Repository navigation
Fix query condition cache poisoning by on-fly mutations - #107145
Conversation
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]>
Pre-PR validation gate
Found by investigating the flaky Session id: cron:clickhouse-worker-slot-28:20260611-030400 |
|
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 ( |
|
Workflow [PR], commit [b7182f6] Summary: ✅
AI ReviewSummaryThis PR prevents Final VerdictStatus: ✅ Approve |
…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]>
Pre-PR validation gate (updated for the WHERE-path fixup cab744b)
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]>
Pre-PR validation gate (updated for the row-policy /
|
| # | 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]>
Pre-PR validation gate (test-only follow-up: row-policy Fast-test fix + patch-parts case)
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]>
Pre-PR validation gate (patch-part test determinism fixup, commit b7182f6)
Session id: cron:clickhouse-worker-slot-2:20260611-162800 |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 30/30 (100.00%) | Lost baseline coverage: none · Uncovered code |
|
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) |
|
@groeneai does it mean that you want to disable PREWHERE in case of presence of any lightweight mutations? |
|
@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 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. |
|
Hi — this looks like a backport candidate for |
|
Hi @groeneai @alesapin — a couple of suggestions to make this PR easier for reviewers and the changelog reader. Description (currently
Ignore this if the current title/body is intentional. |
Cherry pick #107145 to 26.3: Fix query condition cache poisoning by on-fly mutations
Cherry pick #107145 to 26.4: Fix query condition cache poisoning by on-fly mutations
Cherry pick #107145 to 26.5: Fix query condition cache poisoning by on-fly mutations
Backport #107145 to 26.4: Fix query condition cache poisoning by on-fly mutations
Backport #107145 to 26.5: Fix query condition cache poisoning by on-fly mutations
Backport #107145 to 26.3: Fix query condition cache poisoning by on-fly mutations
…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
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]>
Changelog category (leave one):
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 beforePREWHERE. A query reading withapply_mutations_on_fly = 1could poison the cache so that a later query withapply_mutations_on_fly = 0and 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 ofPREWHERE: 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 aPREWHERE/WHEREpredicate so later queries with the same predicate can skip non-matching marks.On-fly mutations (lightweight
UPDATE/DELETEapplied viaapply_mutations_on_fly) and patch parts are spliced into the readers chain ahead ofPREWHERE, so they drop or rewrite rows beforePREWHEREevaluates 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 thePREWHERE/WHEREpredicate 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 whenrow_level_filteris set.The effect was masked at large
index_granularity(the granule is recorded as "may match" andPREWHEREre-runs per row) and surfaced deterministically at smallindex_granularity, which is why03047_on_fly_update_deletewas flaky under randomizedindex_granularity.The read path already bypasses the cache when on-fly mutations or patch parts are active. This makes the write path symmetric:
MergeTreeSelectProcessornow skips the cache write/attribution whenever the read task applies mutations beforePREWHERE(or a row policy filter is set), mirroring the existingreadersChainCanSkipMarksBeforePrewhereguard 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_mutationscovers both on-flyDELETEand on-flyUPDATEatindex_granularity = 1, and03229_query_condition_cache_row_policy.shcovers the row-policy poisoning vector; both fail before this change and pass after.Version info
26.6.1.1043(included in26.6and later)26.5.6.46,26.4.5.134,26.3.17.50