Skip to content

Add test: Lazy FINAL direct text-index read combined with is_deleted deletion filter is untested - #109705

Closed
clickgapai wants to merge 13 commits into
ClickHouse:masterfrom
clickgapai:qa-bot/coverage-pr106894
Closed

clickgapai wants to merge 13 commits into
ClickHouse:masterfrom
clickgapai:qa-bot/coverage-pr106894

Conversation

@clickgapai

@clickgapai clickgapai commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

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

This is a test-only PR — no source code changes. Please review: test quality, whether the claimed coverage gaps are real, and whether test output makes sense.

Adds test coverage for 1 untested code path, found during automated review of PR #106894.
The PR fixes wrong results when a ReplacingMergeTree FINAL query filtering on a text index runs with query_plan_optimize_lazy_final=1 and query_plan_direct_read_from_text_index=1. (1) In createNonIntersectingPlan (optimizeLazyFinal.cpp:219-220) it now copies the source step's `IndexReadTas …

1. Lazy FINAL direct text-index read combined with is_deleted deletion filter is untested
src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:219, src/Processors/QueryPlan/Optimizations/optimizeLazyFinal.cpp:234
Risk: In createNonIntersectingPlan the new setIndexReadTasks copy at optimizeLazyFinal.cpp:219-220 runs, then addIsDeletedFilter (line 234-235) adds an is_deleted = 0 FilterStep on the same reading step; EXPLAIN confirms ReadFromMergeTree outputs __text_index_idx_... and is_deleted with a stacked filter. Risk: if this interaction breaks (e.g. is_deleted filter skipped or column not read alongside the text-index virtual column), deleted rows silently resurface in FINAL results, or …
What's unique vs PR tests: The PR test 02346_text_index_bug106809.sql uses ReplacingMergeTree(version) with no is_deleted column, so it never exercises addIsDeletedFilter alongside the copied index read tasks. This test adds the ReplacingMergeTree(version, is_deleted) variant, uniquely guarding the deletion-filter + direct-text-index interaction.
Try it on ClickHouse Fiddle

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Not applicable — test-only change.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickgapai

Copy link
Copy Markdown
Contributor Author

Pre-PR Validation Gate (per ClickGap pipeline):

a) Deterministic repro? ✅
Test exercises the previously-uncovered branch and passes (correct behaviour).

b) Root cause explained? ✅
optimizeLazyFinal.cpp:219-220 (setIndexReadTasks copy) executes in the same non-intersecting plan as the pre-existing is_deleted handling at lines 145-196 and 234-235; only the no-is_deleted combination is covered by the PR test.

c) Fix matches root cause? ✅
N/A for coverage gap — this PR adds a regression test, not a fix. Asserts current correct behaviour at the cited line.

d) Test intent preserved? / New tests added? ✅
New regression test added: 04508_lazy_final_text_index_is_deleted.sql.

e) Both directions demonstrated? ✅
Test passes (MATCH) on master proving current correctness; would fail if the cited branch regressed. Single-direction is the correct shape for a coverage gap test.

f) Fix is general, not a narrow patch? ✅
Test asserts the invariant at the cited line — covers the branch, not a specific input shape.

@tiandiwonder tiandiwonder self-assigned this Jul 8, 2026
SET min_filtered_ratio_for_lazy_final = 0;
SET query_plan_direct_read_from_text_index = 1;

DROP TABLE IF EXISTS tab;

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.

optional: duplicate DROP TABLE IF EXISTS tab; — line 4 already drops it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Pushed a commit. Here's the actual diff so you can review what was committed:

diff --git a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
index 7d62bf6c66e..f99d2f70d09 100644
--- a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
+++ b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
@@ -6,8 +6,6 @@ SET query_plan_optimize_lazy_final = 1;
 SET min_filtered_ratio_for_lazy_final = 0;
 SET query_plan_direct_read_from_text_index = 1;
 
-DROP TABLE IF EXISTS tab;
-
 CREATE TABLE tab
 (
     id UInt64,

If this isn't the change you wanted, please describe the edit concretely and I'll retry.

Line-4 DROP already clears `tab` before the SET block; the second
DROP after the SETs was redundant.

Requested by @tiandiwonder in ClickHouse#109705 (comment)
Assert the lazy-FINAL plan carries both the `__text_index_idx_*` direct read
and the `is_deleted = 0` filter, and add an intersecting/non-intersecting
variant to cover the union path with a deletion filter.

Requested by @tiandiwonder in ClickHouse#109705 (comment)
Randomizer can set it to 0, disabling skip indexes under FINAL so the
direct __text_index_idx_ read is never produced (EXPLAIN assert at
.sql:33-37 breaks). Session SET overrides the randomized default.

Requested by @tiandiwonder in ClickHouse#109705 (comment)
Comment on lines +51 to +54
-- Mixed intersecting and non-intersecting parts with is_deleted: the intersecting
-- pair (parts 1+2 overlap on id 2) forces the regular-FINAL branch, while the
-- non-intersecting part 3 (id 10) takes the direct-read + is_deleted branch. Lazy
-- FINAL unions the two, so this exercises the union path with a deletion filter.

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.

this comment overstates the coverage: no query here actually produces the union — text-index pruning drops the other side's parts before the split, so zzz collapses to the fully-replaced non-intersecting plan and aaa/bbb/ccc to a regular FINAL read (checked via EXPLAIN). either reword it to what's actually exercised, or add a spanning query like SELECT count() FROM tab FINAL WHERE str IN ('aaa', 'zzz') (returns 2), which does yield the union with the is_deleted = 0 branch — though the IN filter then stays above the union and isn't rewritten to a direct index read, so it covers union + deletion filter, not union + direct read.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Pushed a commit. Here's the actual diff so you can review what was committed:

diff --git a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.reference b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.reference
index 54fbf89c6cde..925f4dfa50d4 100644
--- a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.reference
+++ b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.reference
@@ -9,3 +9,6 @@ is_deleted filter in plan	1
 1
 1
 1
+2
+union in plan	1
+is_deleted filter in union plan	1
diff --git a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
index ba3b59967c46..9077ee025bb0 100644
--- a/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
+++ b/tests/queries/0_stateless/04508_lazy_final_text_index_is_deleted.sql
@@ -48,10 +48,12 @@ WHERE explain LIKE '%is_deleted = 0%';
 
 DROP TABLE tab;
 
--- Mixed intersecting and non-intersecting parts with is_deleted: the intersecting
--- pair (parts 1+2 overlap on id 2) forces the regular-FINAL branch, while the
--- non-intersecting part 3 (id 10) takes the direct-read + is_deleted branch. Lazy
--- FINAL unions the two, so this exercises the union path with a deletion filter.
+-- Mixed intersecting and non-intersecting parts with is_deleted. The single-token
+-- queries below do NOT produce a union: text-index pruning drops the other side's
+-- parts before the plan split, so each collapses to one side -- 'aaa'/'bbb'/'ccc'
+-- to the intersecting regular-FINAL replacing read, 'zzz' to the non-intersecting
+-- direct-read + is_deleted branch (verified via EXPLAIN). They still assert correct
+-- replacement/deletion on both sides. The union itself is exercised separately below.
 CREATE TABLE tab
 (
     id UInt64,
@@ -73,4 +75,22 @@ SELECT count() FROM tab FINAL WHERE str = 'ccc';    -- 1: survivor from the inte
 SELECT count() FROM tab FINAL WHERE str = 'zzz';    -- 1: from the non-intersecting part
 SELECT count() FROM tab FINAL PREWHERE str = 'zzz'; -- 1: same via PREWHERE
 
+-- A query spanning both sides ('aaa' intersecting + 'zzz' non-intersecting) is what
+-- actually yields the union of the regular-FINAL and non-intersecting plans. The IN
+-- filter stays above the union (not rewritten to a direct index read), so this covers
+-- the union path together with the deletion filter (`is_deleted = 0`), not a direct read.
+SELECT count() FROM tab FINAL WHERE str IN ('aaa', 'zzz');  -- 2: one survivor per side
+
+SELECT 'union in plan', count() > 0 FROM
+(
+    EXPLAIN actions = 1 SELECT count() FROM tab FINAL WHERE str IN ('aaa', 'zzz')
+)
+WHERE explain LIKE '%Union%';
+
+SELECT 'is_deleted filter in union plan', count() > 0 FROM
+(
+    EXPLAIN actions = 1 SELECT count() FROM tab FINAL WHERE str IN ('aaa', 'zzz')
+)
+WHERE explain LIKE '%is_deleted = 0%';
+
 DROP TABLE tab;

If this isn't the change you wanted, please describe the edit concretely and I'll retry.

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

clickhouse-gh Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8a1aa1b]

Summary: ✅


AI Review

Summary

This PR adds a stateless regression test for lazy FINAL on ReplacingMergeTree(version, is_deleted) when a text-index predicate is rewritten into a direct read. The current head closes the earlier coverage gaps around PREWHERE and visible is_deleted, so I do not see a remaining correctness problem in the added assertions themselves.

Findings

💡 Nits

  • [tests/queries/0_stateless/04700_lazy_final_text_index_is_deleted.sql:1] The remaining concern is test organization rather than correctness: maintainers already asked to fold this is_deleted coverage into 02346_text_index_bug106809.sql instead of keeping a separate 04700 file, and the mixed-parts section here overlaps coverage that already exists in 04092_lazy_final_is_deleted.sh rather than guarding a new direct-read carrier. Suggested fix: move the all-non-intersecting is_deleted case into 02346 and drop the standalone file / redundant mixed section.
Final Verdict

No new blocker or major correctness findings. The only remaining concern is the unresolved request to consolidate this coverage into 02346 instead of merging a standalone 04700 test.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 8, 2026
@clickgapai

Copy link
Copy Markdown
Contributor Author

CI failure in Stateless tests (amd_asan_ubsan, distributed plan, parallel, 2/2), Stateless tests (amd_tsan, parallel, 2/2) appears to be unrelated breakage and is not related to this change. Let me know if you'd like me to merge master and retrigger CI.

clickgapai and others added 2 commits July 8, 2026 12:19
`optimize_lazy_final` is computed as `query_plan_optimize_lazy_final &&
allow_experimental_analyzer` (QueryPlanOptimizationSettings.cpp), so in the
old-analyzer CI lane the optimization never fires and the test's plan-shape
assertions fail deterministically (3/3 reruns) while query results stay correct.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.28% 86.30% +0.02%
Functions 91.49% 91.50% +0.00%
Branches 78.72% 78.77% +0.04%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 159 line(s), 41 function(s) across 48 file(s) · Details

Top files
  • src/Functions/FunctionShowCertificate.cpp: 38 line(s), 4 function(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h: 14 line(s), 32 function(s)
  • src/Parsers/ASTColumnsTransformers.cpp: 8 line(s), 2 function(s)
  • src/Processors/QueryPlan/LazilyUnorderedReadFromMergeTree.cpp: 8 line(s), 1 function(s)
  • src/Functions/array/arrayNorm.cpp: 7 line(s)

Full report

alexey-milovidov and others added 2 commits July 31, 2026 23:24
04508 is shared by 9 other tests added to this PR; rename to
the next sequential number after the current max (04664) to
give the test an unambiguous number and satisfy the style
check's test_numbers_check.
@clickgapai

Copy link
Copy Markdown
Contributor Author

CI failure in Style check

Root cause: Ten tests in this PR all share the number 04508; the style check's test_numbers_check can flag this as ambiguous/conflicting during the CI run depending on which files are visible at snapshot time.
Fix applied: Renamed 04508_lazy_final_text_index_is_deleted.{sql,reference} → 04665_lazy_final_text_index_is_deleted.{sql,reference} via git mv, placing the test immediately after the current max (04664) with no gap. No test content was changed.
Verification:

  • Test passes locally ✓
  • Quality gates passed ✓
  • Adversarial reviewer approved ✓

Pushed Fix: Renamed 04508_lazy_final_text_index_is_deleted.{sql,reference}→04665_lazy_final_text_index_is_deleted.{sql,reference}viagit mv, placing the test immediately after the current max (04664) with no gap. No test content was changed..

04665 is already used by two tests merged into master
(04665_remote_engine_settings_clause and
04665_valueless_setting_ast_json_and_secret_parts); rename to
04700, the first free number after master's sequential max of 04699.
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Dear @tiandiwonder, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@rschu1ze

rschu1ze commented Aug 10, 2026 •

Copy link
Copy Markdown
Member

@groeneai Look at exising test tests/queries/0_stateless/02346_text_index_bug106809.sql and thing about how it can be extended in an intelligent way instead of adding some new test on the side. While at it, please remove all slob comments (there is lots of them in 04700_lazy_final_text_index_is_deleted.sql).

To counter the argument that we only add but never extend tests to make red test analysis easier: 02346_text_index_bug106809 didn't have a single test failure in the past two months: history

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I will fold the is_deleted case into tests/queries/0_stateless/02346_text_index_bug106809.sql as an appended section rather than a separate file, and drop the commentary. I will follow up here with the PR (or with my findings if it turns out the extension is not worth it).

@groeneai

Copy link
Copy Markdown
Collaborator

#114253 does this: the is_deleted case is now an appended third section of
02346_text_index_bug106809.sql, existing lines untouched, and the commentary is gone.

About a third of this PR carried over. optimizeLazyFinal.cpp:321 bails out of lazy FINAL entirely
when index read tasks exist and any part is intersecting, so the combination tested here is reachable
only from an all-non-intersecting part set. Confirmed by running it: with merges stopped so the parts
stay intersecting, the plan shows FINAL: 1 and no is_deleted = 0 step while the counts still
pass. The mixed-parts half therefore cannot reach what it targets, and that shape is already covered
by 04092_lazy_final_is_deleted.sh. Of its four plan-shape probes I kept one, asserting that the
direct index read and the is_deleted filter land in the same plan, since the count assertions alone
also pass through a regular FINAL read.

Something I found in the existing file while doing this: line 9 pins
query_plan_direct_read_from_text_index = 1 to exercise the direct read, but that was already
defeated in about half of all runs, because the flag is conjunctive with use_skip_indexes, which
FINAL clears when the randomized use_skip_indexes_if_final is 0. The file is also inert in the
old-analyzer lane. #114253 pins both, so the two existing sections now test what they claim, with
their expected values unchanged.

Disposition of this PR is yours and @ Ergus's call, so I have left it open.

The PREWHERE queries were result-only, so a regular FINAL read would keep
them green. Assert `__text_index_idx_*` and `is_deleted = 0` in both
PREWHERE plans.

Requested by @clickhouse-gh[bot] in ClickHouse#109705 (comment)
The prior assertions all hid `is_deleted` (count()/id only), exercising only the
branch where `createNonIntersectingPlan` injects and later strips it. Adds the
`SELECT id, is_deleted` WHERE/PREWHERE forms plus EXPLAIN proof of the direct read.

Requested by @clickhouse-gh[bot] in ClickHouse#109705 (comment)
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8a1aa1bf5 with master 41453250d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 694.55 MiB 691.54 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

6 translation units recompiled, 4 s compile time in total, 6 of them have a recent master baseline.

Job report

@rschu1ze

Copy link
Copy Markdown
Member

Superseded by #114253

@rschu1ze rschu1ze closed this Aug 31, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 3, 2026
ClickHouse#106894 fixed lazy FINAL dropping rows when a query reads directly from a
text index. Its test uses ReplacingMergeTree(version) with no is_deleted
column, so it never exercises addIsDeletedFilter alongside the copied
setIndexReadTasks. Of the 12 stateless tests that set
query_plan_optimize_lazy_final, only this one has a text index and only
04092 / 04207 have an is_deleted column, so that intersection was untested.

Append a third section covering it: one merged non-intersecting part, a
replacement deletion, and assertions that the tombstoned row is dropped
through WHERE and PREWHERE. optimizeLazyFinal.cpp:321 bails out of lazy
FINAL entirely when index read tasks exist and any part is intersecting, so
the combination is reachable only from an all-non-intersecting part set;
that is why the fixture merges into a single part and why the mixed-parts
shape is not covered here (04092 already covers it).

One assertion checks that the plan really took that shape, because the value
assertions alone also pass through a regular FINAL read. It names the EXPLAIN
options it depends on, since a bare EXPLAIN takes them from the session
setting explain_query_plan_default and the token it matches is only printed
by the pretty renderer.

Three settings are pinned in the file's existing top-level block.
use_skip_indexes_if_final is randomized and at 0 disables skip indexes under
FINAL, so the existing query_plan_direct_read_from_text_index pin was already
defeated in roughly half of all runs;
use_skip_indexes_if_final_exact_mode must stay in sync with it, since the
pair (1, 0) returns deliberately approximate results under FINAL and CI never
generates that pair on its own; enable_analyzer is required because lazy
FINAL is gated on the new analyzer. Expected values of the existing sections
are unchanged.

min_bytes_for_wide_part and index_granularity are pinned to their defaults on
the new table only, so that the three rows stay in a single granule: three
randomized MergeTree settings together write a Wide part with one row per
granule, and a randomized index_granularity of 1 or 2 splits the rows the
same way. The text index then selects a granule subset and lazy FINAL
declines.

Extends the existing test instead of adding a separate one, as requested on
ClickHouse#109705
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-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants