Skip to content

Key skip-index query condition cache entries by the skip indexes that ran - #108548

Merged
shankar-iyer merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-108519-qcc-skip-index-read-gate
Jul 13, 2026
Merged

shankar-iyer merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-108519-qcc-skip-index-read-gate

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 with use_skip_indexes = 0, ignore_data_skipping_indices, or a different use_skip_indexes_for_disjunctions mode. 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 in ReadFromMergeTree, 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 token ab, so the index does not match hasToken(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:

  • the effective set of useful skip indexes, each contributing the tree hash of its full definition AST (so a dropped, ignored, or redefined index changes the key, and buildIndexes already excludes indexes listed in ignore_data_skipping_indices or 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 = 0 still 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 same Indexes is 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):

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');
SELECT count() FROM tab WHERE hasToken(s, 'a') SETTINGS use_skip_indexes_on_data_read = 0;   -- 0, populates the cache
SELECT count() FROM tab WHERE hasToken(s, 'a') SETTINGS use_skip_indexes = 0;                 -- was 0 (wrong), now 1

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

  • Merged into: 26.7.1.848 (included in 26.7 and later)

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master defaults plus use_skip_indexes_on_data_read = 0: SELECT count() FROM tab WHERE hasToken(s,'a') SETTINGS use_skip_indexes_on_data_read = 0 (returns 0, populates the cache), then the same predicate SETTINGS use_skip_indexes = 0 returns 0 every time without the fix. Table: text index with preprocessor = replaceAll(s, ' ', ''), rows ('zzz'),('a b'), index_granularity = 1.
b Root cause explained? The query condition cache is keyed by {table uuid, part name, WHERE-condition hash} only. The cached "matching marks" verdict depends on whether skip indexes ran during index analysis, but the key does not encode that. The read gate filterPartsByQueryConditionCache checked use_query_condition_cache, analyzer, prewhere/filter, vector search, FINAL and mutations, but NOT use_skip_indexes. A query at use_skip_indexes_on_data_read = 0 runs the text index at analysis time; the index drops the 'a b' granule (it is indexed as token ab, a false negative for hasToken(s,'a')), and that exclusion is persisted under the WHERE hash. A later use_skip_indexes = 0 query consults the same key and drops a granule the row-level predicate matches → 0 instead of 1.
c Fix matches root cause? Yes. Adds || !settings[Setting::use_skip_indexes] to the read gate: a query that disabled skip indexes does not consult a skip-index-derived verdict. Directly targets the mechanism in (b), not a symptom.
d Test intent preserved / new tests added? New regression test 02346_text_index_bug108519_qcc_skip_index.sql added (asserts skip_indexes_off = 1, plus a cache-off sanity row). No existing test was weakened; no existing stateless test combines use_skip_indexes = 0 with use_query_condition_cache = 1, so there is no interaction with existing assertions.
e Both directions demonstrated? Yes, on byte-identical builds differing only in this gate clause. Baseline (Build ID 48c31a9e): Q_B returns 0 (wrong). Fixed (Build ID 5ff60e5b/61731e90): Q_B returns 1 (correct). The new test passes on the fixed binary and 40/40 under full CI randomization.
f Fix is general across code paths? Yes. filterPartsByQueryConditionCache is the single read/consult site of the QCC (called once from ReadFromMergeTree::selectRangesToRead). The write side needs no change: an entry written with skip indexes off is the pure row-level matching set (a sound superset), and one written with them on is now only consulted with them on, so no other code path can replay a skip-index verdict to a skip-index-disabled query.
g Fix generalizes across inputs (params/datatypes/wrappers)? The fix is type-agnostic: it gates on the use_skip_indexes setting, independent of column type, tokenizer, preprocessor, or skip-index kind, so all skip-index families (text, bloom_filter, set, minmax, etc.) and all column types are covered identically. The repro uses a text index because that is the clearest legitimate index-vs-row divergence.
h Backward compatible? (maintainer-approved exception only) Yes, no exception needed. No setting default, on-disk/wire format, or validation changes. The only behavior change is that a use_skip_indexes = 0 query no longer reuses a skip-index-derived cache entry — it now returns the correct result instead of a wrong one. Cache writing is unchanged.
i Invariants and contracts preserved? Yes. The change only widens the early-return condition of the read gate (consult fewer entries); it adds no new cache reads/writes and touches no mark-range arithmetic, block structure, ownership, or locking. The QCC's soundness contract (a consulted verdict must be valid for the consulting query's evaluation profile) is now upheld for the skip-index dimension.

