Skip to content

Do not move conditions to PREWHERE when PREWHERE is deferred after FINAL - #109703

Merged
yariks5s merged 13 commits into
masterfrom
yarik/fix-prewhere-final-defer-escape
Jul 29, 2026
Merged

yariks5s merged 13 commits into
masterfrom
yarik/fix-prewhere-final-defer-escape

Conversation

@yariks5s

@yariks5s yariks5s commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

Before this change, when PREWHERE is applied after FINAL (because apply_prewhere_after_final = 1, or apply_row_policy_after_final = 1 with a non-sorting-key row policy), optimizePrewhere could still move WHERE conditions into PREWHERE and optimizeDirectReadFromTextIndex could rewrite the deferred PREWHERE to a direct index read. Both escape the deferral: the moved/rewritten condition runs during reading, before the deferred row policy, which can expose policy-hidden rows to the predicate (e.g. intDiv(1, k-2) throwing ILLEGAL_DIVISION) or produce results that ignore FINAL deduplication. This PR skips those two optimizations whenever the PREWHERE is deferred after FINAL, and keeps deferred_prewhere_info in sync in updatePrewhereInfo.

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

Prevents bugs when using deferred prewhere with optimise_move_to_prewhere=1. When PREWHERE is applied after FINAL, moving WHERE conditions to PREWHERE must be skipped, otherwise they escape the deferral and run before a deferred row policy

Version info

  • Merged into: 26.8.1.389 (included in 26.8 and later)

@yariks5s
yariks5s marked this pull request as draft July 7, 2026 19:22
@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7c6e042]

Summary: ✅


AI Review

Summary

This PR makes deferred-PREWHERE handling consistent for FINAL reads: it stops optimizePrewhere from moving WHERE predicates into a PREWHERE that must run after FINAL, and it centralizes deferred-PREWHERE resync in ReadFromMergeTree::updatePrewhereInfo for late rewrites such as text-index optimization. I did not find a remaining correctness bug in the current code, but one focused text-index regression path is still unproven by the new tests.

Tests
  • ⚠️ [tests/queries/0_stateless/04653_text_index_prewhere_deferred_after_final.sql:27] The new whole-token case only proves the deferred PREWHERE stays untouched when no matching text-index query was registered anywhere else. The new updatePrewhereInfo sync is needed in the narrower case where the same text-index predicate also survives in WHERE (or another non-deferred carrier), so the deferred PREWHERE gets rewritten after deferred_prewhere_info was already snapshotted. Please add one focused FINAL case with the same text predicate in both PREWHERE and WHERE, or assert the rewritten deferred filter in EXPLAIN, so removing the new sync would actually fail a test.
Final Verdict

⚠️ The code change looks correct, but the regression coverage is still weaker than the contract around deferred text-index PREWHERE rewrites.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 7, 2026
@yariks5s
yariks5s marked this pull request as ready for review July 8, 2026 17:17
SELECT count() FROM (EXPLAIN actions=1 SELECT k FROM t_text_defer_final FINAL PREWHERE hasPhrase(text, 'hello')) WHERE explain LIKE '%__text_index_idx%';
SELECT count() FROM (EXPLAIN actions=1 SELECT k FROM t_text_defer_final FINAL PREWHERE hasPhrase(text, 'hello')) WHERE explain LIKE '%Deferred prewhere filter column%';

-- whole-token needles: the deferred filter currently runs without the index tokenizer rewrite,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These whole-token needles no longer exercise the tokenizer/preprocessor rewrite that motivated the deferred-PREWHERE sync. With hello / goodbye, both the stale deferred DAG and the rewritten DAG produce the same rows, so this test now only proves that direct index read is disabled and that filtering happens after FINAL.

Please keep one tokenizer-sensitive case here (or assert the rewritten deferred filter expression in EXPLAIN) so the updatePrewhereInfo sync in ReadFromMergeTree is actually covered.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this — the suppression doesn't actually happen. For a deferred PREWHERE the rewrite is a no-op: the deferred filter is excluded from index analysis, so its search queries are never registered in MergeTreeIndexConditionText and the replacer finds nothing to rewrite (not even the tokenizer injection). So optimized stays false and the WHERE path is unaffected.

Ran your exact shape to confirm:

