Skip to content

Fix lazy FINAL over a text index read on a Nullable, floating-point or mixed-direction sorting key - #122534

Merged
fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-lazy-final-text-index-unsafe-key
Sep 29, 2026
Merged

fm4v merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-lazy-final-text-index-unsafe-key

Conversation

@groeneai

@groeneai groeneai commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #106809

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 and a LOGICAL_ERROR (Column ... already added for reading) for a FINAL query with query_plan_optimize_lazy_final = 1 that reads a text index directly, when the ReplacingMergeTree sorting key is Nullable, floating-point, or mixes ASC and DESC columns.

Description

On 26.8.10.6, with only query_plan_optimize_lazy_final = 1 set, SELECT count() FROM tab FINAL WHERE str = 'ccc' over a ReplacingMergeTree with a Nullable(UInt64) sorting key and a text index on str returns 0 instead of 1, and ... FINAL PREWHERE str = 'bbb' WHERE str = 'bbb' fails with LOGICAL_ERROR. Found by AST fuzzer (amd_debug, targeted, old_compatibility) on #122492 (report, job, STID 4792-5e4c; 6 PRs in 30 days).

Root cause: for a key the parts splitter cannot compare and for mixed sort directions, trySplitNonIntersectingParts returns "not replaced" before the checks that keep a text index read (#106894) and a query that stops reading early (#110576) away from the set-building plan. That plan reads the __text_index_* column without the read tasks that produce it, so rows are dropped, or a WHERE repeating the PREWHERE registers the same column again and throws.

Fix: apply the same two conditions right after the split. Such reads get the regular FINAL read, as with a comparable key, and a small LIMIT regains its early exit (LIMIT 10 over 4M rows: 3.2M selected rows before, 0.69M after). Lazy FINAL still applies to these keys otherwise. The same site covers a third return, a full replacement selecting nothing, which no text index read reached in my probes. My open #112526 re-checks the same conditions at two of the returns inside a larger change.

Validation: 02346 gains Nullable-key and mixed ASC/DESC-key sections, 04539 early-exit rows and a positive control for a float and a mixed-direction key. Both fail on master and pass 50 randomized runs each; dropping either condition fails exactly one of them. Float32, BFloat16 and LowCardinality(Nullable(String)) keys and the merge(), remote(), cluster() and ReplicatedReplacingMergeTree routes also fail on master and pass with the fix.

Reproducer
CREATE TABLE tab (id Nullable(UInt64), version UInt64, str String, INDEX idx(str) TYPE text(tokenizer = array))
ENGINE = ReplacingMergeTree(version) ORDER BY id SETTINGS allow_nullable_key = 1;
SYSTEM STOP MERGES tab;
INSERT INTO tab VALUES (1, 1, 'aaa'), (2, 1, 'bbb');
INSERT INTO tab VALUES (2, 2, 'bbb_updated'), (3, 1, 'ccc');
INSERT INTO tab VALUES (10, 1, 'zzz');
SET query_plan_optimize_lazy_final = 1;
SELECT count() FROM tab FINAL WHERE str = 'ccc';                      -- 0, expected 1
SELECT count() FROM tab FINAL PREWHERE str = 'bbb' WHERE str = 'bbb'; -- LOGICAL_ERROR, expected 1

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/122534]

Version info

  • Merged into: 26.10.1.1000-master (included in 26.10 and later)

groeneai and others added 4 commits September 27, 2026 11:09
…oint sorting key