Session id: cron:clickhouse-worker-slot-8:20260625-200200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @CurtizJ — could you review this? The query condition cache read gate (filterPartsByQueryConditionCache) did not check use_skip_indexes, so a query with use_skip_indexes = 0 could consult a verdict produced by a skip index. When a skip index legitimately diverges from the row-level predicate (text index + preprocessor), that cached exclusion is a false negative and the query returned a wrong result. Fix gates the read on use_skip_indexes; this is the read-side counterpart to the skip-index case that #107145 deliberately left out for mutations. Closes #108519.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [170cf5a]

Summary: ✅


AI Review

Summary

This PR rekeys skip-index-derived QueryConditionCache entries by the effective skip-index profile while keeping row-level entries on the bare predicate hash. On the current head, the earlier correctness gaps around ignored indexes, disjunction mode, index identity, profile-event accounting, pending ALTER MODIFY COLUMN, and the regression test have been addressed. I did not find a remaining correctness, safety, or compatibility issue in the final diff.

Final Verdict

✅ No new findings on the current PR head.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai The fix needs a revisit because of the implications. Now we silently couple two orthogonal settngs, use_skip_indexes = 0 now also means "disable the query condition cache". QCC is a learned index and there could be pure QCC environments where use_skip_indexes is permanently OFF and user just wants a workload driven, data pruning in-memory index. Let me know your opinion, dont change the fix yet.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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

  1. Gate only the skip-index-analysis write (ReadFromMergeTree ~2867) so divergent skip-index exclusions are never persisted, leaving the three row-level writes untouched. QCC then still prunes with use_skip_indexes=0, and every entry it serves is row-level-sound. Simplest, but it forgoes caching real skip-index exclusions.

  2. Record provenance in the entry (skip-index-derived vs row-level), or fold the effective skip-index profile into the key, then have the read side skip only skip-index-derived entries when skip indexes are off or the index is in ignore_data_skipping_indices. Preserves skip-index caching at the cost of a key/format change.

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.

@shankar-iyer

Copy link
Copy Markdown
Member

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

  1. Gate only the skip-index-analysis write (ReadFromMergeTree ~2867) so divergent skip-index exclusions are never persisted, leaving the three row-level writes untouched. QCC then still prunes with use_skip_indexes=0, and every entry it serves is row-level-sound. Simplest, but it forgoes caching real skip-index exclusions.
  2. Record provenance in the entry (skip-index-derived vs row-level), or fold the effective skip-index profile into the key, then have the read side skip only skip-index-derived entries when skip indexes are off or the index is in ignore_data_skipping_indices. Preserves skip-index caching at the cost of a key/format change.

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 part with a million granules and most of those have been filtered out for a condition : age > 50. Why repeatedly evaluate the skip index for the same condition ? Reading a skip index could require I/O and a bit of CPU depending upon minmax/bloom etc. Also look at this comment from the review bot : #108548 (comment). Can you explain again this "When the skip index legitimately diverges from the row-level predicate" ?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, going with option 2.

Re-explaining the divergence on the regression index text(tokenizer = splitByNonAlpha, preprocessor = replaceAll(s, ' ', '')): the preprocessor rewrites the value before tokenizing, so the row 'a b' is indexed as the single token ab (the space is stripped), not as a/b. For hasToken(s, 'a') the text index reports "no granule has token a" and excludes the granule. But the row-level predicate evaluates hasToken('a b', 'a'), which tokenizes the raw value into ['a','b'] and matches. So the skip-index verdict (here a false negative) legitimately diverges from the row-level predicate: it is correct for the preprocessed token stream, wrong for the raw row. The QCC stores that index-derived "no match" under the bare WHERE hash, so a later row-level query (use_skip_indexes = 0, or with that index in ignore_data_skipping_indices) consults it and returns 0 instead of 1.

One mechanism detail that shapes the fix: all four writers refine the same entry under {table, part, WHERE-hash}. write() ORs more non-matching marks into one shared bitset, so the skip-index-derived marks (the ReadFromMergeTree index-analysis diff) and the sound row-level marks (FilterTransform / MergeTreeSelectProcessor / object storage) end up merged in that single bitset. A per-entry provenance flag therefore cannot separate them after the fact, so the profile has to live in the key. To keep row-level entries universally readable (your pure-QCC case, and the review bot's point), I will fold the profile into the key for the skip-index-derived write only, not the row-level writes:

  • Row-level writers keep writing under the bare WHERE-hash key, so a use_skip_indexes = 0 query still reads them and a pure-QCC environment keeps full reuse.
  • The skip-index-derived write goes under a key salted with the effective skip-index profile (use_skip_indexes plus ignore_data_skipping_indices).
  • The read consults both keys for the current profile and merges them, so a skip-indexes-on environment keeps reusing its cached skip-index exclusions (the million-granule age > 50 case is not re-evaluated), while a query that disabled skip indexes or ignored the named index never sees the skip-index-derived entry.

I will revert the read-side use_skip_indexes / ignore_data_skipping_indices early-return gates from this PR and add the row-level-hit regression the review bot asked for.

…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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed f8e02e2: switched to the profile-keyed approach (option 2). The read-side use_skip_indexes / ignore_data_skipping_indices gates are reverted; skip-index-analysis exclusions are now stored under a key salted with the effective skip-index profile, row-level exclusions keep the bare condition hash, and the read merges both. This keeps the pure-QCC reads (use_skip_indexes = 0) and the skip-index-exclusion reuse you asked about, while still fixing the poisoning. The regression test adds the row-level-hit case the review asked for.

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. hasToken(s,'a') on a text index with preprocessor=replaceAll(s,' ','') over rows ('zzz'),('a b'), index_granularity=1: a query at use_skip_indexes_on_data_read=0 populates the QCC, then the same predicate at use_skip_indexes=0 (or ignore_data_skipping_indices='idx') returns 0 instead of 1.
b Root cause explained? The QCC key is {table, part, WHERE-hash} with no skip-index provenance. All four writers OR their non-matching marks into one shared bitset under that key. The skip-index-analysis write (ReadFromMergeTree) records a granule the text index excludes (the preprocessor strips the space, so 'a b' indexes as token ab, a false negative for hasToken('a')). A later query that disabled that index reads the same key and skips a granule its row-level predicate matches.
c Fix matches root cause? Yes. Skip-index-derived exclusions are stored under a key salted with the effective skip-index profile (use_skip_indexes + the set disabled via ignore_data_skipping_indices), so they are only consulted by a query that ran the same indexes. Row-level exclusions keep the bare hash; the read consults both and merges.
d Test intent preserved / new tests added? New stateless test 02346_text_index_bug108519_qcc_skip_index asserts the poisoning is fixed for both use_skip_indexes=0 and ignore_data_skipping_indices, that the skip-index path still prunes for a same-profile query, and (per review) that a row-level QCC entry is still served at use_skip_indexes=0 (EXPLAIN indexes=1 shows Granules: 1/125).
e Both directions demonstrated? Yes, on byte-verified binaries differing only by this change. Baseline (Build ID ebe5d850): skip_indexes_off=0, ignore_index=0 (poisoned). Fixed (20a05fba): both =1. Cold cache returns the correct 1 on both.
f Fix is general across code paths? Yes. Only the ReadFromMergeTree skip-index-analysis write can diverge from the row-level predicate; the three row-level writers (FilterTransform, MergeTreeSelectProcessor, object storage) are sound and intentionally keep the bare key. The salt is computed by one shared helper used at both the write and the read so they always agree.
g Fix generalizes across inputs? The salt covers both ways the effective skip-index set narrows while use_skip_indexes is otherwise on: the global flag and ignore_data_skipping_indices (parsed exactly as buildIndexes does, names sorted so the key is order-independent). force_data_skipping_indices only requires an index, it does not remove exclusions; FINAL is already excluded by the existing isFinal() early-return.
h Backward compatible? Yes. The QCC is an in-memory, server-local cache with no persisted or wire format; the key change only affects in-process lookup. No setting default or on-disk/replication format changes, so SettingsChangesHistory.cpp is not involved.
i Invariants and contracts preserved? Yes. QueryConditionCache::read returns marks for one part, so the two entries have the same marks_count; the merge ANDs equal-length bitsets (must-read iff both say must-read) and falls back safely if only one is present or sizes differ. No locking or ownership change. The read gate still runs before skip-index analysis, and the helper reads only settings, so write and read compute the identical salt.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 744b696 to fix the two Fast test failures the option-2 commit introduced (03229_query_condition_cache_profile_events, 04249_query_condition_cache_fine_grained_granules).

Cause: the two-key read gate calls QueryConditionCache::read twice per part (bare hash + profiled hash), and each read incremented QueryConditionCacheHits/QueryConditionCacheMisses internally, so one logical consultation emitted up to two events and the asserted miss counts doubled.

Fix: read takes an increment_profile_events flag (default true); the read gate passes false on both probes and counts exactly one hit (if either key matched) or one miss per consultation. The events count consultations again, not internal key lookups, so both tests pass unchanged (no reference edits) and the public metric is not coupled to the internal two-key probing. Single-key callers (object storage) keep the default and are unaffected.

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

@shankar-iyer

Copy link
Copy Markdown
Member

@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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the option-2 commit, with index_granularity = 1 text index (preprocessor strips spaces): populate the QCC at use_skip_indexes_for_disjunctions = 1, use_skip_indexes_on_data_read = 0, then rerun the same OR predicate at use_skip_indexes_for_disjunctions = 0 and read ProfileEvents['QueryConditionCacheHits'] from system.query_log. Before this change the second query records a hit (consults the disjunction-enabled entry); after it records a miss.
b Root cause explained? The salt was a function of the use_skip_indexes and ignore_data_skipping_indices settings, not of the skip indexes analysis actually ran. So (1) an async DROP INDEX (metadata-only, does not disable the QCC) kept the same settings -> same key -> stale exclusion reused; (2) the ignored-name set was hashed with SipHash::update(std::string) which appends no length delimiter, so {"a","bc"} and {"ab","c"} collide; (3) use_skip_indexes_for_disjunctions was absent, so an OR entry written with it enabled was consulted by a query that disabled it.
c Fix matches root cause? Yes. getSkipIndexProfiledConditionHash now salts with the effective useful skip-index set (each index's definition_ast tree hash, sorted by name, folded as fixed-width values) plus use_skip_indexes and use_skip_indexes_for_disjunctions. The effective set already reflects ignore_data_skipping_indices and current metadata, so it closes all three gaps at once.
d Test intent preserved / new tests added? Existing assertions unchanged. Added a different-ignored-set case and a use_skip_indexes_for_disjunctions toggle (asserted via the QCC hit/miss events).
e Both directions demonstrated? Yes, on byte-verified debug binaries differing only by this change. Old salt: disj_off_consults_entry = 1 (wrong, consults the disjunction-enabled entry). Fixed (Build ID 3c401ac4): disj_off_consults_entry = 0 and disj_same_reuses_entry = 1 (no cross-profile consult, same-profile reuse preserved). Full test passes 5/5 and under the CI-randomized settings from a sample run.
f Fix is general across code paths? Yes. The salt is computed once per call by one shared helper and passed to both the single QCC write site (ReadFromMergeTree::selectRangesToRead) and the single read site (filterPartsByQueryConditionCache) from the same Indexes, so write and read always agree. The three row-level writers keep the bare key.
g Fix generalizes across inputs? The key is index-kind agnostic: it hashes the definition AST of every useful skip index (text, bloom_filter, set, minmax, ...) and the two effective flags, so any index kind, column type, ignore-list shape, or disjunction mode is covered. Fixed-width per-index contributions remove the name-boundary collision for all names.
h Backward compatible? Yes. The QCC is an in-memory, server-local cache with no persisted or wire format; the key change only affects in-process lookup. No setting default, on-disk, or replication format change, so SettingsChangesHistory.cpp is not involved.
i Invariants and contracts preserved? Yes. getSkipIndexProfiledConditionHash only reads Indexes (already built before both call sites) and allocates a local vector; no locking, ownership, or mark-range arithmetic changes. QueryConditionCache::read still returns marks for one part, so the two-key merge ANDs equal-length bitsets. The soundness contract (a consulted skip-index verdict must be valid for the consulting query's index set) now holds across the metadata, ignore-set, and disjunction dimensions.

Session id: cron:clickhouse-worker-slot-2:20260629-092300

@groeneai

Copy link
Copy Markdown
Collaborator Author

@shankar-iyer Pushed 586323e, which addresses all three open bot review comments. The earlier option-2 commit keyed skip-index entries by the use_skip_indexes / ignore_data_skipping_indices settings; the bot was right that the settings are not the same thing as the indexes that actually ran. The salt is now a function of the effective useful skip-index set itself:

  • r3489956110 (stale entry after a metadata change): the key now folds in each useful index's definition_ast tree hash. buildIndexes already drops indexes that are gone from metadata or listed in ignore_data_skipping_indices, so an async DROP INDEX (which does not disable the QCC) changes the running set, hence the key, and the stale exclusion is no longer consulted. Hashing the definition AST (not just the name) also distinguishes a same-name index that was redefined.
  • r3489956114 (ambiguous ignored-name hash): each index now contributes a fixed-width definition hash, so {a, bc} and {ab, c} can no longer collapse to the same byte stream.
  • r3490522160 (use_skip_indexes_for_disjunctions missing): it is now part of the salt.

The salt is computed by one helper from the same Indexes on both the write side (ReadFromMergeTree) and the read side (filterPartsByQueryConditionCache), so they always agree.

On "when the skip index legitimately diverges from the row-level predicate": the regression index is text(tokenizer = splitByNonAlpha, preprocessor = replaceAll(s, ' ', '')). The preprocessor rewrites the value before tokenizing, so the row 'a b' is indexed as the single token ab, not a/b. For hasToken(s, 'a') the index reports "no granule has token a" and excludes the granule, but the row-level predicate tokenizes the raw value into ['a','b'] and matches. So the index verdict is correct for the preprocessed token stream and wrong for the raw row: a false negative for the row-level predicate. The QCC stored that index-derived exclusion under the bare WHERE hash, so a query that did not run that index (skip indexes off, the index ignored, or a different disjunction mode) consulted it and returned 0 instead of 1. Keying the skip-index entries by the running index set is what stops that, while row-level entries keep the bare hash and stay reusable in a pure-QCC environment.

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 QueryConditionCacheHits/Misses events: a disjunction-disabled query misses the disjunction-enabled entry, and a same-profile query still hits it, so the combined-index exclusions are not re-evaluated.

@groeneai groeneai changed the title Do not consult the query condition cache when skip indexes are disabled Key skip-index query condition cache entries by the skip indexes that ran Jun 29, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

@shankar-iyer the two new bot comments on 586323e are addressed in 2600528 (test-only):

  1. Pending ALTER MODIFY COLUMN on an indexed column (the "indexes that actually ran" concern). It does not misfire on HEAD, so I added a regression that locks the behavior in rather than a mutation gate. canUseIndex rejects an index for a part only when the indexed column's type changes (AlterConversions adds it to getAllUpdatedColumns() only for a READ_COLUMN with data_type set). That same type change also changes the bare WHERE condition hash (ActionsDAG::Node::updateHash folds in each node's result_type), hence the profiled key, so the query misses the stale entry. Instrumented confirmation in the inline thread: salt component byte-identical, bare hash changed, clean miss, correct count. If you would rather fail closed on hasAlterMutations() to make the invariant explicit (mirroring supportsSkipIndexesOnDataRead()) instead of resting on the condition-hash coupling, it is a one-line gate change at MergeTreeDataSelectExecutor.cpp:1425. Your call on which you prefer for the QCC path.

  2. Test parallel-safety: dropped the instance-wide SYSTEM DROP QUERY CONDITION CACHE; the fresh-UUID tab_disj already isolates this run's entries. Verified parallel-safe under self-parallel and concurrent-clear stress.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed 74dfd1cf1f5: make 02346_text_index_bug108519_qcc_skip_index no-parallel to fix its flaky-check failure.

The flaky check on the prior head failed only on the last assertion: disj_same_reuses_entry flipped from 1 to 0. Root cause: that assertion checks a QueryConditionCacheHits profile event, and the query condition cache is instance-wide. Sibling stateless tests (03229_query_condition_cache_*, 04065_join_shard_by_pk_with_qcc, 04275_104781_qcc_*) issue SYSTEM DROP QUERY CONDITION CACHE; in the parallel pool one of them can evict our entry between the populate query and the reuse query, turning the expected hit into a miss. The whole QCC test family already uses no-parallel for exactly this; the row-level row-count assertions here are eviction-robust, so the test was fine in parallel until the hit assertion was added. no-parallel only changes scheduling; the test output is unchanged (no .reference edit).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Running the disjunction sub-test's populate query, then SYSTEM DROP QUERY CONDITION CACHE, then the same-profile query makes disj_same_reuses_entry return 0 every time (a sibling test's drop interleaved between populate and reuse).
b Root cause explained? The QCC is instance-wide. disj_same_reuses_entry asserts a cache hit (populate writes the skip-index exclusion under the profiled key; the same-profile query reuses it). Six sibling stateless tests issue instance-wide SYSTEM DROP QUERY CONDITION CACHE; in the parallel pool one lands between this test's populate and reuse query, evicts the entry, the reuse query misses, and the hit count flips 1 to 0.
c Fix matches root cause? Yes. no-parallel runs the test in the sequential pool, so no sibling can drop the cache between the two queries. This is the same mechanism the entire QCC test family uses. Not a band-aid: the cache is true server-global state, the documented no-parallel last-resort case.
d Test intent preserved / new tests added? Yes. No assertion is changed or weakened; the test still proves the option-2 profile-keyed behavior (poisoning fixed for use_skip_indexes=0 / ignore_data_skipping_indices, skip-index reuse preserved for the same profile, row-level QCC served at use_skip_indexes=0, and disjunction-mode profile separation). Only the scheduling tag changes.
e Both directions demonstrated? Yes. Without the fix: a concurrent SYSTEM DROP QUERY CONDITION CACHE interleaved between populate and reuse deterministically yields disj_same_reuses_entry 0 (the CI failure signature). With the fix (sequential, no interleaving): 50/50 runs match the reference exactly, and 30/30 with the failing runs' randomized settings applied.
f Fix is general across code paths? N/A (test scheduling fix, not a code bug).
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (test scheduling fix, not a code bug).
h Backward compatible? (maintainer-approved exception only) N/A (test scheduling fix; no settings/format/behavior change).
i Invariants and contracts preserved? N/A (test scheduling fix; no source change).

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two same-definition minmax indexes ix_a/ix_b; populate running ix_a (ignore_data_skipping_indices = 'ix_b'), then query running ix_b (ignore_data_skipping_indices = 'ix_a'). On the old salt the second query reports QueryConditionCacheHits = 1 every time.
b Root cause explained? The salt hashed only each useful index's definition_ast->getTreeHash. ASTIndexDeclaration keeps name and granularity as plain members and does not override updateTreeHashImpl, so IAST::updateTreeHashImpl (which hashes getID() = "Index" plus the child ASTs) excludes both. Two indexes with the same expression and type but a different name therefore produced the same salt, sharing one profiled QCC key, so a verdict written while ix_a ran could be read by a query running only ix_b.
c Fix matches root cause? Yes. The salt now folds each useful index's name (length-prefixed) and granularity in next to its definition AST hash.
d Test intent preserved / new tests added? Added the tab_namecol section (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. No existing assertion weakened.
e Both directions demonstrated? Yes. Old name-blind salt: namecol_read_b_consults_entry = 1 (collision). Fixed: = 0 (clean miss), and namecol_reuse_a_reuses_entry = 1 (reuse preserved). Proven on rebuilt binaries (old Build ID fd842016, fixed cd8ee7d5).
f Fix is general across code paths? The salt is the single chokepoint: computed once from the running ReadFromMergeTree::Indexes in selectRangesToRead and threaded to both the read (filterPartsByQueryConditionCache) and write (ReadFromMergeTree) sites, so read == write by construction. No sibling path to widen.
g Fix generalizes across inputs? Both distinguishing members the bot named are folded in: name (length-prefixed, so ('a','bc') and ('ab','c') cannot collide by concatenation) and granularity. The existing use_skip_indexes / disjunction-mode / definition-AST components are unchanged.
h Backward compatible? N/A. The query condition cache is an in-memory, per-process cache; changing the salt only affects hit/miss within a run. No on-disk/wire/replication format, setting default, or new data validation changes, so no SettingsChangesHistory.cpp entry is needed.
i Invariants and contracts preserved? Strengthens the "only consult entries produced by the same effective skip-index set" invariant. The read and write keys are produced by the same function over the same indexes argument, so they remain equal; useful_indices already reflects ignore_data_skipping_indices and dropped/redefined indexes.

Session id: cron:clickhouse-worker-slot-3:20260629-125900

@groeneai

Copy link
Copy Markdown
Collaborator Author

@shankar-iyer Pushed f780010, addressing the last open bot blocker (the salt was name- and granularity-blind).

ASTIndexDeclaration keeps name and granularity as plain members and does not override updateTreeHashImpl, so definition_ast->getTreeHash excluded both. Two indexes with the same expression and type but a different name shared a profiled key, which re-opened the stale skip-index read in the partially-materialized case. The salt now folds each useful index's name (length-prefixed) and granularity in next to its definition AST hash, still computed once from the running set and threaded to both read and write sites.

Verified both directions with two same-definition minmax indexes (sound exclusions, so checked via QueryConditionCacheHits): old salt -> the ix_b query reads ix_a's entry; fixed -> clean miss, while the same ix_a profile still reuses its entry. Added as the tab_namecol regression. 30/30 randomized-settings runs pass.

I believe this closes the salt-completeness line of review. Ready for your pass.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — f780010

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (11 configs) / 02354_vector_search_rescoring master regression (Code 44 ILLEGAL_COLUMN _distance, from #105591) #108812 (ours, merged) — merged master @ bf5c5e7 to pick it up
CH Inc sync - CH Inc sync (private, not actionable)

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bf5c5e7

Every failure below has an owner. Only CH Inc sync is exempt. None are caused by this PR (a query-condition-cache skip-index keying fix in MergeTreeDataSelectExecutor.cpp; the failures below are unrelated).

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Hung check failed, possible deadlock found trunk shutdown-deadlock hung-check family #101680 / #105905 (ours, open)
Stress test (arm_tsan) / Hung check failed, possible deadlock found trunk shutdown-deadlock hung-check family #101680 / #105905 (ours, open)
PR rollup of the two Stress failures above (no independent failure) owned via the rows above
CH Inc sync private sync CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260629-233000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — bf5c5e7

Every 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 CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) + (arm_tsan) / Hung check failed, possible deadlock found deadlock #101680 / #105905 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

(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
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged current master (1322ce4) to resolve a conflict, pushed 170cf5a.

The conflict was in the two QCC read sites that master's new top_k_filter_info cache salt (ORDER BY ... LIMIT N plans) also touches:

  • MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache now takes both top_k_filter_info and indexes; and inside drop_mark_ranges the profiled skip-index hash is computed AFTER the optional top-k salt is combined into condition_hash, exactly mirroring the write side in ReadFromMergeTree (bare hash -> top-k salt -> getSkipIndexProfiledConditionHash). So read == write keys under both dimensions.
  • The filterPartsByQueryConditionCache call site in ReadFromMergeTree passes both new args.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered: 76/76 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 170cf5a

CI fully finished on this head (master-conflict merge). Finish Workflow + Mergeable Check both pass; every check green.

Check / test Reason Owner / fixing PR
(no red checks) — —
CH Inc sync private fork mirror CH Inc sync (private, not actionable)

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

@shankar-iyer shankar-iyer self-assigned this Jul 6, 2026
@shankar-iyer
shankar-iyer added this pull request to the merge queue Jul 13, 2026
Merged via the queue into ClickHouse:master with commit f76b144 Jul 13, 2026
177 checks passed
@shankar-iyer

Copy link
Copy Markdown
Member

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)

@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Key skip-index query condition cache entries by the skip indexes that ran

ClickGap verified: reproduced it with the script below on 26.6; tested 7 version(s) — 6 affected, 1 clean (see Affects); present since the feature was introduced in v25.9 (not a recent regression).

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 1

▶ Run on ClickHouse Fiddle

Bisect

  • The reproducer requires use_skip_indexes_on_data_read, introduced in v25.9 — so this is not pre-existing: it was introduced no earlier than v25.9, and the introducing change is in the 25.9–master range (most likely the change that added the feature). Every release line down to there reproduces.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.6, 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-mergetree
Severity: P2


ClickGap · Finding: phase_d_pr108548

Triage metadata

  • Primary component: comp-mergetree
  • Secondary components: comp-testing
  • Component owners (comp-mergetree): @CurtizJ @alexey-milovidov

@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 13, 2026
pull Bot pushed a commit to stnxo2023/ClickHouse that referenced this pull request Jul 15, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…9-qcc-skip-index-read-gate

Key skip-index query condition cache entries by the skip indexes that ran
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
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 pr-bugfix Pull request with bugfix, not backported by default 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.

Query condition cache consulted on queries with use_skip_indexes=0, returning wrong results (text index + preprocessor)

5 participants