SELECT k FROM t3 FINAL PREWHERE hasPhrase(text, 'hello wor') WHERE hasToken(msg, 'foo')
SETTINGS apply_prewhere_after_final = 1, query_plan_direct_read_from_text_index = 1;
Filter column: __text_index_midx_hasToken_2300886…   <- WHERE direct read is intact
    Prewhere filter column: hasPhrase(text, 'hello wor')
    Deferred filters (applied after FINAL)
      Deferred prewhere filter column: hasPhrase(text, 'hello wor')

yariks5s added 2 commits July 23, 2026 22:08
…final-defer-escape

# Conflicts:
#	src/Processors/QueryPlan/Optimizations/optimizeDirectReadFromTextIndex.cpp
#	src/Processors/QueryPlan/Optimizations/optimizePrewhere.cpp
@nihalzp nihalzp self-assigned this Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 39/41 (95.12%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is a query-planner correctness fix that only changes behavior when PREWHERE or a row policy is deferred after FINAL (the apply_prewhere_after_final / apply_row_policy_after_final paths); the guards short-circuit for any non-FINAL read. The three flagged ClickBench queries (Q4, Q15, Q30) are plain SELECTs that use none of those features, and each shows flat CPU time against its wall-clock delta, confirming the movements are within-baseline variance rather than a PR effect. All three were deterministically suppressed as within-envelope, and that is the correct call. No action needed.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 272 322 +18.4% <0.0001 cache: CPU is flat (2792→2775 ms) while wall time rises +18.4%; the delta is envelope variance, and this FINAL-deferral fix does not touch Q30's read path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 366a1ecb-4cbf-43f0-ae44-69c4dde37759
  • MIRAI run: 26152aee-b596-401a-be70-fa1ac6e1c02c
  • PR check IDs:
    • clickbench_842424_1785345959
    • clickbench_842733_1785346235
    • clickbench_842836_1785346258
    • tpch_adapted_1_official_843168_1785346414
    • tpch_adapted_1_official_843364_1785346500
    • tpch_adapted_1_official_843521_1785346564

@yariks5s
yariks5s added this pull request to the merge queue Jul 29, 2026
@yariks5s

Copy link
Copy Markdown
Member Author

⚠️ [tests/queries/0_stateless/04653_text_index_prewhere_deferred_after_final.sql:27] The new whole-token case only proves the deferred PREWHERE stays untouched when no matching text-index query was registered anywhere else. The new updatePrewhereInfo sync is needed in the narrower case where the same text-index predicate also survives in WHERE (or another non-deferred carrier), so the deferred PREWHERE gets rewritten after deferred_prewhere_info was already snapshotted. Please add one focused FINAL case with the same text predicate in both PREWHERE and WHERE, or assert the rewritten deferred filter in EXPLAIN, so removing the new sync would actually fail a test.

@groeneai please create a new PR which adds this test after the current PR is merged.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I will open a follow-up pull request adding that focused case once #109703 is merged, and I will post the link here.

I am not opening it before the merge: the case has to exercise isPrewhereDeferredAfterFinal and the new deferred_prewhere_info assignment in updatePrewhereInfo, and neither exists on master yet (both grep to zero hits there), so a test written now would pass for the wrong reason, and a pull request stacked on an unmerged branch gets no CI.

The follow-up will extend 04653_text_index_prewhere_deferred_after_final with a FINAL case carrying the same text predicate in both PREWHERE and WHERE, plus an EXPLAIN assertion on the rewritten deferred filter, and I will confirm that reverting the sync reddens it before I open the pull request.

Merged via the queue into master with commit 51a4cd5 Jul 29, 2026
352 of 353 checks passed
@yariks5s
yariks5s deleted the yarik/fix-prewhere-final-defer-escape branch July 29, 2026 23:22
@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up is open: #112507

It extends 04653_text_index_prewhere_deferred_after_final with a FINAL case carrying the same text predicate in both PREWHERE and WHERE, over an index declared with preprocessor = lower(text) and mixed-case data queried with a lower-case needle, so only the rewritten predicate matches. The duplicate WHERE is required rather than stylistic: a deferred PREWHERE is excluded from index analysis, so the WHERE copy is the only thing that registers the text index and lets a later rewrite fire. Without it the query returns nothing even on a correct build.

Your acceptance criterion is met. With ReadFromMergeTree.cpp:3293-3294 deleted, 04653 fails and 04652 still passes. Because the appended block is three identical 1 lines I measured the three assertions individually rather than reading the runner diff: the new SELECT moves from one row to none while both controls hold, so the failure is the sync and not a collapsed fixture. The mutation compiled, and restoring it relinked bit-identically.

One correction to what I promised. I said I would also add an EXPLAIN assertion on the rewritten deferred filter, and that is not achievable. The deferred block in describeActions prints only deferred_prewhere_info->prewhere_column_name and never dumps prewhere_actions, unlike the row_level_filter branch just above it, and the rewrite re-aliases its result back to the original name. So EXPLAIN actions=1 is byte-identical with and without the sync, which I verified by capturing both arms and diffing them. The Prewhere info block does show the rewrite, but that is query_info.prewhere_info written on the line above the sync, so asserting there would be blind to it. The two EXPLAIN assertions I did ship are non-vacuity controls: they pin that the filter is still deferred and that the index is still registered on the mutation arm.

The test is tag-free and passed 50 of 50 runs at four-way parallelism.

@clickgapai

Copy link
Copy Markdown
Contributor

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

Description (currently incomplete):

  • Why: The body is essentially the template: the Closes/Related lines are unfilled placeholders and there is no explanation of what was broken, how it manifested (wrong results / ILLEGAL_DIVISION when a moved condition runs before a deferred row policy), or that the direct-read-from-text-index path is also affected. A reviewer cannot understand the fix's scope from the body alone.

  • Suggested addition:

    Before this change, when PREWHERE is applied after FINAL (because apply_prewhere_after_final = 1, or apply_row_policy_after_final = 1 with a non-sorting-key row policy), optimizePrewhere could still move WHERE conditions into PREWHERE and optimizeDirectReadFromTextIndex could rewrite the deferred PREWHERE to a direct index read. Both escape the deferral: the moved/rewritten condition runs during reading, before the deferred row policy, which can expose policy-hidden rows to the predicate (e.g. intDiv(1, k-2) throwing ILLEGAL_DIVISION) or produce results that ignore FINAL deduplication. This PR skips those two optimizations whenever the PREWHERE is deferred after FINAL, and keeps deferred_prewhere_info in sync in updatePrewhereInfo.

Ignore this if the current title/body is intentional.

pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jul 30, 2026
PR ClickHouse#109703 added a sync in ReadFromMergeTree::updatePrewhereInfo that copies a
later PREWHERE rewrite into deferred_prewhere_info when the PREWHERE is deferred
after FINAL. Neither test it shipped makes that line load-bearing: deleting it
leaves both green. 04653 states as much itself, that the deferred filter runs
without the index tokenizer rewrite so its expected results must not depend on
it, which is exactly the property the sync controls.

deferFiltersAfterFinalIfNeeded snapshots deferred_prewhere_info, and only after
that does the text-index pass rewrite the PREWHERE and call updatePrewhereInfo.
The isPrewhereDeferredAfterFinal gate in that pass suppresses only the
direct-read/virtual-column half, so the tokenizer/preprocessor rewrite still
fires on a deferred PREWHERE and the sync is what makes the post-FINAL filter
use the rewritten DAG.

The new case uses preprocessor = lower(text) with mixed-case data and a
lower-case needle so that only the rewritten predicate matches. The predicate is
duplicated in WHERE because a deferred PREWHERE is excluded from index analysis
and text is not a sorting-key column, which makes the WHERE copy the only
registrant of the text index; without it the rewrite never fires. use_skip_indexes
and use_skip_indexes_if_final are pinned per statement because the runner
randomizes the latter 50/50 and a false draw unregisters the index and would make
the case silently vacuous rather than failing.

With the sync reverted the new query returns nothing instead of one row while
both controls and every pre-existing assertion stay green. Asserting the
rewritten deferred filter in EXPLAIN is not possible: the deferred block prints
only the filter's column name and the rewrite preserves that name, so EXPLAIN
actions=1 is byte-identical with and without the sync.

Related: ClickHouse#109703
pull Bot pushed a commit to CrazyForks/ClickHouse that referenced this pull request Jul 30, 2026
…p-deferred-prewhere-test

Add a test pinning the deferred-PREWHERE sync from ClickHouse#109703
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants