Skip to content

Use the query condition cache when a filter is moved to PREWHERE after an early row estimate - #122339

Open
groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:qcc-join-stale-index-analysis
Open

groeneai wants to merge 19 commits into
ClickHouse:masterfrom
groeneai:qcc-join-stale-index-analysis

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Performance Improvement

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

A repeated query now uses the query condition cache for a MergeTree table read under a JOIN, or by parallel replicas sized by parallel_replicas_min_number_of_rows_per_replica, when its filter is moved to PREWHERE (the default), so the second run reads only the granules that can match instead of the whole table.

Description

To pick the join order, the planner asks a MergeTree table how many rows it will read. That index analysis, including the query condition cache lookup, runs while the filter is still a WHERE condition, and it is kept for the real read. The filter is then moved to PREWHERE, and the read stores its result in the cache under the PREWHERE condition, which the kept analysis never looks up, so every run reads the whole table. The parallel_replicas_min_number_of_rows_per_replica estimate does the same, and with parallel replicas the kept analysis is what the coordinator hands out to the replicas.

optimizePrewhere now calls ReadFromMergeTree::applyPrewhereQueryConditionCache right after it moves the condition. It looks the cache up for the new PREWHERE condition and removes the granules it rules out from the kept analysis. No second index analysis runs (IndexAnalysisRounds is unchanged). TopK reads are left as they are. Reads under a masking policy (Cloud only) do not write the cache.

Second run of SELECT count() FROM hits JOIN users ON hits.user_id = users.user_id WHERE hits.duration = 42 on 1M rows: 124 marks before, 2 after, same result. Both new tests fail without the change.

Closes: #134069
Related: #122044
Related: #71028 (comment)


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

groeneai and others added 2 commits September 25, 2026 18:52
…x analysis

With a JOIN over a `MergeTree` table, join-order estimation asks the read step for a row
count, which runs and memoizes `selectRangesToRead` while `query_info.prewhere_info` is
still null. Its query condition cache probe therefore takes the `filter_actions_dag`
branch and keys on the WHERE-derived condition. `optimizePrewhere` then installs the
moved-down predicate through `updatePrewhereInfo`, which left that verdict in place, and
nothing probes the cache again, while the reader writes its entry under the PREWHERE
key. The entry is written, is correct, and is never consulted, so a repeated query
prunes nothing. Both `optimize_move_to_prewhere` and `query_plan_optimize_prewhere` are
on by default, so this is the default path.

Apply the verdict for the new PREWHERE to the ranges the memoized analysis already
selected, by calling the same probe the analysis uses on a copy of `parts_with_ranges`,
and refresh the five fields that are by definition derived from those ranges:
`selected_parts`, `selected_ranges`, `selected_marks`, `selected_rows` and
`has_exact_ranges`. The probe indexes its verdict by absolute mark number per part and
only ever removes marks, and every mark it removes is one the cache recorded as
containing no row matching the condition, so applying it to the already-selected ranges
cannot change the query's result. Applying it to a narrower input can drop marks a full
re-analysis would have kept, never the reverse. `total_parts`, `total_marks_pk` and
`index_stats` are kept, so `SelectedMarksTotal` keeps describing the table and the
comparison of `SelectedMarks` against it stays the observable statement that pruning
happened.

The WHERE verdict is already in the memo, so the probe is handed a copy of `query_info`
with the filter DAG cleared and consults only the new PREWHERE. One logical
consultation then reports one event: without this, a read that now prunes perfectly
also reports a cache miss for the condition it had already applied.

Discarding the memo instead would be simpler, and is what the first version of this
change did, but it costs a full second index analysis: measured +25% CPU on a 300-part
table, paid by every cache-eligible join read at default settings and paid in full
exactly when the cache has least to offer. This shape adds no analysis pass, so
`ProfileEvents['IndexAnalysisRounds']` is unchanged, which the test pins, and a
difference-in-differences benchmark over 300 runs per cell with the binaries crossed
over puts the remaining cost at -3.4% and +0.6% of query CPU.

The gate mirrors the two soundness conditions the probe cannot check for itself, a
unique key and a filter over a non-deterministic virtual column, whose key of table,
part and condition cannot express either. Reads that take part in parallel replicas
are excluded: a coordinator-driven read must keep the ranges the coordinator assigned,
and the remaining shapes are left to the analysis that already handles them.
Everything the probe self-gates on is hoisted into the same condition through
`canFilterPartsByQueryConditionCache`, so a read the cache cannot serve returns before
any ranges are copied.

Second run of a repeated query on the fixture from issue ClickHouse#122044: 8,639,765 -> 311,335
rows and 1056 -> 39 granules, with identical results. On a 500k single-part fixture:
500,001 -> 8,193 rows and 62 -> 2 granules.

Related: ClickHouse#122044
Drop the design narration from the new comments in updatePrewhereInfo and on canFilterPartsByQueryConditionCache; keep the reason for the unique-key and non-deterministic-virtual exclusions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 25, 2026
@groeneai

groeneai commented Sep 25, 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; 8 findings across my own cold pass
and the gate, all fixed; the delta recheck of the fix round raised 0 new findings; bounded: 1 full
pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ A read the cache cannot serve still copied the whole selected range set, because the probe's eligibility conditions were checked inside it, after the copy AGREE, fixed @ 96d290d Eligibility split into one shared predicate, canFilterPartsByQueryConditionCache, checked before the copy
2 ⚠️ The new probe re-consulted the WHERE condition the memoized analysis had already applied, counting a second QueryConditionCacheMisses for one consultation AGREE, fixed @ 96d290d The probe sees only the new PREWHERE; the test pins one hit and one miss on the second run
3 ⚠️ The test asserted only that some granule was pruned, and did not pin the single-index-analysis property that decided this design AGREE, fixed @ 96d290d Pruning must be at least 4x; IndexAnalysisRounds is pinned after 20 randomized runs showed it constant
4 ⚠️ The commit message justified the change by commutativity of range intersection; the probe's small-gap merge depends on the input ranges AGREE, fixed @ 96d290d Restated as a soundness claim: the probe only removes granules the cache recorded as matching no row
5 ⚠️ The commit message said only coordinator-driven parallel-replica reads are excluded; the gate excludes every read taking part in parallel replicas AGREE, fixed @ 96d290d Wording corrected; the gate is deliberately left conservative
6 💡 The in-diff comment described two gate conditions where five are written beneath it AGREE, fixed @ 96d290d Rewritten, then trimmed at publish to the reason for the unique-key and non-deterministic-virtual exclusions only
7 💡 has_exact_ranges is derived like the refreshed counters but was left stale AGREE, fixed @ 96d290d Refreshed with them
8 💡 The Related link sat inside the template's HTML comment and would not render AGREE, fixed @ 96d290d A visible Related line added

Noted, not blocking:

  • EXPLAIN indexes = 1 does not attribute this narrowing, because index_stats is kept as index analysis produced it; SelectedMarks in system.query_log does show it.
  • The SelectQueryInfo copy handed to the probe is taken before the gate, so it also runs for reads without a memoized analysis. It happens at plan time and costs a few refcounts.
  • The commit message's "never the reverse" holds for one probe applied to nested inputs. A full re-analysis runs the cache before the primary key and in the other key order, so that sentence compares the two; correctness does not rest on it.

Fold of the parallel-replicas case (2026-09-29): my own cold pass (1 finding) plus the independent model
(3 findings) on the master merge, the refresh admitted for the initiator's local parallel-replicas read, a
masking-policy exclusion at both consult sites, one new test and one new arm. The delta recheck of the fix
round raised 0 new findings.

