Skip to content

Fix topK dynamic filtering crash with Dynamic/Variant columns - #100742

Merged
pufit merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/topk-dynamic-type-crash
Mar 26, 2026
Merged

pufit merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/topk-dynamic-type-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (pick one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes):

Fix server crash (logical error "Unexpected return type from __topKFilter") when use_top_k_dynamic_filtering is enabled and the ORDER BY column has Dynamic or Variant type.


Summary

When use_top_k_dynamic_filtering = 1 is used with an ORDER BY on a Dynamic(max_types=...) column, the __topKFilter internal function calls lessOrEquals which returns Nullable(UInt8) instead of the expected UInt8, causing:

Logical error: 'Unexpected return type from __topKFilter. Expected UInt8. Got Nullable(UInt8).'

This is AST fuzzer finding STID 1611-483a, recurring across multiple unrelated PRs.

Root cause

Dynamic and Variant types wrap their inner values in Nullable. When the vectorized comparison path in FunctionTopKFilter calls lessOrEquals on a Dynamic column, the result is Nullable(UInt8) — but the query plan expects UInt8 from __topKFilter, producing a logical error.

Fix

Two layers of defense:

  1. Query plan optimizer (optimizeTopK.cpp): Skip the dynamic-filtering prewhere optimization entirely when the sort column is Dynamic or Variant. These types don't benefit from the optimization anyway since their comparison semantics are complex.

  2. Runtime guard (FunctionTopKFilter.cpp): Route Dynamic/Variant arguments to the general comparison path (which returns a clean ColumnUInt8) instead of the vectorized path that delegates to lessOrEquals.

Test plan

  • Reproduced crash locally with exact fuzzer query
  • Verified fix: query completes without error, returns correct results
  • Verified optimization still works for regular types (UInt64, etc.)
  • Added regression test 04058_topk_dynamic_filtering_with_dynamic_type

Note: This fix is important for PR #99537 which proposes enabling use_top_k_dynamic_filtering by default — without this fix, that would crash on every table with Dynamic columns.

Version info

  • Merged into: 26.4.1.286

When use_top_k_dynamic_filtering is enabled and the ORDER BY column has
Dynamic or Variant type, the __topKFilter function's vectorized path
calls lessOrEquals which returns Nullable(UInt8) instead of UInt8,
triggering a "Unexpected return type" logical error (STID 1611-483a).

Fix: skip the dynamic-filtering prewhere optimization for Dynamic and
Variant sort columns in the query plan optimizer, and route these types
to the general comparison path in FunctionTopKFilter as defense-in-depth.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (session: cron:clickhouse-ci-task-worker:20260325-182556)

a) Deterministic repro?
Yes. SELECT v1, v2 FROM tab1 ORDER BY v1 ASC LIMIT 5 SETTINGS use_top_k_dynamic_filtering=1, allow_suspicious_types_in_order_by=1 on a table with v1 Dynamic(max_types=216) crashes 100% of the time with Logical error: Unexpected return type from __topKFilter. Expected UInt8. Got Nullable(UInt8).

b) Root cause explained?
Dynamic wraps values in Nullable. FunctionTopKFilter::executeVectorized delegates to lessOrEquals, which returns Nullable(UInt8) for Dynamic input. The query plan expects UInt8 from __topKFilter (declared in getReturnTypeImpl), so the block structure check throws a logical error.

c) Fix matches root cause?
Yes. The optimizer now skips the dynamic-filtering prewhere for Dynamic/Variant columns (avoiding the type mismatch entirely), and the runtime routes these types to the general path as defense-in-depth.

d) Test intent preserved?
No existing test is modified. The new test 04058_topk_dynamic_filtering_with_dynamic_type verifies the crash no longer occurs.

e) Demonstrated in both directions?

  • Without fix: crash (Logical error: Unexpected return type)
  • With fix: query returns correct top-5 results, no error

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [163f6c6]

Summary: ✅


AI Review

Summary

This PR fixes a real __topKFilter exception path for Dynamic/Variant sort keys by disabling dynamic prewhere filtering for those types and adding a runtime guard in FunctionTopKFilter to use the general comparison path. The change is focused, has regression coverage for both Dynamic and Variant, and I did not find correctness, safety, or performance blockers in the modified code.

Missing context
  • ⚠️ CI/Praktika results were still in progress during this review, so no finished full test signal was available.
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 ✅
Safe rollout ✅
Compilation time ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 25, 2026
- Make ORDER BY deterministic (add payload tiebreaker) to fix flaky
  output when multiple rows share the same sort key value
- Add Variant(Int64, String) test case alongside the existing Dynamic
  test to cover both code paths in the optimization skip
- Fix typo: "a Unexpected" → "an Unexpected"

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 24.50% 24.70% +0.20%
Branches 76.70% 76.70% +0.00%

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

@murphy-4o murphy-4o self-assigned this Mar 26, 2026
@pufit
pufit added this pull request to the merge queue Mar 26, 2026
Merged via the queue into ClickHouse:master with commit cac197c Mar 26, 2026
297 of 298 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 26, 2026
azat pushed a commit to azat/ClickHouse that referenced this pull request Oct 8, 2026
…ains a Nullable

FunctionTopKFilter::getReturnTypeImpl declares UInt8 unconditionally, but
executeVectorized returns whatever the lessOrEquals/greaterOrEquals it delegates
to resolves to. FunctionComparison::getReturnTypeImpl propagates Nullable
transitively out of tuple elements, so for a sort column that contains a Nullable
without being Nullable the fast path produces Nullable(UInt8) and the
columnMatchesType guard in ExpressionActions throws LOGICAL_ERROR.

The guard meant to route such columns to the safe path tested only top level
nullability, and DataTypeTuple does not override IDataType::isNullable().

Test the resolved comparison type where it is already computed and fall back to
executeGeneral, which builds a ColumnUInt8 directly and cannot diverge. Keying on
the resolved type rather than on the argument's structure is deliberate: a
structural predicate such as hasNullable is also true for Array(Nullable(T)) and
Map(K, Nullable(V)), whose comparisons resolve to plain UInt8 and work correctly
today, so it would silently disable use_top_k_dynamic_filtering for them.

executeGeneral also applies nulls_direction, which the lessOrEquals fast path did
not, so the general path is both safe and more correct for these types. It is row
at a time, but it now runs only for arguments that throw today, and Nullable and
collated columns already took it unconditionally.

Found by the AST fuzzer on an unrelated PR, STID 1611-483a, reachable from
ordinary DDL with no opt-in setting since use_top_k_dynamic_filtering defaults to
true. ClickHouse#100742 was an incomplete earlier fix for the same STID: it enumerated the
two reported types, Dynamic and Variant, instead of keying on the causal
property, so the Tuple carrier remained. Its regression test is extended here
with the Tuple, Tuple-of-LowCardinality(Nullable) and NULL bearing arms.

The LowCardinality arm pins max_threads = 1 because without it the threshold is
not always set before the remaining parts are read, and the arm only reaches the
filter in about seven runs out of ten.
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-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.

4 participants