Skip to content

Fix lost text index optimization for queries with ORDER BY ... LIMIT - #115586

Merged
Ergus merged 6 commits into
ClickHouse:masterfrom
Ergus:fix-text-index-direct-read-blocked-by-expression-step
Aug 25, 2026
Merged

Ergus merged 6 commits into
ClickHouse:masterfrom
Ergus:fix-text-index-direct-read-blocked-by-expression-step

Conversation

@Ergus

@Ergus Ergus commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Related: https://github.com/ClickHouse/clickhouse-private/issues/68580
Related: #93545

A query that filters on a text index and also has ORDER BY ... LIMIT could stop using the index to answer the filter, and read and tokenize the whole text column instead:

SELECT count() FROM (SELECT id, v FROM t WHERE hasToken(s, 'error') ORDER BY v DESC, id LIMIT 10)

The two optimizations did not compose: the one that speeds up ORDER BY ... LIMIT reshaped the
plan in a way the text index optimization no longer recognized, and it silently fell back to
reading the column. Nothing indicated this in the query plan or the logs, and the results stayed correct, but the query got much slower and used much more memory. On a full-text search benchmark over ~30M rows the affected queries took ~300 ms and ~500 MB instead of ~30 ms and
~15 MB.

Whether a query was affected depended on the order of the columns in SELECT, which made it look arbitrary: SELECT v, id ... ORDER BY v was fine while SELECT id, v ... ORDER BY v was not. All the settings involved are enabled by default.

Both optimizations now apply together. A TRACE log entry was also added for the remaining cases where the text index optimization cannot be used, so a silent fallback is visible in the logs.

Changelog category (leave one):

  • Performance Improvement

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

Fixed a performance regression where a query combining a text index filter with ORDER BY ... LIMIT stopped answering the filter from the index and read the whole text column instead.


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

Version info

  • Merged into: 26.9.1.106 (included in 26.9 and later)
  • Backported to: 26.8.1.2026, 26.7.6.53, 26.6.4.61

@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [44a11ed]

Summary: ✅


AI Review

Summary

This PR restores direct text-index reads for ORDER BY ... LIMIT queries whose Top-K optimization inserts a header-conversion ExpressionStep between FilterStep and ReadFromMergeTree, and adds a focused stateless regression test for several affected plan shapes. I did not find a current correctness, safety, or performance blocker in the implementation at the current head.

Missing context / blind spots
  • ⚠️ I could not run the new stateless test locally in this checkout because no built clickhouse binary is available here; the review is based on code inspection, the current PR discussion, and the available CI summary.
Final Verdict

✅ No actionable review findings at 44a11ed6d984cb6aeba6d03a734ae8dc902f55d4.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 16/17 (94.12%) · Uncovered code

Full report · Diff report

@Ergus
Ergus requested a review from alexbakharew August 20, 2026 10:47
@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 20, 2026
@Ergus
Ergus requested a review from rschu1ze August 20, 2026 10:47
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 44a11ed6d with master 86a433ccd (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 710.09 MiB 707.05 MiB -3.04 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

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

Job report

SET query_plan_max_limit_for_top_k_optimization = 1000 because ity is randomized.

When 1, tryOptimizeTopK returns early (n > settings.max_limit_for_top_k_optimization, and our LIMIT 10
gives n = 10). No __topKFilter is installed, so the guard line prints 0. It's only in the "flaky check" jobs because those re-run the changed
test with fresh randomization each time.
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR narrowly fixes direct reads from a text index when an ExpressionStep from top-K optimization hides the filter above the read step; it only affects queries that use a text index with hasToken plus ORDER BY/LIMIT. None of the flagged ClickBench queries (Q18, Q28, Q33) use text indexes, so the three small improvements (-5.8% to -7.2%) cannot be attributed to this change. Q18 and Q28 are downgraded to not_sure as off-path variance, and Q33's no_change (delta within master's normal variance band) is correct. No performance impact from this PR is evident in these benchmarks.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 18 not_sure 1110 1042 -6.1% <0.0001 This PR only fixes direct text-index reads under top-K filtering; ClickBench Q18 uses no text index, so the -6.1% shift is off-path and reads as run-to-run variance.
⚠️ 28 not_sure 1125 1044 -7.2% <0.0001 Q28 does not exercise the text-index/top-K planner path this PR touches, and the measurements were noisy; the -7.2% is not a plausible PR effect.

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: 1039fec3-91ce-4f58-90fb-a68b9a81d3b7
  • MIRAI run: 9bc26082-9ddc-4608-9959-def7fa530259
  • PR check IDs:
    • clickbench_344160_1787675762
    • clickbench_344166_1787675765
    • clickbench_344175_1787675762
    • tpch_adapted_1_official_344190_1787675761
    • tpch_adapted_1_official_344204_1787675760
    • tpch_adapted_1_official_344230_1787675764

@rschu1ze rschu1ze self-assigned this Aug 24, 2026
@Ergus
Ergus added this pull request to the merge queue Aug 25, 2026
Merged via the queue into ClickHouse:master with commit 5b43330 Aug 25, 2026
178 checks passed
@Ergus
Ergus deleted the fix-text-index-direct-read-blocked-by-expression-step branch August 25, 2026 19:08
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
@rschu1ze rschu1ze added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Aug 27, 2026
@rschu1ze

Copy link
Copy Markdown
Member

Let's backport to 26.8 at least.

@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 27, 2026
@Ergus

Ergus commented Aug 27, 2026

Copy link
Copy Markdown
Member Author

Let's backport to 26.8 at least.

I will give it a look, the change is pretty small, but the backport is not trivial because the code is pretty different

kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 28, 2026
robot-ch-test-poll added a commit that referenced this pull request Aug 28, 2026
Cherry pick #115586 to 26.8: Fix lost text index optimization for queries with ORDER BY ... LIMIT
robot-clickhouse added a commit that referenced this pull request Aug 28, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 28, 2026
Backport #115586 to 26.8: Fix lost text index optimization for queries with ORDER BY ... LIMIT
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 28, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer
SET allow_experimental_full_text_index = 1;
SET query_plan_direct_read_from_text_index = 1;
SET use_top_k_dynamic_filtering = 1;
SET query_plan_max_limit_for_top_k_optimization = 1000;
SET query_plan_merge_expressions = 1;

CREATE TABLE tab
(
    id UInt64,
    v UInt64,
    s String,
    INDEX idx_s s TYPE text(tokenizer = 'splitByNonAlpha') GRANULARITY 1
)
ENGINE = MergeTree ORDER BY id;

INSERT INTO tab SELECT number, number % 1000, if (number % 100 = 0, 'error', 'fine') FROM numbers(10000);

-- plan references __text_index_idx_s_hasToken (index answers the filter)
EXPLAIN actions = 1 SELECT id, v FROM tab WHERE hasToken(s, 'error');

-- on 26.5/26.6/26.7 it does NOT: the ORDER BY ... LIMIT plan drops the virtual
-- column and reads + tokenizes the whole `s` column instead
EXPLAIN actions = 1 SELECT id, v FROM tab WHERE hasToken(s, 'error') ORDER BY v DESC, id LIMIT 10;

-- column order decides it: `SELECT v, id` keeps the index, `SELECT id, v` loses it
EXPLAIN actions = 1 SELECT v, id FROM tab WHERE hasToken(s, 'error') ORDER BY v DESC, id LIMIT 10;

Results:

  • Culprit PR: not pinned — introduced in the 25.11–26.5 window (details in Analysis metadata)
  • Reproduces on: 26.7, 26.6, 26.5
  • Does not reproduce on: master
  • Tested versions: master, 26.7, 26.6, 26.5, 26.3, 25.8
  • Also tested (unsupported, context only): 26.2 unknown
  • ✓ Fix is on master — this PR's change fixes the bug on master. The releases listed above still have the bug and need the backport.

Backport the fix to 26.7, 26.6, 26.5.

CC component owner: @CurtizJ @ahmadov

Analysis metadata

comp-text-index · Severity P2 · Finding phase_d_pr115586

  • Verified against master build 573230bfe668 (aarch64)
  • Feature not present (repro inconclusive — the affected code path postdates these releases): 25.8
  • Could not test: 26.3
Introducing change: not identified
  • Secondary components: comp-query-optimizer

clickhouse-gh Bot added a commit that referenced this pull request Aug 31, 2026
Backport #115586 to 26.6: Fix lost text index optimization for queries with ORDER BY ... LIMIT
clickhouse-gh Bot pushed a commit that referenced this pull request Aug 31, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 31, 2026
Backport #115586 to 26.7: Fix lost text index optimization for queries with ORDER BY ... LIMIT
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
PedroTadim added a commit that referenced this pull request Sep 10, 2026
26.6 gained #115586 (`1cc90fa8b08`) after this backport branch was cut, so its
`tryMergeExpressions` block collided with the loop #113154 restructures.

Resolved to master's combined form: hoist the merge into a `walk_begin`
iterator and keep the "parent is not a filter" LOG_TRACE inside the walk. The
resolved `processAndOptimizeTextIndexFunctions` is identical to the one on
master at #113154's merge commit `5c856f8790c`, except for the
`isPrewhereDeferredAfterFinal` arguments, which this backport already omits
because 26.6 has no such method.

The DistinctStep.h include is kept: `isRowScanPassThroughStep` needs it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim added a commit that referenced this pull request Sep 10, 2026
26.7 gained #115586 after this backport branch was cut, so its
`tryMergeExpressions` block collided with the loop #113154 restructures.

Resolved to master's combined form: hoist the merge into a `walk_begin`
iterator and keep the "parent is not a filter" LOG_TRACE inside the walk. The
resolved `processAndOptimizeTextIndexFunctions` is identical to the one on
master at #113154's merge commit `5c856f8790c`, except for the
`isPrewhereDeferredAfterFinal` arguments, which this backport already omits
because 26.7 has no such method.

The DistinctStep.h include is kept: `isRowScanPassThroughStep` needs it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements 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.

6 participants