Skip to content

Fix query condition cache poisoning by on-fly mutations - #107145

Merged
alesapin merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-qcc-on-fly-mutations
Jun 19, 2026
Merged

alesapin merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-qcc-on-fly-mutations

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 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 query results caused by the query condition cache when on-fly mutations (apply_mutations_on_fly) or patch parts filtered rows before PREWHERE. A query reading with apply_mutations_on_fly = 1 could poison the cache so that a later query with apply_mutations_on_fly = 0 and the same predicate skipped marks it should have read and returned too few rows. The same fix also covers row-level security policies, which are prepended as a filter ahead of PREWHERE: a query run under a restrictive row policy could poison the cache for a later query that uses the same predicate without that policy.

Description

The query condition cache stores, per (table, part, predicate hash), which marks match a PREWHERE/WHERE predicate so later queries with the same predicate can skip non-matching marks.

On-fly mutations (lightweight UPDATE/DELETE applied via apply_mutations_on_fly) and patch parts are spliced into the readers chain ahead of PREWHERE, so they drop or rewrite rows before PREWHERE evaluates them. A mark could therefore become fully non-matching only because of the mutation, not because of the predicate, yet it was still attributed to the predicate's hash. A later query that shares the same predicate but does not apply the mutations (apply_mutations_on_fly = 0) then hit the cached entry and wrongly skipped those marks, returning too few rows.

The same poisoning exists for row-level security policies: a row policy is prepended as a filter ahead of PREWHERE (getPrewhereActions), so a mark hidden only by the policy was wrongly attributed to the PREWHERE/WHERE predicate hash. A later query with the same predicate but without that policy then read the poisoned entry and skipped rows it should have seen. The write path now also skips cache attribution when row_level_filter is set.

The effect was masked at large index_granularity (the granule is recorded as "may match" and PREWHERE re-runs per row) and surfaced deterministically at small index_granularity, which is why 03047_on_fly_update_delete was flaky under randomized index_granularity.