# Sev Finding Verdict Evidence / action
9 ❌ A read under a masking policy (Cloud build) consults verdicts computed on stored values, in the new refresh and in the existing analysis consult AGREE, fixed @ 679e801 Both consult sites exclude such reads, as statistics and sparsity pruning already do (e258bd9, b724707)
10 ⚠️ The tests pin marks only as a 4x relation AGREE, fixed @ 41f38ce The cold run must read every mark, the warm run at most the matching granule, the one of dim, and on a compact part the next granule
11 ⚠️ A JOIN read by parallel replicas is claimed but not covered by a committed arm AGREE, fixed @ 41f38ce New arm in 05257 with a ParallelReplicasUsedCount witness, red without the change
12 ⚠️ parallel_replicas_local_plan = 0 is not covered DISAGREE With local_plan = 0 there is no initiator read; every coordinated read is a follower read, which stays excluded, so behaviour is unchanged (identical results on both binaries across the parallel-replicas suites)
13 💡 The follower-exclusion comment gave a reason that does not hold AGREE, fixed @ 679e801 Comment removed; a replica is only ever assigned parts it announced

Noted, not blocking:

  • On a compact part read in blocks of one to two granules, the cold run does not record the granule after the match (master too), so the warm-run bound allows that one extra granule.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20260925-202800 (fold: cron:clickhouse-review-slot-11:20260929-010700)

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, two fixtures: the reporter's from #122044 (8.64M rows) and a 500k single-part one. Every run reproduced; nothing probabilistic.
b Root cause explained? Join-order estimation memoizes selectRangesToRead() while prewhere_info is null, so the cache probe uses the WHERE-derived key; updatePrewhereInfo then replaces the PREWHERE without refreshing that verdict, while the reader writes under the PREWHERE key.
c Fix matches root cause? Yes: only the stale part of the memo (the cache verdict, the one part that depends on PREWHERE) is re-derived, at the moment the PREWHERE changes, and only for the new PREWHERE, since the memo already holds the WHERE verdict. No widened bound, no no-random-* tag, no shrunk dataset, no guard at the symptom.
d Test intent preserved / new tests added? One new stateless test: 20/20 red on master, every time on arm 1 only (run 2's hit and pruning, run 1's lookup count), both control arms green; 100/100 green on the fix. It also pins the index-analysis count, so a fix that re-analyzes the read fails it. No existing test edited.
e Both directions demonstrated? Yes, both binaries against the same data directory, swapped sequentially: 8,639,765 to 311,335 rows and 1056 to 39 granules (27.7x); 500,001 to 8,193 rows and 62 to 2 granules (61x). Results identical in every arm.
f Fix is general across code paths? updatePrewhereInfo is the only site that replaces a MergeTree read's PREWHERE after analysis; all three callers that install one route through it, and each call applies the then-current verdict to the then-current ranges. The other updatePrewhereInfo overrides memoize no index analysis. The eligibility test has one definition, shared with the probe.
g Fix generalizes across inputs (params/datatypes/wrappers)? No type dispatch exists in the change (mark ranges and cache keys only), so type wrappers cannot reach it. The settings matrix, which is the real axis, is measured in full: both PREWHERE settings in all four combinations, join runtime filters on and off, join-order estimation on and off, cache on and off.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no cache key, format or on-disk change. A read the cache cannot serve skips the new block before any ranges are copied, and a read with no verdict keeps the memo as it was.
i Invariants and contracts preserved? The probe only removes marks, each one the cache recorded as holding no matching row, so the query's result cannot change. total_marks_pk and index_stats are kept, so SelectedMarksTotal still describes the table. No shared state is mutated (ranges copied, new AnalysisResult via the existing copy constructor). split_parts is filled later in the pipeline. Sampling is never re-derived. The memo is replaced only after the probe returns, so an exception leaves it untouched.

Session id: cron:clickhouse-impl-self-slot-57:20260925-181951

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fb5dc09]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 5/6) ERROR

AI Review

Summary

Reviewed fb5dc090a8de5f8882c6e9aef3e8f8ce21745f68. The change consults the query condition cache after a filter moves to PREWHERE, narrowing memoized ranges without repeating index analysis, and prevents masked reads from writing shared cache entries. No actionable blockers or majors remain. The latest commit addresses the prior disabled-cache copying finding; that thread is now resolved. Leaving TopK behavior unchanged is an accepted scope decision. Both new regression tests pass in the head commit's Fast test report, and the PR provides before/after pruning measurements.

Missing context / blind spots
  • ⚠️ Cloud-only masking-policy behavior was reviewed statically; this checkout cannot exercise it. A Cloud regression covering masked and unmasked users sharing the same predicate would close that validation gap. No local build or tests were run.
Final Verdict

✅ Approve. No new inline findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 25, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 25, 2026
…analysis

The test server profile sets `max_rows_to_read`. Under a row limit that throws, join-order
estimation analyzes the read without memoizing the result, so the read is analyzed again after
`optimizePrewhere` installs the PREWHERE, and that analysis already probes the cache under the
PREWHERE key. Base and fix then print the same values, two index analyses per table and one more
cache miss per run, which is what Fast test reported. Pin the default of no limit, which is the
path the fix changes.

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

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

This PR changes query condition cache handling: it checks the cache again once PREWHERE is chosen after join reordering, and turns the cache off for tables with masking policies. None of the flagged queries is a plausible beneficiary. ClickBench Q33/Q34 are unfiltered GROUP BYs that never use the cache, TPC-H Q1 has no join, and TPC-H Q7's shipdate filter matches rows in nearly every granule, so all four improvements (-13.8%, -13.5%, -18.5%, -24.7%) are downgraded to not sure. In each case the base run sat at the slow edge of master's normal range and the PR run falls inside it. The ClickBench Q31 slowdown (+14.9%) stays within master's normal range with slightly lower CPU time, and I see no reason to challenge that.

clickbench

⚠️ 3 inconclusive

Flagged queries (3 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 31 not_sure 269 309 +14.9% <0.0001 Single-table read whose filter key does not change with this PR, and CPU time fell from 2831.6 to 2733.2 ms. The +14.9% wall-clock delta stays inside master's normal range, so it is not attributed to this PR.
⚠️ 33 not_sure 1153 994 -13.8% <0.0001 aggregation: This is a large GROUP BY with no WHERE, so the query condition cache this PR changes is never consulted. The -13.8% sits inside master's normal range, and this query's history is noisy.
⚠️ 34 not_sure 1148 994 -13.5% <0.0001 aggregation: Same unfiltered GROUP BY shape as Q33, so the query condition cache path is never used. The -13.5% sits inside master's normal range, and this query's history is noisy.

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 Single-table scan with no join, so the new PREWHERE re-probe after join reordering does not run. The shipdate filter keeps almost every granule anyway, and 53 ms is inside master's range.
⚠️ 7 not_sure 81 61 -24.7% <0.0001 join_operator: This join query does reach the new PREWHERE cache re-probe. But its two-year shipdate filter matches rows in nearly every granule, so there is little to skip. The new 61 ms median is inside master's range.

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: 502601f7-c98f-49ea-93ea-40e0065b4807
  • MIRAI run: e962503e-d818-4f69-80d8-9f20df9fcf07
  • PR check IDs:
    • clickbench_1164540_1791855279
    • clickbench_1164546_1791855279
    • clickbench_1164552_1791855279
    • tpch_adapted_1_official_1164563_1791855279
    • tpch_adapted_1_official_1164575_1791855279
    • tpch_adapted_1_official_1164610_1791855279

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fb5dc090a with master ad36c6520 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cb8da84

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
Performance Comparison (amd_release, master_head, 3/6) / to_valid_utf8 #5 dashboard confirmed_regression, client_time 0.0084 -> 0.0099 (+17.3%). The shard's own report does not flag it (2 too long only, the query is OK there), so the dashboard verdict alone made the shard red. The query runs toValidUTF8 over numbers(100000), so it never reads a MergeTree table and never reaches the ReadFromMergeTree / MergeTreeDataSelectExecutor code this PR changes ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, where @ fm4v handles these verdicts after #121847, which is present in the tested tree a191ddca60ca. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 6/6) / cryptographic_hashes #18 same class: dashboard confirmed_regression, client_time 0.1097 -> 0.1753 (+59.6%), while the shard's own report does not flag the query (1 too long only). It runs a hash function over numbers() / numbers_mt(), with no MergeTree read either ClickHouse/performance-comparison#5 (external, open), the same owner as the row above
Mergeable Check, PR rollups, red only because of the two shards above ClickHouse/performance-comparison#5 (external, open)
Sync - CH Inc sync (private, not actionable by me)

All other check runs completed (136 pass, 35 not selected, 4 red), Finish Workflow is green and
CH Inc sync is still pending. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20260926-063421

@rschu1ze

Copy link
Copy Markdown
Member

@shankar-iyer Another fix in the query condition cache area :-( If you have time, like to check? Thanks.

groeneai and others added 5 commits September 28, 2026 21:02
Master's ClickHouse#114659 and ClickHouse#117968 added the `allow_top_k_prewhere_query_condition_cache` parameter and the pending-TopK `prewhere_info_for_cache` to `filterPartsByQueryConditionCache`, which the textual merge spliced into the extracted `canFilterPartsByQueryConditionCache`, so it did not compile. Resolved by keeping master's `filterPartsByQueryConditionCache` behind the eligibility helper, which now counts a pending TopK filter as a PREWHERE, and by keeping TopK reads out of the refresh in `updatePrewhereInfo`, whose probe does not carry the post-PREWHERE filter that a TopK PREWHERE entry is keyed on.

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

`updatePrewhereInfo` probes the query condition cache for a PREWHERE installed after the read was analyzed, but it skipped every read that takes part in parallel replicas. That also excluded the initiator's local read, which reuses the analysis made before the condition moved to PREWHERE, by the `parallel_replicas_min_number_of_rows_per_replica` estimate or by join reordering. With `parallel_replicas_index_analysis_only_on_coordinator` that analysis is the snapshot replica's announcement, so a repeated query read the unpruned ranges on every replica (`04249_query_condition_cache_fine_grained_granules`: 100 marks instead of 1 on the warm run). Only a follower's read is excluded now, because it must keep every part the coordinator may assign to it.

Found while investigating `04249_query_condition_cache_fine_grained_granules` on ClickHouse#71028, in the reruns of this job:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=71028&sha=ccaacd566915d761c4f0e4a722eb36956ab147ad&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A masking policy rewrites, for the querying user only, the values a read
returns. It is appended to the part's alter conversions at read time, which
the mutations snapshot does not see, so the existing exclusion of reads with
on-the-fly mutations never fires for it, while the cached verdicts are
computed on the stored values: a masked read could skip granules whose
masked values match. Exclude such reads at both places that consult the
cache, the index analysis in `selectRangesToRead` and the refresh in
`updatePrewhereInfo`. The write side already skips them, because a masked
column the query reads produces on-the-fly mutation steps.

Statistics pruning and the sparsity statistics use the same gate
(b724707, e258bd9). `hasEnabledMaskingPolicies` is constant
false outside the Cloud build.

Also drop the comment on the follower exclusion in the refresh: its reason
did not hold, since a replica is only assigned parts it announced. Follower
reads are left as they were.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…N read by parallel replicas

The tests checked the marks a warm run reads only as a fraction of the table
(`SelectedMarks * 4 < SelectedMarksTotal`), which still passes when the cache
prunes only three quarters of the granules. Assert instead that the cold run
reads every mark and that the warm run reads at most the matching granule,
the one of the joined table and, on a compact part, sometimes the next
granule: a compact part read in blocks of more than one and at most two
granules leaves the granule after the matching one unrecorded.

The control without a JOIN now reads `k` too, so its condition moves to
PREWHERE as in the other arms. As a WHERE filter it records whole read
blocks, whose size follows `max_block_size`.

05257 gains an arm for a JOIN read by parallel replicas. Without a row
estimate, join reordering inside the local plan is the only analysis made
before PREWHERE, a different producer than the estimate 05292 covers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the TopK exclusion's comment into the one above the gate, shorten that one to two lines, and drop the doc comment of canFilterPartsByQueryConditionCache, which restated its name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Use the query condition cache in joins when the filter is moved to PREWHERE Use the query condition cache when a filter is moved to PREWHERE after an early row estimate Sep 29, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Sep 29, 2026
@groeneai
groeneai requested a review from nickitat September 29, 2026 01:56
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fd1999d

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
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) / 05325_iceberg_mixed_format_top_k_dynamic_filtering flaky, not from this PR (54 of 54 reruns pass): the output is correct, but the sinks of a parallel INSERT race for the same Iceberg metadata version and Iceberg::writeMetadataFile logs the lost conditional write at Error (v3.metadata.json already exists ... FILE_ALREADY_EXISTS), so the test fails on stderr. This PR does not touch the Iceberg write path. 6 PRs and 1 master run show it in 30 days #125026 (mine, open)
Mergeable Check, PR praktika rollups of the row above #125026 (mine, open)

Session id: cron:our-pr-ci-monitor:20261010-230007

fm4v added 2 commits October 12, 2026 22:35
…e-probe a restored PREWHERE

Masked reads now neither read nor write the cache (`selectRangesToRead` and `initializePipeline`). `updatePrewhereInfo` remembers the PREWHERE it probed, so the clear/restore in the text index optimization does not double `QueryConditionCacheHits`/`QueryConditionCacheMisses`.
groeneai and others added 2 commits October 12, 2026 23:06
…amic filter

`updatePrewhereInfo` skipped every TopK-stamped read, so a repeated
`ORDER BY ... LIMIT` query whose condition moves from WHERE to PREWHERE
kept the stale verdict of the memoized analysis in the JOIN and
parallel-replicas cases this PR fixes. The warm run read 61/61 marks under
`parallel_replicas_min_number_of_rows_per_replica = 1` and 62/62 under a
reordered JOIN, against 1 and 2 marks for the same queries without
`ORDER BY ... LIMIT`.

The refresh now probes a TopK read while its `__topKFilter` is still
pending: the cache then consults the PREWHERE with the filter merged in and
salts it with the TopK plan and the WHERE, which is what the reader writes
under. To keep the WHERE for that salt, `filterPartsByQueryConditionCache`
gets `consult_where` instead of the refresh clearing `filter_actions_dag`.
The call from `installTopKDynamicFilter` is not probed: it installs the
PREWHERE that the pending probe already used, so probing it would only
count the cache twice (the plain TopK path keeps 2 misses, then 1 hit and
1 miss).

Warm runs now read 1 mark (parallel replicas) and 2 marks (JOIN).
05257 and 05292 gain a TopK arm each; both arms are red on 616d785
(0 hits, every mark read) and green with this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`query_condition_cache_probed_prewhere` was set only by a probe in
`updatePrewhereInfo`, so the text-index clear/restore of an explicit
PREWHERE looked the restored PREWHERE up again although the memoized
analysis already carried its verdict. With an explicit PREWHERE on a table
with a text index and `parallel_replicas_min_number_of_rows_per_replica = 1`
that was 3 misses and 3 hits where master has 2 and 2; now it is 2 and 2.
Until the first probe, the guard now holds the PREWHERE the read had when
its analysis was memoized.

The TopK arms of 05257 and 05292 now also check the miss count and
`IndexAnalysisRounds`, and 05292's arm anchors the `__topKFilter` PREWHERE
in the plan, so a lost TopK stamp or an extra WHERE lookup turns them red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
groeneai and others added 3 commits October 13, 2026 01:49
…d after index analysis

`tryOptimizeGroupByTopK` installed the `__topKFilter` PREWHERE before stamping the read with
`setTopKColumn`, so when the read already had a memoized analysis (e.g. from evaluating an
aggregate projection that was then rejected), the refresh in `updatePrewhereInfo` looked the
new PREWHERE up without the TopK salt. No entry is ever written under that key, so the lookup
was a wasted miss, and the warm query still read every mark the primary key selects.

The read is now stamped first, and `updatePrewhereInfo` also refreshes a non-pending TopK read
whose analysis predates the stamp. A pending read keeps skipping the install call, whose
PREWHERE the pending probe already used.

Measured on a 500k-row table with a rejected aggregate projection, warm
`SELECT w, count() ... WHERE k < 100000 AND v > 5 GROUP BY w ORDER BY w LIMIT 3`: 13 marks and
1 hit before (master too), 8 marks and 2 hits after, the same as without the projection.

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

The warm run prints its rows, which equal those of the query without the cache,
reads the same marks as the arm without the projection, and does not add an index analysis.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1d0782e

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
Fast test / 04902_access_entity_map_setting_round_trip not from this PR (it changes query condition cache lookups in ReadFromMergeTree): clickhouse-local did not exit within the 60 s test timeout after CREATE SETTINGS PROFILE on an on-disk access storage, the one-minute shutdown delay of DiskAccessStorage. It failed the same way on 2 other PRs in the last 7 days #118099 (mine, open)
Mergeable Check, PR praktika rollups: the Fast test failure dropped the remaining 110 jobs #118099 (mine, open)

The Fast test failure dropped the remaining jobs, so this head has no other test signal yet. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261013-110003

@rschu1ze

rschu1ze commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

@groeneai:

Join-order estimation and the parallel_replicas_min_number_of_rows_per_replica estimate both run and memoize selectRangesToRead while prewhere_info is still null, so its query condition cache probe uses the WHERE key. optimizePrewhere then installs the moved-down condition through updatePrewhereInfo, nothing probes the PREWHERE key the reader writes, and a repeated query prunes nothing. With parallel replicas, the initiator's local read reuses that analysis as the coordinator's announcement, so every replica reads the unpruned ranges.

updatePrewhereInfo now applies the verdict for the new PREWHERE to the ranges the memoized analysis selected, using the analysis' own probe, and refreshes the fields derived from them. This adds no index analysis (IndexAnalysisRounds is unchanged); discarding the memo instead costs +25% CPU on a 300-part table, and a crossed-over benchmark puts this change at -3.4% and +0.6% of query CPU.

Please explain in simple plain English

  • What problem does this PR solve? Give a SQL example.
  • How does it solve it?

Make the least introsive and most minimal fix. We currently add member variables query_condition_cache_probed_prewhere and query_condition_cache_analysis_before_top_k to generic code and I think we can do without them.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

What problem does this PR solve?

The query condition cache remembers, per part, which granules have no row matching a filter, so a repeated query can skip them. When the table is read under a JOIN, this never works: the second run reads everything again.

CREATE TABLE hits (id UInt64, user_id UInt64, duration UInt64) ENGINE = MergeTree ORDER BY id;
INSERT INTO hits SELECT number, number % 1000, number FROM numbers(1000000);
CREATE TABLE users (user_id UInt64, name String) ENGINE = MergeTree ORDER BY user_id;
INSERT INTO users SELECT number, toString(number) FROM numbers(1000);

-- run it twice
SELECT count() FROM hits JOIN users ON hits.user_id = users.user_id WHERE hits.duration = 42;

On today's master, SelectedMarks is 124 on both runs, with 0 cache hits. Without the JOIN, SELECT count() FROM hits WHERE duration = 42 goes from 123 marks to 8 on the second run.

Why: to pick the join order, the planner asks hits how many rows it will read. That runs the index analysis, including the cache lookup, while duration = 42 is still a WHERE condition, and the result is kept for the real read. Then the condition is moved to PREWHERE. The read stores its result in the cache under the PREWHERE condition, but the kept analysis only looked up the WHERE condition, so every run misses. The parallel_replicas_min_number_of_rows_per_replica estimate does the same thing.

How does it solve it?

When the condition is moved to PREWHERE and the read already has a kept analysis, the read looks up the cache once for the new PREWHERE condition and removes the granules it rules out from the kept ranges. No second index analysis runs.

Making it minimal

Agreed, I'm reducing the change to that. The lookup will be called from optimizePrewhere, right after it moves the condition, instead of from updatePrewhereInfo, which the text index and TopK optimizations also call. That removes both member variables, the consult_where parameter, canFilterPartsByQueryConditionCache and the reordering in optimizeGroupByTopK. TopK reads stay as they are on master. I'll push it here once it is tested.

groeneai and others added 2 commits November 9, 2026 10:14
…zePrewhere

Reduce the fix to its core, as asked in review. An analysis memoized before
optimizePrewhere moves a WHERE condition to PREWHERE (join order estimation, the
parallel_replicas_min_number_of_rows_per_replica estimate) looked the query
condition cache up for the WHERE condition only, while the read records its
verdict under the PREWHERE condition. optimizePrewhere now calls
ReadFromMergeTree::applyPrewhereQueryConditionCache right after installing the
PREWHERE, which looks the cache up for that PREWHERE and narrows the memoized
ranges, without a second index analysis.

Calling it from optimizePrewhere instead of updatePrewhereInfo means the text
index clear/restore and the TopK filter installs never look the cache up again,
so the members query_condition_cache_probed_prewhere and
query_condition_cache_analysis_before_top_k, the consult_where parameter,
canFilterPartsByQueryConditionCache and the reordering in optimizeGroupByTopK
are gone. TopK reads are left out (their PREWHERE key also hashes the WHERE
condition, which this lookup drops) and keep master's behaviour; the TopK test
cases are removed with them. The masking policy write gate stays.

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

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed the minimal version in fccd0e7, plus a master merge (227c68a) because the branch had conflicts.

The fix is now one method, ReadFromMergeTree::applyPrewhereQueryConditionCache, called from optimizePrewhere right after it moves the condition. There are no new member variables, and MergeTreeDataSelectExecutor and optimizeGroupByTopK are unchanged from master. On the SQL example above, the second run reads 2 marks instead of 124, and IndexAnalysisRounds stays the same. The masking-policy lines are @ fm4v's write gate, kept as he pushed them.

…ache is disabled

`applyPrewhereQueryConditionCache` copied the memoized analysis and recounted
its ranges even with `use_query_condition_cache = 0`, where
`filterPartsByQueryConditionCache` returns at once. Return before the copy.

Measured on a debug build, a JOIN over a 3000-part table with the condition
moved to PREWHERE: 0.61% of planning CPU samples were in this method with the
cache disabled, 0 after the change. With the cache enabled the lookup count is
unchanged (6000 misses, IndexAnalysisRounds 2).

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

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fb5dc09

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
Performance Comparison (amd_release, master_head, 5/6) infra, not from this PR (it changes only the query condition cache refresh in ReadFromMergeTree and optimizePrewhere): the shard ran all 142 of its tests between 16:20 and 17:57 and was then killed by the 7200 s job timeout while computing its report. The same shard ran into the same 2-hour limit on master at eb580cb and b1b6e83 in the last 24 hours #129176 (mine, open)
Mergeable Check, PR praktika rollups of the row above #129176 (the owner above)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261109-183010

This branch has not been deployed

No deployments
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-performance Pull request with some performance improvements

Projects

None yet

5 participants