`trySplitNonIntersectingParts` returns "not replaced" for a primary key the parts splitter
cannot compare (`isSafePrimaryKey`: `Nullable`, `Float*`, `BFloat16`, `Variant`, `Dynamic`,
`JSON`, also nested), for mixed `ASC`/`DESC` key columns, and when a full non-intersecting
replacement selects nothing. All three return before the checks that keep a direct read from
a text index (ClickHouse#106894) and a query that stops reading early (ClickHouse#110576) away from the
set-building plan, so `optimizeLazyFinal` built that plan anyway. Its read inherits the
`__text_index_*` column name from `getAllColumnNames` but not the index read tasks that
produce it: the filter drops rows, and when the `WHERE` repeats the `PREWHERE` predicate,
`set_plan.optimize` rewrites the copy to the same name and `createReadTasksForTextIndex`
throws `Column __text_index_... already added for reading`.

Apply the same two conditions right after the split. On every path that reaches the new
check with either condition true the reading step is still untouched, so the query keeps the
regular `FINAL` read, as it already does for a comparable key. The in-split checks stay, as
they must run before the partial split narrows the reading step. With both conditions false
the control flow is unchanged.

On 26.8.10.6, `SELECT count() FROM tab FINAL WHERE str = 'ccc'` with only
`query_plan_optimize_lazy_final = 1`, over a `ReplacingMergeTree` with a `Nullable(UInt64)`
sorting key and a text index on `str`, returns 0 instead of 1.

Found by `AST fuzzer (amd_debug, targeted, old_compatibility)` (STID 4792-5e4c) on
ClickHouse#122492:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122492&sha=f6b330abde632fb2c271eb66e098d4230b4a7004&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%2C%20old_compatibility%29

Tests: `02346_text_index_bug106809` gains a `Nullable`-key section (its `PREWHERE` + `WHERE`
row is 1 because `PREWHERE` is evaluated before `FINAL`), and
`04539_lazy_final_read_in_order_limit_disabled` gains `Float64`-key rows for both gates plus
a positive control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ex_bug106809`

Such a key reaches a separate early return of `trySplitNonIntersectingParts`, which the `Nullable`-key section does
not cover. Both new rows fail on master: a `LOGICAL_ERROR` for the `PREWHERE` + `WHERE` row, 0 instead of 1 for
the `WHERE`-only row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…2346_text_index_bug106809`

The section's two rows check results only, so they would also pass if the text index stopped
being read directly and the section no longer reached the fixed path. Add the `EXPLAIN` check
that the `Nullable`-key section already has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…39_lazy_final_read_in_order_limit_disabled`

A sorting key mixing `ASC` and `DESC` columns takes its own early return in
`trySplitNonIntersectingParts`. Its `02346` section always reads the text index directly, so it
did not show that lazy `FINAL` still applies to such a key, or that a small `LIMIT` keeps its
early exit there. Add the float-key rows' positive control and small `LIMIT` row for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings; bounded: 1 full pass + 3 fix rounds + 3 delta rechecks, the last of which found nothing new).

# Sev Finding Verdict Evidence / action
1 ⚠️ The sorting key mixing ASC and DESC columns, named in the changelog entry, reaches a separate early return (optimizeLazyFinal.cpp:294-297) that no test covered AGREE, fixed @ 35b9c36 02346 gains a mixed-direction section; both of its rows fail on master (LOGICAL_ERROR, and 0 instead of 1)
2 ⚠️ The mixed-direction section checks results only, so it would still pass if the text index stopped being read directly for that table AGREE, fixed @ 1e6b954 The section gains the EXPLAIN check the Nullable-key section already has; with the direct read switched off it prints 0
3 ⚠️ The mixed-direction section runs only with a direct text index read, so it would still pass if lazy FINAL were switched off for such keys or their early-exit check were lost AGREE, fixed @ f2de874 04539 gains a mixed-direction positive control and a small LIMIT row; the LIMIT row fails on master, and each row fails alone under its own mutation
4 ⚠️ The third early return (all parts non-intersecting, the full replacement selects nothing, optimizeLazyFinal.cpp:303-310) is unverified AGREE, resolved by measurement (no code change) A temporary marker at that return fires for a LIMIT 1 query that stops early (master builds the set-building plan there, the fix does not; the result is empty either way). No text index read reached it, so the description now names it with that scope

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-9:20260927-141300

@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2de874]

Summary: ✅


AI Review

Summary

This PR fixes the lazy FINAL fallback gap for cases where trySplitNonIntersectingParts exits before the existing text-index and early-stop guards run, so Nullable, floating-point, and mixed-direction sorting keys no longer reach the broken set-building path. The new guard is in the right place, keeps the existing behavior for comparable keys, and the added stateless coverage exercises both the direct text-index regression and the lazy-FINAL gating checks.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit f2de874.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.60% 79.60% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 27, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Sep 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f2de87487 with master f4fc5b9ab (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 863b4536b; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

The PR adds one early-return guard in optimizeLazyFinal and new stateless tests. The guard skips lazy FINAL for queries that stop reading early or read the text index directly, and it only runs on FINAL reads of ReplacingMergeTree-style tables. The one flagged change, ClickBench Q23 at -45.7% (94 ms to 51 ms), is a plain query on the hits table with no FINAL, so it never reaches the changed code; it is downgraded to not_sure. CPU time dropped just as sharply, so something did change between the two builds, most likely other differences between the PR build and the 26.10.1.39897 master baseline rather than this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 94 51 -45.7% <0.0001 The PR only adds an early return in optimizeLazyFinal, which runs only for FINAL reads, and ClickBench Q23 has no FINAL. The CPU drop (724 to 193 ms) shows a real change in work, most likely from differences between the PR build and the base build, not from this diff.

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: 5f6d8968-b6ac-4e89-a556-43eb1c4a1684
  • MIRAI run: b90b6ac5-d990-4bbb-8832-ba849cfd06e8
  • PR check IDs:
    • clickbench_2146082_1790566226
    • clickbench_2146095_1790566227
    • clickbench_2146101_1790566226
    • tpch_adapted_1_official_2146107_1790566227
    • tpch_adapted_1_official_2146119_1790566227
    • tpch_adapted_1_official_2146152_1790566227

@fm4v
fm4v added this pull request to the merge queue Sep 29, 2026
Merged via the queue into ClickHouse:master with commit 3a90dee Sep 29, 2026
172 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 29, 2026
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 comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

3 participants