The read path already bypasses the cache when on-fly mutations or patch parts are active. This makes the write path symmetric: MergeTreeSelectProcessor now skips the cache write/attribution whenever the read task applies mutations before PREWHERE (or a row policy filter is set), mirroring the existing readersChainCanSkipMarksBeforePrewhere guard for skip indexes (issue #104781). The cache still prunes normally when no mutations or row policies are involved.

Regression tests: 03229_query_condition_cache_on_fly_mutations covers both on-fly DELETE and on-fly UPDATE at index_granularity = 1, and 03229_query_condition_cache_row_policy.sh covers the row-policy poisoning vector; both fail before this change and pass after.

Version info

  • Merged into: 26.6.1.1043 (included in 26.6 and later)
  • Backported to: 26.5.6.46, 26.4.5.134, 26.3.17.50

The query condition cache records, per (table, part, predicate hash), which
marks match a PREWHERE/WHERE predicate so later queries with the same predicate
can skip non-matching marks. On-fly mutations (lightweight UPDATE/DELETE, via
apply_mutations_on_fly) and patch parts are spliced into the readers chain
ahead of PREWHERE, so they drop or rewrite rows before PREWHERE evaluates them.
A mark could therefore become fully non-matching only because of the mutation,
not because of the predicate itself, yet it was still attributed to the
predicate's hash.

This poisoned the cache: a later query that shares the same predicate but does
not apply the mutations (apply_mutations_on_fly = 0) hit the cached entry and
wrongly skipped those marks, returning too few rows. The effect was masked at
large index_granularity (the granule is recorded as "may match" and PREWHERE
re-runs per row) and surfaced deterministically at small index_granularity,
which is why 03047_on_fly_update_delete was flaky under randomized
index_granularity.

The read path already bypasses the cache when on-fly mutations or patch parts
are active (MergeTreeDataSelectExecutor); this makes the write path symmetric by
skipping the cache write/attribution in MergeTreeSelectProcessor whenever the
read task applies mutations before PREWHERE, mirroring the existing
readersChainCanSkipMarksBeforePrewhere guard for skip indexes (issue ClickHouse#104781).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (id UInt64, v UInt64) ENGINE=MergeTree ORDER BY id SETTINGS index_granularity=1; INSERT 100 rows; SET mutations_sync=0; SYSTEM STOP MERGES t; ALTER TABLE t DELETE WHERE id%3=0; then SELECT count() FROM t PREWHERE id%5=0 SETTINGS apply_mutations_on_fly=1 (returns 13, writes the cache entry) followed by the same query with apply_mutations_on_fly=0 returns 13 every time, should be 20.
b Root cause explained? The query condition cache records which marks match a PREWHERE predicate, keyed by (table, part, predicate hash). On-fly mutations are spliced into the readers chain ahead of PREWHERE, so a mark can be fully filtered by the mutation and still get attributed to the predicate's hash. A later query with the same predicate and apply_mutations_on_fly=0 reads the poisoned entry and skips marks the predicate alone would match. Large index_granularity masks it (granule recorded as "may match", PREWHERE re-runs per row); index_granularity=1 exposes it, which is why 03047_on_fly_update_delete was flaky under randomized granularity.
c Fix matches root cause? Yes. The read path already bypasses the cache when on-fly mutations/patch parts are active; the fix makes the write path symmetric by skipping the cache write/attribution in MergeTreeSelectProcessor whenever the read task applied mutations before PREWHERE (new appliesMutationsBeforePrewhere()), mirroring the existing readersChainCanSkipMarksBeforePrewhere guard for skip indexes (#104781). Not a symptom band-aid: the cache still prunes normally when no mutations are involved (verified: cold scan reads 1,000,000 rows, warm reads 16,960).
d Test intent preserved / new tests added? New test 03229_query_condition_cache_on_fly_mutations added, covering both on-fly DELETE and on-fly UPDATE at index_granularity=1. No existing test weakened.
e Both directions demonstrated? Yes. On the unfixed build the new test outputs 13 / 13 / 0 / 0; with the fix it outputs the expected 13 / 20 / 0 / 50. The original 03047_on_fly_update_delete now matches its reference at index_granularity 1, 2, 4, 13 and 8192 (wide and compact parts).
f Fix is general, not a narrow patch? Yes. The guard covers both on-fly mutation steps (lightweight UPDATE and DELETE) and patch parts, and is applied at all three QCC attribution sites in MergeTreeSelectProcessor (two addPrewhereUnmatchedMarks plus the write). It fixes the write at its source rather than guarding the read symptom.

Found by investigating the flaky 03047_on_fly_update_delete (Stateless tests, distributed plan + s3 storage), reproduced from CIDB which isolated small index_granularity as the trigger.

Session id: cron:clickhouse-worker-slot-28:20260611-030400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @rschu1ze — could you review this? The query condition cache was writing PREWHERE mark-match info that had been pre-filtered by on-fly mutations (apply_mutations_on_fly) / patch parts, keyed only by the predicate hash. A later query with the same predicate but apply_mutations_on_fly = 0 then hit the poisoned entry and skipped marks it should have read, returning too few rows (deterministic at small index_granularity; this is the root cause of flaky 03047_on_fly_update_delete). The fix makes the cache write path skip attribution when mutations ran before PREWHERE, symmetric with the read path which already bypasses the cache in that case.

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

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b7182f6]

Summary: ✅


AI Review

Summary

This PR prevents QueryConditionCache entries from being written when the marks were filtered by on-fly mutations, patch parts, or row-level security before the user predicate actually evaluated. The current patch also covers the previously raised WHERE, row-policy, patch-part, and mutations_sync gaps, and I found no remaining review findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
…mutations

The previous commit only gated the PREWHERE attribution sites in
MergeTreeSelectProcessor. The WHERE predicate uses a separate cache write path:
MergeTreeSelectProcessor attaches a MarkRangesInfo to every data chunk, and the
downstream FilterTransform::writeIntoQueryConditionCache records those mark ranges
under the WHERE condition hash whenever it fully filters a chunk.

With an on-fly UPDATE that rewrites the WHERE column, a query with
apply_mutations_on_fly = 1 can mark originally-matching granules as non-matching
(the mutation, not the predicate, dropped the rows), poisoning the cache. A later
apply_mutations_on_fly = 0 query reads that entry (its mutation snapshot has no data
mutations, so the read path does not bypass the cache) and returns too few rows.

Skip attaching the MarkRangesInfo when the read task applies mutations or patch
parts ahead of the filter, which starves the WHERE-side writer. This mirrors the
PREWHERE guard and keeps the write path symmetric with the read path
(MergeTreeDataSelectExecutor already bypasses the cache when mutations are active).

Add a WHERE-clause regression to 03229_query_condition_cache_on_fly_mutations:
an on-fly UPDATE changing the WHERE column at index_granularity = 1, with
move-to-prewhere disabled so the predicate is evaluated by FilterTransform.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for the WHERE-path fixup cab744b)

# Question Answer
a Deterministic repro? Yes. On-fly UPDATE v=0 WHERE id>=50, then SELECT count() FROM t WHERE v>=50 with apply_mutations_on_fly=1 (writes the entry) followed by =0 (reads it), index_granularity=1, optimize_move_to_prewhere=0, query_plan_optimize_prewhere=0. Returns 0 then 0 on the PREWHERE-only binary; correct second value is 50.
b Root cause explained? The WHERE predicate uses a separate cache-write path from PREWHERE. readCurrentTask attaches a MarkRangesInfo to every chunk; after updateQueryConditionCache sets the WHERE condition on the downstream FilterTransform, FilterTransform::writeIntoQueryConditionCache records those marks under the WHERE hash when a chunk is fully filtered. An on-fly UPDATE that rewrites the WHERE column makes originally-matching granules non-matching, so a fly=1 query writes a poisoned entry that a later fly=0 query reads (its snapshot has no data mutations, so the read path does not bypass the cache).
c Fix matches root cause? Yes. Skip attaching the MarkRangesInfo when appliesMutationsBeforePrewhere() is true, which starves both FilterTransform writer branches. Addresses the exact mechanism in (b); no symptom masking.
d Test intent preserved / new tests added? Added Case 3 to 03229_query_condition_cache_on_fly_mutations (on-fly UPDATE changing the WHERE column, move-to-prewhere disabled) alongside the existing PREWHERE cases. Confirmed the cache still prunes correctly with no mutations (cold 1,000,000 rows -> warm read skips marks).
e Both directions demonstrated? Yes. PREWHERE-only binary: WHERE repro returns 0/0 (new test FAILs). With the fixup: 0/50 (PASSes). Full test 50/50 with randomization; all non-distributed query_condition_cache tests pass.
f Fix is general, not a narrow patch? Yes. Both QCC write paths are now gated by the same appliesMutationsBeforePrewhere() predicate: PREWHERE attribution (3 sites, prior commit) and the WHERE-side MarkRangesInfo attachment (this commit, covering both FilterTransform writer branches). Gated on mutations only, not skip-index (#104781): skip-index drops whole marks before they are read, while mutations rewrite values within read marks. Symmetric with the read-path bypass in MergeTreeDataSelectExecutor::filterPartsByQueryConditionCache.

Session id: cron:clickhouse-worker-slot-18:20260611-110700

… is present

A SELECT row policy is prepended as a filter step ahead of PREWHERE
(getPrewhereActions), but the PREWHERE attribution path keys the cache write only
on the query PREWHERE predicate's hash, not on the row policy. A user whose policy
hides a mark could therefore populate a PREWHERE cache entry for that mark; a later
query by a user without that policy shares the prewhere-only key, reads the entry in
filterPartsByQueryConditionCache, and skips rows it should see.

Gate the three PREWHERE attribution sites in MergeTreeSelectProcessor on the absence
of row_level_filter, mirroring the existing readersChainCanSkipMarksBeforePrewhere
(Issue ClickHouse#104781) and appliesMutationsBeforePrewhere guards. The WHERE-side writer is
already scoped by the full filter_actions_dag key (which includes the row policy), so
it needs no change.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (updated for the row-policy / row_level_filter fix, 0b66b14)

# Question Answer
a Deterministic repro? Yes. Table index_granularity = 1; permissive policy FOR SELECT USING v < 50 TO u_pol. u_pol runs SELECT count() ... PREWHERE v >= 50 (0 under its policy), then u_nopol (no policy) runs the same query. On PR-HEAD cab744b4 the no-policy user gets 0; with use_query_condition_cache = 0 it gets 50.
b Root cause explained? A SELECT row policy is prepended as a filter step ahead of PREWHERE (getPrewhereActions), but the PREWHERE attribution write keys the cache only on prewhere_info->prewhere_actions (output->getHash()), not on the row policy. So a mark emptied by the policy is attributed to the bare PREWHERE predicate; a later user without that policy shares the same key in filterPartsByQueryConditionCache and skips marks it should read.
c Fix matches root cause? Yes. Suppress the PREWHERE QCC attribution when row_level_filter is present (the prepended row-policy step), so a policy-scoped read never writes a predicate-keyed entry. Mirrors the existing readersChainCanSkipMarksBeforePrewhere (#104781) and appliesMutationsBeforePrewhere guards. The WHERE writer is already scoped by filter_actions_dag (includes the policy), so it is unchanged.
d Test intent preserved / new tests added? New 03229_query_condition_cache_row_policy.sh (two users, one with a row policy, one without). The prior PREWHERE/WHERE on-fly-mutation cases in 03229_query_condition_cache_on_fly_mutations.sql are unchanged and still pass.
e Both directions demonstrated? Yes. New test FAILS on cab744b4 (no-policy user 0 vs reference 50) and PASSES on the fixed binary; 20/20 with full settings randomization.
f Fix is general, not a narrow patch? All three PREWHERE-attribution sites in MergeTreeSelectProcessor are gated identically (read() write + two addPrewhereUnmatchedMarks in readCurrentTask). The symmetric WHERE path was verified to already key on the full filter_actions_dag (row-policy-scoped), so no change is needed there. The new gate composes with the on-fly-mutation and skip-index guards rather than duplicating them.

Session id: cron:clickhouse-worker-slot-11:20260611-124800

The row-policy regression assumed a user without any policy on a policied
table sees all rows, but the test config enables
throw_on_unmatched_row_policies, so that user is denied (ACCESS_DENIED)
and the test failed in Fast test. Use two users that both have a policy:
one restricted to v < 50 and one with an always-true policy that must see
every row. The always-true policy is dropped by the planner so the show
user shares the poisoned PREWHERE cache key, still exercising the bug.

Also add no-parallel-replicas to the test (the query condition cache is
per replica, so the poisoning is deterministic only on a single replica)
to stop random parallel-replicas runs from erroring with
INCONSISTENT_CLUSTER_DEFINITION.

Add a fourth case to 03229_query_condition_cache_on_fly_mutations that
exercises a patch part (alter_update_mode = 'lightweight_force') rather
than an on-fly mutation step, covering the info->patch_parts half of the
appliesMutationsBeforePrewhere guard which the existing heavy ALTER UPDATE
cases do not reach. apply_patch_parts = 1 poisons, apply_patch_parts = 0
must still see the original rows.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (test-only follow-up: row-policy Fast-test fix + patch-parts case)

# Question Answer
a Deterministic repro? Yes. Row policy: with throw_on_unmatched_row_policies on (test config), a no-policy user on a policied table is denied (Code 497 ACCESS_DENIED). Reworked test (two policied users) reproduces the poisoning deterministically on master HEAD: show user returns 0 instead of 50 at index_granularity = 1. Patch parts: alter_update_mode = 'lightweight_force' + apply_patch_parts = 1 then = 0 returns 0/0 on master HEAD instead of 0/50.
b Root cause explained? Two distinct issues. (1) The original row-policy test wrongly assumed a no-policy user sees all rows; under the test config's throw_on_unmatched_row_policies that user is denied, so Fast test failed with ACCESS_DENIED (not a timeout). (2) The fix gates both info->mutation_steps and info->patch_parts, but the existing cases only used ALTER ... UPDATE (defaults to alter_update_mode = 'heavy'), exercising only the mutation_steps half.
c Fix matches root cause? Yes. Row-policy test now uses two users that both have a policy (hide: v < 50; show: always-true), so neither hits throw_on_unmatched; the always-true policy is dropped by the planner so the show user still shares the poisoned PREWHERE cache key. New Case 4 uses a real patch part so apply_patch_parts (not apply_mutations_on_fly) controls application, covering the patch_parts branch of appliesMutationsBeforePrewhere. No production code changed in this commit.
d Test intent preserved / new tests added? Preserved and strengthened. Row-policy test still proves a user who should see a mark is not denied rows by a poisoned cache entry. Patch-parts case is new coverage for the second half of the guard. Added no-parallel-replicas to both tests because the query condition cache is per replica, so the poisoning is deterministic only on a single replica (random parallel-replicas runs otherwise error with INCONSISTENT_CLUSTER_DEFINITION).
e Both directions demonstrated? Yes, on Build-ID-verified binaries. Master HEAD (pre-fix, build id 9582140e): row-policy show user 0 (FAIL), patch-parts 0/0 (FAIL). With the fix (build id 8f2c5d63): row-policy 0/50, patch-parts 0/50. Both tests pass 100/100 with full randomization.
f Fix is general, not a narrow patch? N/A for production code in this commit (test-only). The underlying production fix already covers PREWHERE on-fly mutations, patch parts, the WHERE-side writer, and the row-policy PREWHERE writer; this commit adds the missing test coverage for the patch-parts branch and corrects the row-policy test for the CI access config.

Session id: cron:clickhouse-worker-slot-19:20260611-140500

The patch-part case (Case 4) in 03229_query_condition_cache_on_fly_mutations
inherited mutations_sync = 0 from the earlier on-fly mutation cases, so the
lightweight ALTER ... UPDATE could return before the patch part was committed.
The apply_patch_parts = 1 read could then see no patch, return 50, and never
exercise the info->patch_parts guard. Set mutations_sync = 1 on the ALTER so
the patch part is committed before the read. Output is unchanged.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (patch-part test determinism fixup, commit b7182f6)

# Question Answer
a Deterministic repro? Yes. With mutations_sync = 0 the lightweight ALTER ... UPDATE can return before the patch part is committed, so the apply_patch_parts = 1 read may see no patch and return 50, making Case 4 vacuous (never reaches the info->patch_parts guard). With mutations_sync = 1, the patch part (patch-...-all_3_3_0_2, 50 rows) is committed before the read in 30/30 iterations.
b Root cause explained? Case 4 inherited the session-level mutations_sync = 0 set in cases 2-3. alter_update_mode = 'lightweight_force' builds the patch part asynchronously; without waiting, the immediately-following apply_patch_parts = 1 read can run before the patch is committed, so it sees the original rows (count 50) instead of the poisoning-write count 0, and the patch-parts half of the fix goes untested.
c Fix matches root cause? Yes. Added mutations_sync = 1 to the Case 4 ALTER (query-level SETTINGS overrides the inherited session value), exactly the bot's suggestion. This forces the patch part to be committed before the read. No production code change.
d Test intent preserved / new tests added? Preserved and strengthened. The case still asserts 0 (apply_patch_parts=1) then 50 (apply_patch_parts=0); .reference is unchanged. The change only removes the timing dependency so the info->patch_parts guard is exercised deterministically on every run.
e Both directions demonstrated? The fix-vs-no-fix discrimination for this case was shown earlier on the pre-fix binary (Build ID 9582140e: Case 4 -> 0/0 FAIL) vs fixed (0/50 PASS). This fixup keeps the fixed-binary result at 0/50 while making the apply_patch_parts=1 read deterministically see the patch (30/30 patch-present). Full test: 5/5 no-random and 50/50 with randomization via the clickhouse-test runner on the fixed binary (Build ID 8f2c5d63).
f Fix is general, not a narrow patch? N/A for production code (test-only change). The production fix already gates both info->mutation_steps and info->patch_parts via appliesMutationsBeforePrewhere(); this commit only makes the regression that covers the patch_parts branch deterministic.

Session id: cron:clickhouse-worker-slot-2:20260611-162800

@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.20% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 30/30 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on b7182f6. All checks green (147 success, 19 skipped, 0 failures). No PR-caused failures. Ready for review.

(cron:our-pr-ci-monitor:20260611-210000)

@alesapin alesapin self-assigned this Jun 19, 2026
@alesapin

Copy link
Copy Markdown
Member

@groeneai does it mean that you want to disable PREWHERE in case of presence of any lightweight mutations?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alesapin No, PREWHERE is not disabled. It still executes and prunes rows exactly as before. The change only skips writing into the query condition cache (the per-mark "this mark does not match predicate P" attribution) while on-fly mutations or patch parts are spliced into the readers chain ahead of PREWHERE.

Those steps can make a whole mark non-matching for a reason unrelated to P: an on-fly DELETE removed the matching rows, or an on-fly UPDATE rewrote the column. Recording that mark under P's hash poisons a later query that shares P but runs with apply_mutations_on_fly = 0 (which does not apply the mutations): it consults the cache and skips the mark, losing rows. The read path already bypasses the QCC when mutations are active (filterPartsByQueryConditionCache); this only makes the write path symmetric. With no mutations present the cache populates and prunes as before (cold 1M rows, warm skips 16,960 marks).

So the only cost is that a mutation-active read does not warm the cache for later queries; PREWHERE itself is untouched.

An alternative to suppression is to fold the mutation / patch-part state (and the row-level filter) into the cache key, so a no-mutation query cannot read a mutation-scoped entry and the cache still gets populated. That is more precise but adds key churn as mutations come and go. I went with suppression to mirror the existing #104781 guard; I can switch to keying if you prefer that direction.

@alesapin
alesapin added this pull request to the merge queue Jun 19, 2026
Merged via the queue into ClickHouse:master with commit 57afe3c Jun 19, 2026
166 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 19, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alesapin — a couple of suggestions to make this PR easier for reviewers and the changelog reader.

Description (currently incomplete):

  • Why: The description thoroughly explains the on-fly-mutation/patch-part case but does not mention the row-level-policy poisoning that the diff also fixes (the !row_level_filter guards and the row_policy.sh test), even though that is a security-adjacent correctness fix (a user with a restrictive policy could poison the cache for a query without that policy).

  • Suggested addition:

    Also fixes the symmetric poisoning by row-level security policies: a row policy is prepended as a filter ahead of PREWHERE (getPrewhereActions), so a mark hidden by the policy was wrongly attributed to the PREWHERE/WHERE predicate hash. A later query with the same predicate but without that policy then read the poisoned entry and skipped rows it should have seen. The write path now also skips cache attribution when row_level_filter is set (see 03229_query_condition_cache_row_policy.sh).

Ignore this if the current title/body is intentional.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 16, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jul 16, 2026
Cherry pick #107145 to 26.3: Fix query condition cache poisoning by on-fly mutations
robot-clickhouse added a commit that referenced this pull request Jul 16, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jul 16, 2026
Cherry pick #107145 to 26.4: Fix query condition cache poisoning by on-fly mutations
robot-clickhouse added a commit that referenced this pull request Jul 16, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jul 16, 2026
Cherry pick #107145 to 26.5: Fix query condition cache poisoning by on-fly mutations
robot-clickhouse added a commit that referenced this pull request Jul 16, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 16, 2026
PedroTadim added a commit that referenced this pull request Jul 16, 2026
Backport #107145 to 26.4: Fix query condition cache poisoning by on-fly mutations
PedroTadim added a commit that referenced this pull request Jul 16, 2026
Backport #107145 to 26.5: Fix query condition cache poisoning by on-fly mutations
PedroTadim added a commit that referenced this pull request Jul 16, 2026
Backport #107145 to 26.3: Fix query condition cache poisoning by on-fly mutations
fm4v added a commit that referenced this pull request Aug 1, 2026
…ery does not read

`appliesMutationsBeforePrewhere` keyed the write-side disqualification off `AlterConversions::hasMutations`, which is true for any pending on-fly mutation. But `AlterConversions::filterMutationCommands` drops `UPDATE` commands whose assignments touch none of the columns the query reads, so such a mutation contributes no read-chain step, rewrites nothing the query observes, and caching its marks is sound. Keying off `hasMutations` therefore suppressed cache writes more broadly than the read chain it models: with `apply_mutations_on_fly = 1` a pending `UPDATE` of an unrelated column disabled cache population for every predicate on the table.

Track whether any steps produced from the mutations snapshot actually made it into `mutation_steps` (`has_on_fly_mutation_steps`) and disqualify on that instead. DELETE-typed commands are always kept by `filterMutationCommands`, so the poisoning direction of #107145 stays disqualifying, as does an unmaterialized lightweight delete via `hasLightweightDelete`.

The new test section proves the corner: with a pending `UPDATE w` and a query reading only `v`, the `apply_mutations_on_fly = 1` prime must populate the cache and an `apply_mutations_on_fly = 0` reuse must consume it (the read path skips the cache while a data mutation is pending, so the `= 0` side is the one that can hit). The section fails before this commit (verified against the PR-built binary: no entry is written) and the read side was verified to hit once an entry exists.

PR: #112947
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
STOR: query condition cache with apply_mutations_on_fly, patch parts or a row policy before PREWHERE -> wrong (too few rows).
Effect in the production build a394e92: its upstream test(s) 03229_query_condition_cache_on_fly_mutations, 03229_query_condition_cache_row_policy fail on it and pass on official 26.8.8.8, run on isolated servers (evidence/fix_ci_20260925/upstream_repro/server_triage_PROD263_vs_UP2688.tsv).
Upstream patch unchanged, with its test(s): 03229_query_condition_cache_on_fly_mutations,03229_query_condition_cache_row_policy.

Co-Authored-By: Claude Opus 5.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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants