Skip to content

Disable TopK dynamic filtering when read-in-order applies - #100235

Merged
alexey-milovidov merged 3 commits into
masterfrom
fix-topk-read-in-order-interaction
Mar 21, 2026
Merged

alexey-milovidov merged 3 commits into
masterfrom
fix-topk-read-in-order-interaction

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

PR #99033 removed the type restriction that prevented TopK optimization for non-numeric types (like String). This exposed a counterproductive interaction between TopK dynamic filtering and read-in-order optimization.

When both are active on the same sorting key column, the TopK prewhere (__topKFilter) rejects all rows after the threshold is established (since data is read in sorted order), preventing early pipeline cancellation via LIMIT and causing a full table scan instead of reading just a few blocks.

The fix disables TopK dynamic filtering when read_in_order is enabled and the sort column matches the first column of the storage's sorting key.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b949c229302bf2d8153647c38452ddffbb04cb66&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.4.1.91

When the sort column in `ORDER BY ... LIMIT` matches the first column of
the storage's sorting key, the read-in-order optimization reads data in
sorted order and relies on early pipeline cancellation via `LIMIT` to
minimize `rows_read`.

The TopK dynamic filtering (prewhere `__topKFilter`) is counterproductive
in this case: once the threshold is established after the first few rows,
the prewhere rejects all subsequent rows (they are beyond the threshold
in sorted order), preventing early cancellation and causing a full table
scan.

This was exposed by PR #99033 which removed the type restriction that
previously prevented TopK optimization for String columns.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=b949c229302bf2d8153647c38452ddffbb04cb66&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b066a32]

Summary: ✅


AI Review

Summary

This PR disables TopK dynamic filtering for ORDER BY ... LIMIT when read-in-order applies to the sorting-key prefix, and adds a regression test. The optimizer change looks targeted and correct, but the new read_rows assertion is currently not robust enough to guarantee it validates the intended execution path; also, PR metadata category does not match the change scope.

PR Metadata

⚠️ Changelog category is not correct for this change. The PR modifies optimizer behavior and adds a user-visible performance regression test; this is not a CI-only change.

Exact replacement text:

### Changelog category (leave one):
- Performance Improvement

Changelog entry is not required only for CI/doc/not-for-changelog categories. With Performance Improvement, a user-readable entry is required.

Suggested entry text:

### Changelog entry (a [user-readable short description](https://github.com/ClickHouse/ClickHouse/blob/master/docs/changelog_entry_guidelines.md) of the changes that goes into CHANGELOG.md):
Disable `TopK` dynamic prewhere filtering when `optimize_read_in_order` is used on the first `MergeTree` sorting-key column for `ORDER BY ... LIMIT`, avoiding unnecessary full scans in this query shape.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04051_top_k_dynamic_filter_read_in_order.sql:32-40] The read_rows check can match older queries because no new uniquely identifiable target query is executed after SYSTEM FLUSH LOGS query_log, and the LIKE predicate can also match the earlier EXPLAIN/non-tagged SELECT. This can pass even if the intended runtime behavior regresses.
    Suggested fix: run a post-flush SELECT x ... LIMIT 5 with a unique marker comment and filter system.query_log.query by that marker.

Tests

  • ⚠️ Strengthen the new stateless test to assert read_rows for a uniquely tagged query executed after log flush; this is needed to make the regression check deterministic and tied to the intended query instance.

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Changelog category is CI Fix or Improvement, but code changes are optimizer/runtime behavior + test; category should be user-facing (Performance Improvement) with a concrete entry.
Safe rollout ✅
Compilation time ✅

Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make the read_rows regression assertion query-specific and post-flush deterministic.
  2. Fix PR template metadata (Changelog category + required changelog entry).

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 20, 2026
@murphy-4o murphy-4o self-assigned this Mar 21, 2026
alexey-milovidov and others added 2 commits March 21, 2026 10:39
Tests that `__topKFilter` prewhere is not injected when `ORDER BY` matches
the MergeTree sorting key prefix and `optimize_read_in_order` is active.
Verifies correctness, plan shape, and bounded `read_rows`.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…FLUSH LOGS`

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.70% -0.10%
Functions 24.00% 24.00% +0.00%
Branches 76.40% 76.30% -0.10%

PR changed lines: PR changed-lines coverage: 100.00% (20/20, 0 noise lines excluded)
Diff coverage report
Uncovered code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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