Repository navigation
Key skip-index query condition cache entries by the skip indexes that ran - #108548
shankar-iyer merged 10 commits into
Conversation
The query condition cache stores, per {table uuid, part name, WHERE hash},
which marks can match a predicate. That verdict depends on whether skip
indexes ran during index analysis, but the cache key does not encode it.
The read gate filterPartsByQueryConditionCache did not check use_skip_indexes,
so a query with use_skip_indexes = 0 could consult a verdict produced with a
skip index.
When a skip index legitimately diverges from the row-level predicate (a text
index with a preprocessor, e.g. replaceAll(s, ' ', '') indexes 'a b' as token
'ab'), the cached exclusion is a false negative at the row level. A first query
at use_skip_indexes_on_data_read = 0 persists that exclusion under the WHERE
hash; a later use_skip_indexes = 0 query then dropped a granule it should have
kept and returned a wrong result.
Fix: do not consult the cache when use_skip_indexes = 0. The write side is
unchanged: an entry written with skip indexes off is the pure row-level
matching set, and one written with them on is now only read with them on.
Closes ClickHouse#108519.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-8:20260625-200200 |
|
cc @rschu1ze @CurtizJ — could you review this? The query condition cache read gate ( |
|
Workflow [PR], commit [170cf5a] Summary: ✅
AI ReviewSummaryThis PR rekeys skip-index-derived Final Verdict✅ No new findings on the current PR head. |
|
@groeneai The fix needs a revisit because of the implications. Now we silently couple two orthogonal settngs, |
…es is set The read gate added in this PR only checked the global use_skip_indexes setting. ignore_data_skipping_indices disables named indices while buildIndexes keeps use_skip_indexes true (ReadFromMergeTree.cpp), so a query that ignored an index could still consult a skip-index-derived verdict for that index in the query condition cache and reuse a false negative, returning the same wrong result this PR fixes. Bypass the query condition cache read whenever ignore_data_skipping_indices is changed, mirroring buildIndexes' own gate. Extend the regression test with that scenario. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@shankar-iyer You are right, and I will hold the fix here as you asked. Note on sequencing: I pushed a small commit (fdd8e2e) a few minutes ago that extends the same read-side gate to ignore_data_skipping_indices, in reply to the bot review above. I had not seen your comment yet when I pushed it. I will make no further changes until you decide on the direction below, and I am happy to redo it entirely if we move off the read-side approach. Agreed that use_skip_indexes and the QCC are orthogonal. My read-side gate is too broad: it suppresses every QCC consult when use_skip_indexes=0, including the sound, data-driven entries, which breaks the pure-QCC learned-index case you describe. The poisoning comes from only one of the four write paths: the skip-index analysis write in ReadFromMergeTree (the excluded-ranges diff), which can legitimately diverge from the row-level predicate (text index with a preprocessor). The other three writes are row-level and always sound: FilterTransform (WHERE), MergeTreeSelectProcessor (PREWHERE unmatched marks), and StorageObjectStorageSource. The Key is {table_uuid, part_name, condition_hash} with condition_hash = WHERE-DAG output hash only, so the read side cannot tell a skip-index-derived entry from a row-level one. So I think the correct fix is write-side or provenance-based, not a read-side use_skip_indexes block:
I lean towards option 1 as the minimal correctness fix and option 2 as the follow-up if we want to keep caching skip-index exclusions. What is your preference? I will not touch the fix until you decide. |
I think we will have to do 2. Imagine a |
|
Thanks, going with option 2. Re-explaining the divergence on the regression index One mechanism detail that shapes the fix: all four writers refine the same entry under
I will revert the read-side |
…dex profile Replaces the read-side use_skip_indexes / ignore_data_skipping_indices gates with a profile-keyed approach, per review on PR ClickHouse#108548. The previous gates suppressed every query condition cache read when skip indexes were disabled, which also dropped the sound row-level entries (FilterTransform, MergeTreeSelectProcessor, object storage) and broke the pure-QCC learned-index case (deployments that keep skip indexes off and rely on workload-driven pruning). Now only the skip-index-analysis exclusions (ReadFromMergeTree), which can diverge from the row-level predicate (e.g. a text index with a preprocessor), are stored under a key salted with the effective skip-index profile (use_skip_indexes plus the set of indexes disabled via ignore_data_skipping_indices). Row-level exclusions keep the bare condition hash. The read side consults both keys and merges the verdicts, so a query only consults skip-index entries it could have produced itself, while row-level entries stay readable under any profile and skip-index exclusions are still reused by queries with the same profile. Closes ClickHouse#108519. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed f8e02e2: switched to the profile-keyed approach (option 2). The read-side Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-1:20260629-062000 |
The two-key split (row-level bare hash + skip-index-profiled hash) made filterPartsByQueryConditionCache probe two keys per part, and each QueryConditionCache::read internally incremented QueryConditionCacheHits or QueryConditionCacheMisses, so a single logical consultation emitted up to two events. That doubled the miss counts asserted by 03229_query_condition_cache_profile_events and 04249_query_condition_cache_fine_grained_granules and leaked the internal two-key probing into a user-visible metric. Add an increment_profile_events flag (default true) to QueryConditionCache::read; the two-key read gate passes false on both probes and counts exactly one hit (if either key matched) or one miss per consultation. The events now mean consultations again, not internal key lookups, and both tests pass unchanged. Single-key callers (object storage) keep the default and are unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed 744b696 to fix the two Fast test failures the option-2 commit introduced ( Cause: the two-key read gate calls Fix: Verified on a debug build: both tests match their committed reference (50 runs each with randomization), and the wider query_condition_cache / text_index / skip-index suites still pass (the only local misses need cluster/dataset fixtures my single-node repro lacks). |
|
@groeneai Please check all bot review comments in this PR. |
…exes Address the review on the profile-keyed approach (ClickHouse#108548): the salt was a function of the use_skip_indexes and ignore_data_skipping_indices settings, not of the skip indexes that index analysis actually ran. Three gaps followed: - An async DROP INDEX (a metadata-only change that does not disable the QCC) left the same settings, hence the same key, so a stale skip-index exclusion could be reused after the index was gone. - The ignored-name set was hashed with SipHash::update(std::string), which appends no length delimiter, so {"a","bc"} and {"ab","c"} produced the same key while disabling different indexes. - use_skip_indexes_for_disjunctions, which changes the exclusions the same indexes produce for OR predicates, was not part of the key, so an entry written with it enabled could be consulted by a query that disabled it. getSkipIndexProfiledConditionHash now salts the condition hash with the effective useful skip-index set (each index's definition-AST tree hash, sorted by name and folded as fixed-width values) plus use_skip_indexes and use_skip_indexes_for_disjunctions. The same ReadFromMergeTree::Indexes is passed to both the write side and the read side, so the salt is identical on both. The effective set already reflects ignore_data_skipping_indices and current metadata, so dropping/ignoring/redefining an index changes the key; the fixed-width per-index contribution removes the name-concatenation collision. The regression test gains a different-ignored-set case and a use_skip_indexes_for_disjunctions toggle (asserted via the QueryConditionCacheHits/Misses events, since the text-index false negative also fires at data-read time and masks any row-count difference). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260629-092300 |
|
@shankar-iyer Pushed 586323e, which addresses all three open bot review comments. The earlier option-2 commit keyed skip-index entries by the
The salt is computed by one helper from the same On "when the skip index legitimately diverges from the row-level predicate": the regression index is For the disjunction case the divergence is not visible as a different row count (the per-column text index still filters that granule at data-read time either way), so the regression asserts it through the |
Two follow-ups to the review of the skip-index-profiled query condition cache key, both in 02346_text_index_bug108519_qcc_skip_index. 1. Lock in the "indexes that actually ran" invariant under a pending ALTER MODIFY COLUMN. When a type change is pending on a skip-indexed column, index analysis rejects that index for the part (canUseIndex, via getAllUpdatedColumns, which AlterConversions populates only for a READ_COLUMN whose type is changing). A skip-index exclusion cached earlier, when the index did run, must not be served to a query that no longer runs the index for the part. It is not: the type change that triggers the canUseIndex rejection also changes the bare WHERE condition hash (ActionsDAG::Node::updateHash folds in each node's result_type), hence the profiled key, so the query looks under a different key and gets a clean miss. The new tab_alter case asserts the correct row-level answer (1) rather than the stale skip-index false negative (0). No separate hasAlterMutations() read gate is required for correctness; the test documents and guards the existing behavior. 2. Drop the instance-wide SYSTEM DROP QUERY CONDITION CACHE from the disjunction section. The cache is keyed by (table uuid, part, condition hash) and tab_disj is freshly created, so its entries are already unique to this run. The global clear was unnecessary and made the test race sibling QCC tests in the parallel pool (and could erase entries they assert), so removing it keeps the test parallel-safe without a no-parallel tag.
|
@shankar-iyer the two new bot comments on 586323e are addressed in 2600528 (test-only):
|
The disjunction sub-test added in the previous commit asserts a QueryConditionCacheHits profile event (disj_same_reuses_entry): a populate query writes a skip-index exclusion under the profiled key, and a same-profile query must reuse it. The query condition cache is instance-wide, and several sibling stateless tests (03229_query_condition_cache_*, 04065_join_shard_by_pk_with_qcc, 04275_104781_qcc_*) issue SYSTEM DROP QUERY CONDITION CACHE. When one of them runs in the parallel pool between this test's populate and reuse query, it evicts the entry, so the reuse query misses and disj_same_reuses_entry flips from 1 to 0. That is the flaky check failure on 02346. The whole query condition cache test family already uses no-parallel for this reason (they manipulate the server-global cache). The row-count poisoning assertions in this test are robust to an eviction (they just recompute the correct answer), so the test ran fine in parallel until the hit assertion was added. Add no-parallel to match the family; this only changes scheduling, the test output is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Pushed The flaky check on the prior head failed only on the last assertion: Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260629-114300 |
…on cache key The profiled key salted the condition hash with each useful index's definition_ast tree hash, but ASTIndexDeclaration keeps name and granularity as plain members and does not override updateTreeHashImpl, so neither is part of that tree hash. Two indexes with the same expression and type but a different name (or granularity) therefore produced the same salt and shared a profiled key. That re-opens the stale skip-index exclusion this PR isolates, in the partially-materialized case: with idx_a and idx_b of the same definition, populate while running idx_a (idx_b ignored), then query while running idx_b (idx_a ignored) on a part where idx_b is not built. The two effective sets shared a key, so the second query could read idx_a's exclusion even though it did not run idx_a for the part. Fold each index's name (length-prefixed) and granularity into the salt next to the definition AST hash, computed once from the running set and threaded to both the read and write sides so they match by construction. Extend the regression with a same-definition different-name pair, asserting via the QueryConditionCacheHits profile event that the second set misses the first set's entry while the same set still reuses it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-3:20260629-125900 |
|
@shankar-iyer Pushed f780010, addressing the last open bot blocker (the salt was name- and granularity-blind).
Verified both directions with two same-definition I believe this closes the salt-completeness line of review. Ready for your pass. |
CI finish ledger — f780010Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
The single failing test is the merged-#105591 master regression (deterministic, all configs since 2026-06-29 11:10 UTC), fixed by revert #108812 (merged 14:13 UTC). This branch predated the revert, so I merged current master to pick it up; CI re-runs on bf5c5e7. Session id: cron:our-pr-ci-monitor:20260629-183000 |
CI finish ledger — bf5c5e7Every failure below has an owner. Only
Session id: cron:our-pr-ci-monitor:20260629-233000 |
CI finish ledger — bf5c5e7Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only
(The earlier 02354_vector_search_rescoring failures were on prior heads f780010/74dfd1cf1f56, owned by merged revert #108812 and already picked up by merging master into this branch; they are not present on bf5c5e7.) Session id: cron:our-pr-ci-monitor:20260630-000000 |
…-qcc-skip-index-read-gate # Conflicts: # src/Processors/QueryPlan/ReadFromMergeTree.cpp # src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp
|
Merged current master (1322ce4) to resolve a conflict, pushed 170cf5a. The conflict was in the two QCC read sites that master's new
Mechanical resolution, no logic change to this PR. Rebuilt debug and re-ran the regression (02346_text_index_bug108519_qcc_skip_index): passes on the merged binary. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 76/76 (100.00%) · Uncovered code |
CI finish ledger — 170cf5aCI fully finished on this head (master-conflict merge). Finish Workflow + Mergeable Check both pass; every check green.
No PR-caused failures. The prior chronic hung-check reds seen on superseded head bf5c5e7 are not present on this head. shankar-iyer's option-2 salt direction remains fully addressed (all bot blockers closed). Ready for review. Session id: cron:our-pr-ci-monitor:20260701-170000 |
|
This defensive check can serve us if and if we have lossy skip indexes or skip indexes that are only for retrieving hints` regarding value presence (opposite to bloom filter skip index which can only return false positives) |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRKey skip-index query condition cache entries by the skip indexes that ran ClickGap verified: reproduced it with the script below on Reproduction-- Run against clickhouse-server (the query condition cache is a server-global
-- cache and is NOT retained across queries by clickhouse-local).
SET allow_experimental_full_text_index = 1;
CREATE TABLE tab (s String, INDEX idx s TYPE text(tokenizer = splitByNonAlpha, preprocessor = replaceAll(s, ' ', ''))) ENGINE = MergeTree ORDER BY tuple() SETTINGS index_granularity = 1;
INSERT INTO tab VALUES ('zzz'), ('a b');
-- Populate the cache via the index path (text index with the space-stripping
-- preprocessor indexes 'a b' as token 'ab', a false negative for hasToken(s,'a')):
SELECT count() FROM tab WHERE hasToken(s, 'a') SETTINGS use_query_condition_cache = 1, use_skip_indexes_on_data_read = 0; -- 0
-- Re-run with skip indexes disabled; before the fix this reused the index-derived
-- exclusion and returned 0. Correct answer is 1.
SELECT count() FROM tab WHERE hasToken(s, 'a') SETTINGS use_query_condition_cache = 1, use_skip_indexes = 0; -- was 0 (wrong), correct is 1Bisect
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: ClickGap · Finding: Triage metadata
|
A PR's green CI describes the master of its last run, not of its merge. PR ClickHouse#108548 merged on 2026-07-13 with CI last run on 07-01; on 07-03 master merged ClickHouse#108511, which added materialize_statistics_on_insert to the settings randomizer in tests/clickhouse-test. The PR's new test 02346_text_index_bug108519_qcc_skip_index then failed on master whenever the randomized setting was drawn (~40% of runs) and kept master red for ~7 hours until ClickHouse#110260 pinned auto_statistics_types at the table level. The merge queue already builds the exact merged state (Build (amd_binary)) but ran no stateless tests on it. Add "Stateless tests (amd_binary, flaky check)" to MergeQueueCI: it reruns the PR's new/changed stateless tests on the merge group state (the PR merged with the current master), so a semantic conflict with post-CI master changes bounces the PR from the queue instead of breaking master. The job self-skips when the PR changes no tests. Merge-queue runs use a reduced budget (20 iterations / 20 min instead of 50 iterations / 45 min): the PR CI already ran the full flaky check, and a randomized setting drawn with probability 0.4 per run escapes 20 iterations with probability 0.6^20 ~= 4e-5. Changed-file detection in merge-queue runs now uses the linked PR's paginated files list (PR_NUMBER is 0 there, and the commits API caps a merge commit's file list at 300 entries), and the changed-files fetch fails closed in merge-queue runs so a GitHub API failure cannot silently skip the check. Incident: ClickHouse#108548 Follow-up fix it required: ClickHouse#110260 Co-Authored-By: Claude Fable 5 <[email protected]>
…dex profile Replaces the read-side use_skip_indexes / ignore_data_skipping_indices gates with a profile-keyed approach, per review on PR ClickHouse#108548. The previous gates suppressed every query condition cache read when skip indexes were disabled, which also dropped the sound row-level entries (FilterTransform, MergeTreeSelectProcessor, object storage) and broke the pure-QCC learned-index case (deployments that keep skip indexes off and rely on workload-driven pruning). Now only the skip-index-analysis exclusions (ReadFromMergeTree), which can diverge from the row-level predicate (e.g. a text index with a preprocessor), are stored under a key salted with the effective skip-index profile (use_skip_indexes plus the set of indexes disabled via ignore_data_skipping_indices). Row-level exclusions keep the bare condition hash. The read side consults both keys and merges the verdicts, so a query only consults skip-index entries it could have produced itself, while row-level entries stay readable under any profile and skip-index exclusions are still reused by queries with the same profile. Closes ClickHouse#108519. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…exes Address the review on the profile-keyed approach (ClickHouse#108548): the salt was a function of the use_skip_indexes and ignore_data_skipping_indices settings, not of the skip indexes that index analysis actually ran. Three gaps followed: - An async DROP INDEX (a metadata-only change that does not disable the QCC) left the same settings, hence the same key, so a stale skip-index exclusion could be reused after the index was gone. - The ignored-name set was hashed with SipHash::update(std::string), which appends no length delimiter, so {"a","bc"} and {"ab","c"} produced the same key while disabling different indexes. - use_skip_indexes_for_disjunctions, which changes the exclusions the same indexes produce for OR predicates, was not part of the key, so an entry written with it enabled could be consulted by a query that disabled it. getSkipIndexProfiledConditionHash now salts the condition hash with the effective useful skip-index set (each index's definition-AST tree hash, sorted by name and folded as fixed-width values) plus use_skip_indexes and use_skip_indexes_for_disjunctions. The same ReadFromMergeTree::Indexes is passed to both the write side and the read side, so the salt is identical on both. The effective set already reflects ignore_data_skipping_indices and current metadata, so dropping/ignoring/redefining an index changes the key; the fixed-width per-index contribution removes the name-concatenation collision. The regression test gains a different-ignored-set case and a use_skip_indexes_for_disjunctions toggle (asserted via the QueryConditionCacheHits/Misses events, since the text-index false negative also fires at data-read time and masks any row-count difference). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…9-qcc-skip-index-read-gate Key skip-index query condition cache entries by the skip indexes that ran
A PR's green CI describes the master of its last run, not of its merge. PR ClickHouse#108548 merged on 2026-07-13 with CI last run on 07-01; on 07-03 master merged ClickHouse#108511, which added materialize_statistics_on_insert to the settings randomizer in tests/clickhouse-test. The PR's new test 02346_text_index_bug108519_qcc_skip_index then failed on master whenever the randomized setting was drawn (~40% of runs) and kept master red for ~7 hours until ClickHouse#110260 pinned auto_statistics_types at the table level. The merge queue already builds the exact merged state (Build (amd_binary)) but ran no stateless tests on it. Add "Stateless tests (amd_binary, flaky check)" to MergeQueueCI: it reruns the PR's new/changed stateless tests on the merge group state (the PR merged with the current master), so a semantic conflict with post-CI master changes bounces the PR from the queue instead of breaking master. The job self-skips when the PR changes no tests. Merge-queue runs use a reduced budget (20 iterations / 20 min instead of 50 iterations / 45 min): the PR CI already ran the full flaky check, and a randomized setting drawn with probability 0.4 per run escapes 20 iterations with probability 0.6^20 ~= 4e-5. Changed-file detection in merge-queue runs now uses the linked PR's paginated files list (PR_NUMBER is 0 there, and the commits API caps a merge commit's file list at 300 entries), and the changed-files fetch fails closed in merge-queue runs so a GitHub API failure cannot silently skip the check. Incident: ClickHouse#108548 Follow-up fix it required: ClickHouse#110260 Co-Authored-By: Claude Fable 5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results when the query condition cache (
use_query_condition_cache = 1) reused a skip-index-derived mark exclusion for a query that ran a different set of skip indexes, for example withuse_skip_indexes = 0,ignore_data_skipping_indices, or a differentuse_skip_indexes_for_disjunctionsmode. Skip-index-derived cache entries are now keyed by the effective set of skip indexes that ran, while row-level query-condition-cache entries stay reusable across all of these.Description
Closes #108519.
The query condition cache (QCC) stores, per
{table uuid, part name, WHERE-condition hash}, which marks can match a predicate. Four writers refine the same entry: three row-level ones (FilterTransform for WHERE, MergeTreeSelectProcessor for PREWHERE, and object storage) that are always sound, and the skip-index-analysis writer inReadFromMergeTree, whose exclusions can legitimately diverge from the row-level predicate.The clearest divergence is a text index with a preprocessor: with
preprocessor = replaceAll(s, ' ', '')the row'a b'is indexed as the single tokenab, so the index does not matchhasToken(s, 'a')even though the row does. The index verdict is correct for the preprocessed token stream and a false negative for the raw row. Because the key did not encode whether (or which) skip indexes ran, a later query that disabled or ignored that index consulted the index-derived exclusion and dropped a granule it should have kept, returning 0 instead of 1.Fix: skip-index-derived entries are written under a key salted with the effective skip-index profile that index analysis ran, computed by
MergeTreeDataSelectExecutor::getSkipIndexProfiledConditionHash:buildIndexesalready excludes indexes listed inignore_data_skipping_indicesor absent from metadata);use_skip_indexes;use_skip_indexes_for_disjunctions, which changes the exclusions the same indexes produce for OR predicates.Row-level writers keep the bare WHERE-hash key, so a query with
use_skip_indexes = 0still reuses row-level entries (the pure query-condition-cache learned-index case) and a same-profile query still reuses its cached skip-index exclusions, avoiding re-evaluation of the skip index. The read side consults both keys and merges the verdicts. The sameIndexesis passed to the write and read sites, so the salt is identical on both.Reproducer (deterministic, master defaults plus
use_skip_indexes_on_data_read = 0):This is a distinct facet of query-condition-cache poisoning from the mutation case fixed in #107145, which deliberately gated only on mutations and not on skip indexes; the text-index-plus-preprocessor false negative above is a counterexample to that carve-out for the read side.
Regression test:
tests/queries/0_stateless/02346_text_index_bug108519_qcc_skip_index.sql.Version info
26.7.1.848(included in26.7and later)