Skip to content

Fix ORDER BY ... LIMIT over an Interval column with top-K dynamic filtering - #125221

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-top-k-filter-interval-threshold-type
Oct 15, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-top-k-filter-interval-threshold-type

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #125197

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 ORDER BY ... LIMIT over a column of an Interval type (or Nullable, LowCardinality, Tuple or Array of one) failing with TYPE_MISMATCH when use_top_k_dynamic_filtering is enabled, which is the default. Closes #125197.

Description

On 26.8.18.2, SELECT d FROM t ORDER BY d DESC LIMIT 3 over an IntervalNanosecond column of a MergeTree table fails with default settings: Code: 53 ... Type mismatch in IN or VALUES section. Expected: IntervalNanosecond. Got: Int64: while executing 'FUNCTION __topKFilter(d : 0)'. It affects every release since 26.5, where use_top_k_dynamic_filtering became enabled by default.

Root cause: the top-K threshold is published as a Field, and a Field has no Interval kind, so an IntervalX value is a plain Int64. __topKFilter then called convertFieldToType(threshold, column_type) without a source type, which treats the value as an untyped literal, and convertFieldToType rejects Int64 -> Interval (as in toIntervalSecond(1) IN (1, 2)).

Change: the threshold tracker keeps the type of the sort column it is created for, and __topKFilter passes that type, without LowCardinality (which the function's default implementation removes from its argument), as the source type of the conversion. For the column of that same type the conversion is now the identity, for every type.

Validation: the new test covers all eleven Interval units in both directions, Nullable (both NULLS orders), Tuple(IntervalHour, IntervalMinute), Array(IntervalSecond), GROUP BY ... ORDER BY ... LIMIT, an Interval primary key, a minmax skip index, the Memory engine and LowCardinality (also of Nullable). Each of its 42 queries fails with Code: 53 on unfixed master. The test fails 50/50 randomized runs on master and passes 50/50 with the fix. Results equal those with use_top_k_dynamic_filtering = 0. The 166 existing top-K tests show no new failure (those that fail locally need S3 or cluster config and fail the same way on master).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2434-master (included in 26.10 and later)
  • Backported to: 26.9.20.23, 26.8.29.10, 26.7.34.3, 26.3.56.3

… filtering

`SELECT d FROM t ORDER BY d DESC LIMIT n` over a column of an `Interval` type
(or `Nullable`, `LowCardinality`, `Tuple` or `Array` of one) failed with
`TYPE_MISMATCH` once the top-K threshold was set: "Type mismatch in IN or VALUES
section. Expected: IntervalNanosecond. Got: Int64: while executing
'FUNCTION __topKFilter(d)'". It is reachable with default settings since 26.5,
where `use_top_k_dynamic_filtering` became enabled by default.

The threshold is published as a `Field` taken from a column of the sort
column's type. A `Field` has no `Interval` kind, so an `IntervalX` value is a
plain `Int64`. `__topKFilter` then converted it with
`convertFieldToType(threshold, column_type)` and no source type, i.e. as an
untyped literal, and `convertFieldToType` rejects `Int64 -> Interval` (the same
error as `toIntervalSecond(1) IN (1, 2)`).

The threshold tracker now keeps the type of the sort column it is created for,
and `__topKFilter` passes that type, without `LowCardinality` (which the
function's default implementation removes from its argument), as
`from_type_hint`. For a column of that type the conversion returns the value
unchanged, for every type; for other types it already returned the same value.
Teaching `convertFieldToType` an `Int64 -> Interval` conversion would change
`IN` / `VALUES` semantics for every caller, and excluding `Interval` types from
the optimization would disable it for exactly the reported workload
(`ORDER BY duration DESC` on tracing data).

The test covers all eleven `Interval` units in both directions, `Nullable`
(general comparison path, both `NULLS` orders), `Tuple(IntervalHour,
IntervalMinute)`, `Array(IntervalSecond)`, `GROUP BY ... ORDER BY ... LIMIT`, an
`Interval` primary key, a `minmax` skip index, the `Memory` engine and
`LowCardinality` (also of `Nullable`). Each of its queries fails with
`TYPE_MISMATCH` without the fix.

Closes ClickHouse#125197

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 11, 2026
@groeneai

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

Pre-publication review: my own cold review plus an independent model (engine: codex; 2 findings over 2 rounds).

# Sev Finding Verdict Evidence / action
1 ⚠️ LowCardinality(IntervalX) still failed: the function receives its argument without LowCardinality, so a hint of the declared type missed (own review) AGREE, fixed @ cf976d1 the hint is recursiveRemoveLowCardinality of the tracker type; LowCardinality lines added to the test
2 ⚠️ The test asserts only rows, so it would pass if the filter were not installed (gate) DISAGREE each query fails with Code: 53 raised inside __topKFilter on unfixed master, so every line runs the filter; the change is only the threshold conversion, and results equal those with use_top_k_dynamic_filtering = 0
3 💡 Nested LowCardinality (e.g. Tuple(LowCardinality(IntervalHour), UInt8)) has no test line (own review and gate) noted, not blocking checked by hand: correct rows with the fix, Code: 53 on master
4 💡 createTopKThresholdTracker calls getPtr() four times noted, not blocking none

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261011-162200

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf976d1]

Summary: ✅


AI Review

Summary

I reviewed the current diff and prior PR discussion. The change keeps the sort-column type in TopKThresholdTracker and threads it into __topKFilter's convertFieldToType calls, which correctly fixes the Field/Interval kind-loss bug for plain, Nullable, LowCardinality, Tuple, and Array cases covered by the new stateless test. I did not find any remaining correctness, compatibility, or contract issues in the current patch.

Final Verdict

✅ Looks good to merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 11, 2026
@groeneai
groeneai requested review from CurtizJ and murphy-4o October 11, 2026 17:38
@EmeraldShift

Copy link
Copy Markdown
Contributor

I'd also like to request this be backported to stable and LTS versions since the pre-PR behavior breaks queries

@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Oct 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Measured with the repro from #125197 on the branches that still get backports: the query fails on 26.7.6.57, 26.8.21.12 and 26.9.7.6 with default settings, and on 26.3.33.24 when use_top_k_dynamic_filtering = 1 is set (it is off by default there). The backport decision is up to the maintainers, through the backport labels; I do not apply those myself.

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cf976d149 with master 885c21ade (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of a347fefd4; 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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is straightforward. Thanks!

@alexey-milovidov alexey-milovidov self-assigned this Oct 15, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Oct 15, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@EmeraldShift, will do.

alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.9 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.9 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.9 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.9 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.9 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_dynamic_filtering`, which 26.9 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll4 added a commit that referenced this pull request Oct 16, 2026
Cherry pick #125221 to 26.9: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
robot-clickhouse added a commit that referenced this pull request Oct 16, 2026
… column with top-K dynamic filtering
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.8 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.8 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.8 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.8 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.8 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_dynamic_filtering`, which 26.8 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 16, 2026
Cherry pick #125221 to 26.8: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
robot-clickhouse added a commit that referenced this pull request Oct 16, 2026
… column with top-K dynamic filtering
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.7 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from #116512, which on master split `TopKThresholdTracker` into
`ITopKThresholdTracker` with the lock-free `TopKThresholdTrackerNumeric` and
`TopKThresholdTrackerGeneric`, created by `createTopKThresholdTracker`. 26.7 has the
single `TopKThresholdTracker` struct, and #116512 is not marked for backport, so the
resolution keeps the 26.7 tracker and applies only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`),
  as `ITopKThresholdTracker` does on master.
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.7 does not have.
- `FunctionTopKFilter.cpp` merged without conflicts (the hunks of #125221 verbatim).
- `TopKThresholdTracker.cpp` keeps the 26.7 version: its conflicting hunks are #116512's.
- The test drops its `GROUP BY` query and that query's three reference lines, because
  it uses `enable_group_by_top_k_optimization` and `enable_group_by_top_k_dynamic_filtering`,
  which 26.7 does not have.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-ch-test-poll2 added a commit that referenced this pull request Oct 16, 2026
Cherry pick #125221 to 26.7: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
robot-clickhouse added a commit that referenced this pull request Oct 16, 2026
… column with top-K dynamic filtering
alexey-milovidov pushed a commit that referenced this pull request Oct 16, 2026
Resolve the conflicts of the 26.3 cherry-pick of #125221 ("Fix `ORDER BY ... LIMIT`
over an `Interval` column with top-K dynamic filtering").

The conflicts come from master-only changes to the top-K filter: #116512 split
`TopKThresholdTracker` into `ITopKThresholdTracker` with lock-free implementations in a
new `TopKThresholdTracker.cpp`, and later PRs rewrote `FunctionTopKFilter`. 26.3 has the
original header-only `TopKThresholdTracker` constructed from the sort direction, and a
`FunctionTopKFilter` with a single comparison path. The resolution keeps both and applies
only what #125221 changes:

- `TopKThresholdTracker` takes and keeps the type of the sort column (`getDataType`).
- `optimizeTopK.cpp` passes `sort_column.type` where it creates the tracker. On master
  this is done inside `createTopKThresholdTracker`, which 26.3 does not have.
- `FunctionTopKFilter` gets the threshold type from the tracker, without `LowCardinality`,
  and passes it as the source type of the threshold conversion, as on master.
- `TopKThresholdTracker.cpp` stays absent, as it is on 26.3.
- The test enables `use_top_k_dynamic_filtering`, which is off by default on 26.3 and not
  randomized by its test runner, and drops two queries with their reference lines: the
  `Array` one uses `use_top_k_dynamic_filtering_for_variable_length_types` and the
  `GROUP BY` one uses `enable_group_by_top_k_*`, none of which 26.3 has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 16, 2026
Cherry pick #125221 to 26.3: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
robot-clickhouse added a commit that referenced this pull request Oct 16, 2026
… column with top-K dynamic filtering
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 16, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 16, 2026
Backport #125221 to 26.9: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
clickhouse-gh Bot added a commit that referenced this pull request Oct 16, 2026
Backport #125221 to 26.8: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
clickhouse-gh Bot added a commit that referenced this pull request Oct 18, 2026
Backport #125221 to 26.7: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
PedroTadim added a commit that referenced this pull request Oct 19, 2026
Backport #125221 to 26.3: Fix `ORDER BY ... LIMIT` over an `Interval` column with top-K dynamic filtering
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-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

__topKFilter (use_top_k_dynamic_filtering) throws TYPE_MISMATCH for ORDER BY <Interval column> LIMIT n

5 participants