Skip to content

Fix TopK filtering dropping NULL and NaN rows from the answer - #114812

Merged
shankar-iyer merged 25 commits into
ClickHouse:masterfrom
groeneai:fix-topk-null-nan-wrong-results
Nov 13, 2026
Merged

shankar-iyer merged 25 commits into
ClickHouse:masterfrom
groeneai:fix-topk-null-nan-wrong-results

Conversation

@groeneai

@groeneai groeneai commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116705
Closes: #124313
Closes: #130823
Related: #124984
Related: #121145

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):

Fix ORDER BY ... LIMIT n over a Float32/Float64/BFloat16 column with a minmax index returning wrong rows when the column holds NaN: under DESC or NULLS FIRST, top-K granule selection could skip the granules holding the answer. ASC NULLS LAST keeps using the index.

Description

On 26.8 and 26.9, SELECT v FROM t ORDER BY v DESC LIMIT 3 over a Float64 column with a minmax index whose first granules are all NaN returns nan, nan, nan instead of the three largest values, and ORDER BY v ASC NULLS FIRST LIMIT 1 returns a number instead of nan.

The top-K path ranks and skips granules by their stored bounds, compared as Fields, which rank NaN greatest. The bounds omit NaN unless a whole range is NaN, and merging bounds (accurateLess) can turn only the max into NaN. So ASC NULLS LAST is handled correctly, while NULLS FIRST misses the NaN rows the bounds omit and DESC ranks a NaN max first and skips it as NaN-last (#124313).

tryOptimizeTopK now refuses a float sort key outside ASC NULLS LAST, and buildIndexes applies the same rule (master refused NULLS FIRST there only when a threshold tracker exists). hasTypeThatCanContainFloat replaces the other two copies of the float predicate (FunctionTopKFilter, Parquet Reader). The __topKFilter routing for floats and nested NULLs is already on master (#121145).

The format-source path drops its float gate, which waited for __topKFilter to become NaN-aware, so Parquet float sort keys get the per-row filter (still without the statistics shortcut). It now refuses Dynamic/Variant/JSON anywhere in the key, which the float gate used to cover for a Variant holding a float. Runtime-typed keys elsewhere are #124984.

On master the test fails in every NULLS FIRST and DESC arm except the two with a threshold tracker (anf ON dflt, idx anf), which master already refuses; the ASC NULLS LAST arms assert the index is still used. Removing each guard term reddens only its own arms.


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

Version info

  • Merged into: 26.11.1.2177-master (included in 26.11 and later)

groeneai and others added 3 commits August 13, 2026 23:54
ORDER BY ... LIMIT n silently omitted rows that belong in the answer when the
sort column contained a NaN or a nested NULL and TopK filtering was active.

TopK filtering must order values the way the sorter does. It did not, in three
shapes:

- A composite type whose comparison resolves to plain UInt8 reaches
  GenericComparisonImpl, which hardcodes the nan/nulls-direction hint to 1
  (NULLs and NaNs greatest). The order is total, so only the placement is
  wrong, which makes it incorrect exactly when nulls_direction is -1, i.e.
  ASC NULLS FIRST and DESC NULLS LAST. The latter loses every real value.

- IEEE float comparison is partial: nan <= x, nan >= x, nan <= nan and
  nan >= nan are all false, while the sorter's FloatCompareHelper treats NaN
  as tying with itself. A NaN row is therefore equal under sort order yet
  fails both comparators, at every direction and nulls_direction. This shape
  is reachable at default settings, since Float64 is fixed-length and
  use_top_k_dynamic_filtering defaults to true. A root Tuple belongs here
  too: FunctionComparison dispatches executeTuple before the types_equal
  branch, so it composes partial per-element comparisons rather than reaching
  compareAt.

- use_skip_indexes_for_top_k ranks granules through
  MinMaxGranuleItem::operator<, a bare Field comparison with no
  nulls_direction, and it runs before reads begin. No comparator change can
  reach it: the row is still lost with use_skip_indexes_on_data_read = 0,
  where no threshold tracker exists at all.

For the first two, route the sort column to executeGeneral, which already
passes nulls_direction into compareColumn and keeps equals. For the third,
add floats to the two skip-index eligibility gates. Those gates already
excluded Nullable and collators for the same reason and one carries a TODO
naming this remedy; floats were missed because they are number-represented
yet admit NaN. Losing granule pruning for floats is a performance cost;
keeping it is a correctness bug.

The float predicate is derived from WhichDataType::isFloat plus a recursive
forEachChild walk rather than a list of wrapper types, so BFloat16,
Tuple(Float64, ...), Array(Float64) and typed JSON are all covered. Object,
Variant and Dynamic answer true unconditionally because the types they hold
are only known at runtime; measured, that also fixes a LOGICAL_ERROR for a
Tuple(Dynamic) or Tuple(Variant(...)) sort column, whose comparison resolves
to Nullable(UInt8).

TopKThresholdTracker::compareFields is left unchanged. testAndSet only ever
stores a boundary value the sorter itself published from an already-sorted
block, so the stored threshold is never tighter than the true boundary and
cannot exclude a row that belongs in the answer. The one consumer that could
turn a wrongly ordered threshold into a dropped row at read time is canSkipMark
on floats, which the gate change removes.

Cost on a NaN-free Float64 column, 10M rows, ORDER BY f ASC LIMIT 10: 6 ms to
14 ms, reading 10M rows instead of 81,920. An integer column is unchanged.
Isolated to granule pruning: on a copy of the same data with no minmax index,
before and after are 53 ms and 64 ms and both read everything. Making
MinMaxGranuleItem order-aware would recover this and is left as the TODO
already in the code.

The new test runs each carrier with filtering on and off and requires the two
to agree, since with it off the answer is ground truth. On the unmodified
binary 20 arms disagree and the 11 control arms already agree. Controls cover
the directions where nulls_direction is 1, the Array-wrapped floats that
compare through a total order, a top-level Nullable(Float64) across all four
direction and nulls-direction combinations, integer and Decimal domains that
admit neither NULL nor NaN, and the same fixture shape with an ordinary value
instead of NaN.
Review fix round 1. The test gained an assertion that the general comparison
path still rejects rows: every existing arm only compares answers, so a filter
returning an all-true mask would keep all of them correct while silently
optimizing nothing. That matters here because excluding floats from
skip-index granule ranking leaves the dynamic filter as the only remaining
optimization on the float carriers.

The new assertion compares RowsReadByMainReader against
RowsReadByPrewhereReaders and was validated against a binary whose
executeGeneral returns an all-true mask: the strict inequality originally
considered survives that mutation, because a filter accepting every row still
skips the last granule, so the assertion requires the main reader to read at
most half. It selects a payload column rather than the sort column, since
projecting only the sort column leaves the main reader no work and makes any
such comparison trivially true.

The test also gains no-parallel-replicas, matching all four in-tree tests that
assert a TopK fact from EXPLAIN, and pins explain_query_plan_default because
the assertions scan plan text. Two obsolete SETs are dropped.

The ReadFromMergeTree TODO claimed NaN-aware comparison would suffice to lift
the float restriction. It would not: getExtremes drops NaNs before the minmax
index stores them, so a mixed granule records no NaN at all and no ordering
change can recover it.
…ws-read probes

The nested-Variant arm the test already carried uses Variant(Float64, String),
whose declared alternatives make Float64 statically visible, so the unconditional
float term alone routes it. Deleting the Variant term from
hasTypeThatCanContainFloat therefore left the whole test green while
reintroducing the LOGICAL_ERROR this change claims to fix.

Add a Variant with no float member at all so that term is the only thing that can
route the carrier. Verified against a binary with only that term removed: the new
arm aborts with the carrier named in the message, while the test as it stood
before this commit passes on the same binary.

The two effectiveness probes assert a rows-read ratio but pinned none of the
rows-read settings the test runner randomizes. Pin the two that
03533_skip_index_on_data_reading pins, on those probes only, since pinning them
globally would change the plans the other arms assert on. Both probes still read
1 on the fix and 0 against an all-true-mask filter, so the pins do not weaken the
assertion.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds, all findings adjudicated)

An independent model reviewed this change three times without access to the author's notes. Every
finding is listed with its verdict and the evidence behind it.

# Finding Verdict
❌ __topKFilter returns an all-true mask undetectably: the oracle compares answers only AGREE, fixed
❌ The test cannot detect removal of the unconditional Variant routing AGREE, fixed
❌ Plan assertions run under parallel replicas, where use_skip_indexes_on_data_read is force-disabled AGREE, fixed
❌ Non-float Tuple(Nullable(T)) still takes the fast path at NULLS LAST and raises a logical error DISAGREE — pre-existing, already fixed by #113406
❌ Show reproducible evidence for the quoted float slowdown and the integer control DISAGREE — evidence existed; numbers corrected
⚠️ The new TODO implies NaN-aware ordering alone could lift the float restriction AGREE, fixed
💡 Two obsolete SETs in the test AGREE, removed
💡 The rows-read probes assert a ratio without pinning the settings that change it AGREE, fixed

Liveness. The answer-comparing arms stay green if the general path returns an all-true mask, so
two probes now assert that the main reader reads at most half of what the prewhere readers did. The
prescribed strict inequality did not redden a deliberately built all-true-mask binary (a filter
accepting every row still skips the final granule), so the oracle was changed rather than the
mutation: the shipped predicate reads 1 in 10/10 on the fix and 0 in 10/10 on the mutation.

Attribution. Dropping all three runtime-typed disjuncts at once aborts at an earlier arm, which
would have proved nothing about the Variant term. A narrower binary deleting only isVariant()
was built instead: the new Tuple(Variant(String, UInt64)) arm fails on it and names that carrier
in the abort, while the previous revision of the test passes on the same binary.

Not fixed here. A non-float Tuple(Nullable(T)) sort column raises LOGICAL_ERROR at
ASC NULLS LAST. This reproduces identically on the merge base: none of the guard terms this PR
adds is reachable for that shape, since the nested-nulls term applies only when nulls_direction
is -1. #113406 fixes it with a direction-agnostic check on the resolved comparison type and covers
it with tests, so it is deliberately not duplicated here. Routing it in both directions would also
surrender the vectorized path where filtering already agrees.

Also disclosed: Object/JSON answers the float predicate true unconditionally and no
constructible fixture attributes that disjunct, since an untyped dynamic path cannot hold NaN
(toJSONString(map('g', nan)) yields {"g":null}). It is kept as a fail-safe.

Reviewer never edited source; the source tree is byte-identical to the reviewed revision.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2418022]

Summary: ✅


AI Review

Summary

Reviewed PR #114812 at 2418022b3c16c6f30e96bd99f3416bbe21c56a78. The change restricts float minmax top-K pruning to ASC NULLS LAST and enables float row filtering for Parquet while preserving the statistics guard. No actionable findings remain in the current diff; earlier bot findings are addressed or superseded by the narrowed scope.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build was available for independent execution. Current-head Fast test passes both new SQL regressions. The PR discussion reports the Parquet regression passing after the merge, but detailed current-head CI results for 05025_parquet_top_k_dynamic_filtering were unavailable; a completed run would close that verification gap.
Final Verdict

Status: ✅ Approve.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Every affected carrier reproduces on every run, not probabilistically: SELECT f FROM t ORDER BY f ASC NULLS FIRST LIMIT 1 returns 100 with filtering on and nan with it off, on the same binary, with max_threads = 1 and query_plan_max_limit_for_top_k_optimization pinned. Tuple(Dynamic) is a hard LOGICAL_ERROR.
b Root cause explained? Yes. Three shapes of one invariant, that the filter must order values as the sorter does: GenericComparisonImpl hardcodes the nan/nulls hint to 1 (FunctionsComparison.h:719); IEEE leaves NaN unordered against every value including itself, while the sorter's FloatCompareHelper ties it with itself; and MinMaxGranuleItem::operator< (MergeTreeIndexMinMax.h:112) ranks granules with a bare Field comparison before any read.
c Fix matches root cause? Yes. It changes the two decision points, which comparison path runs and which index is eligible. No widened bound, no relaxed assertion, no no-random-* tag, no guard at the symptom site.
d Test intent preserved / new tests added? Yes. No existing test modified or weakened. New 04899_topk_filtering_null_nan_wrong_results with 34 on/off arm pairs, 11 control arms, 6 plan-presence assertions and 2 index-eligibility assertions.
e Both directions demonstrated? Yes. On the unmodified binary 18 of 31 probe arms disagree; with the fix 0 of 31 do. The test file itself fails on a base server (server died on the Tuple(Dynamic) arm) and passes on the fixed one. Build IDs differ and the running server's buildId() was asserted against the binary in both directions.
f Fix is general across code paths? Yes. Both skip-index eligibility gates changed together; their own comments call them mirrors of each other. executeGeneral and its collation branch already pass nulls_direction. TopKThresholdTracker::compareFields is deliberately unchanged, since it only ever stores a boundary the sorter published, and the Nullable(Float64) control arms guard that.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Array(Nullable(T)), Map(K, Nullable(V)), Array(LowCardinality(Nullable(T))), Array(Tuple(..., Nullable(T))), Array(Float64), Array(Tuple(Float64, UInt64)), Tuple(Float64, UInt64), Tuple(Dynamic), Tuple(Variant(...)), JSON(f Float64) as column and as subcolumn, Float32, Float64, BFloat16, plus UInt64 and Decimal64(2) negative controls. All four direction x nulls-direction combinations, both values of use_skip_indexes_on_data_read, and both a dense and a sparse fixture, because each is vacuous where the other bites.
h Backward compatible? (maintainer-approved exception only) Yes. No setting added, no default changed, no format or serialization change, so no SettingsChangesHistory.cpp entry is needed (the diff touches no Settings* file). The behaviour change is a wrong answer becoming the right one, plus a narrowed optimization for float sort columns.
i Invariants and contracts preserved? Yes. hasTypeThatCanContainFloat is a pure predicate over a type, holds no state, allocates nothing beyond the existing forEachChild walk, and cannot throw where its callers could not already. Both gates keep every existing term and only add a conjunct, so no previously rejected type becomes eligible. No lock, lifetime, error path or durable write is touched.

Session id: cron:clickhouse-impl-self-slot-57:20260813-214900

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 14, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @vdimir, could you review this? TopK dynamic filtering compared through lessOrEquals/greaterOrEquals, which place NULLs and NaNs last whatever nulls_direction says and leave NaN unordered against every value, so a row that belongs in the top n was dropped; the fix routes those sort columns to the existing general path and adds floats to the two skip-index eligibility gates that already excluded Nullable for the same reason.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2418022b3 with master 65ddb52fe (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

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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.65 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.9 s 12.8 s +9.3 s (+262%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -12.6 s (-9%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ecc6c92

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, parallel) / 03566_system_completions_table victim of another test's unscoped stderr (PostgreSQLConnectionPool: connection to 127.0.0.1 port 1 refused); 206/206 reruns passed with the same randomized settings #114818 (mine, open)
Sync - CH Inc sync (private, not actionable)

Not caused by this PR's diff: 03566_system_completions_table is not touched here, and the
failure reason is stderr pollution from a concurrently running PostgreSQL test rather than a
query result.

Session id: cron:our-pr-ci-monitor:20260814-180000

Resolved a single include-ordering conflict in ReadFromMergeTree.cpp: master
added <DataTypes/IDataType.h> and <DataTypes/NestedUtils.h> at the same spot
where this branch added <DataTypes/hasNullable.h>. All three are used, so all
three are kept.

Master's bytes-aware read-stream cap (18 commits) and its row-policy
where_clause fix in optimizeTopK.cpp are preserved unchanged.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve a conflict

Head e3f2b93204ca79285907be385b4c0c0db25fd8b1, merged 6d0a17390c451dac5db306436a6033a6be71718f.
mergeable is back to MERGEABLE.

One conflict, in ReadFromMergeTree.cpp, and it was include ordering only: master added
<DataTypes/IDataType.h> and <DataTypes/NestedUtils.h> at the same spot where this branch adds
<DataTypes/hasNullable.h>. All three are used, so all three are kept. Master's bytes-aware
read-stream cap and its row-policy where_clause fix in optimizeTopK.cpp are preserved
unchanged; the fix content of this PR is byte-identical across the merge.

04899_topk_filtering_null_nan_wrong_results passes on the merged tree. The two rows-read probes
are the part master's read-stream changes could have moved, so I checked the values rather than
just the assertion: RowsReadByMainReader 1350 against RowsReadByPrewhereReaders 3064, the same
band as before the merge. I also ran the top-k filtering and skip-index tests plus master's new
04812_row_policy_top_k_optimization and the five merge_tree_min_bytes_per_read_stream tests:
15 of 15 pass.

The `jsub` pair only compared answers, so it stayed green whether or not a
`__topKFilter` was installed for `ORDER BY v.f`: an uninstalled filter leaves the
sorter to produce the correct answer on its own. A dotted sort column reaches the
filter only through the alias-resolution branch in `tryOptimizeTopK`, which returns
early when the name does not resolve, so that branch needs its own presence
assertion alongside the four existing ones.

Attributed with a mutation that rejects only carriers whose resolved sort-column
name is still dotted: the test then fails on exactly the new `pres jsub` row and
nothing else, while the pre-change test passes on the same binary.
@groeneai

Copy link
Copy Markdown
Collaborator Author

One residual noticed while validating this round, disclosed rather than folded in.

For a sort column of type Tuple(Dynamic) under ORDER BY ... DESC, with
use_top_k_dynamic_filtering_for_variable_length_types = 1 (non-default), the filtered answer can
differ from the unfiltered one. It is not caused by this PR and is out of its scope:

  • Routing for that carrier at nulls_direction = 1 is byte-identical to the merge-base guard, so
    both binaries take the same branch.
  • On the merge-base binary the same query does not return a wrong answer, it aborts with the
    Expected UInt8. Got Nullable(UInt8) logical error that this PR fixes. The threshold error is a
    separate pre-existing defect that the abort was masking.
  • A carrier the merge-base binary can execute through the same code path,
    Nullable(UInt64) DESC, agrees ON vs OFF on both binaries, so that path is not broken in
    general.
  • The four arms this PR is about (ASC NULLS FIRST, ASC NULLS LAST on the shipped carriers) all
    agree; at the setting's default of 0 no filter is installed for the carrier at all.

Fixing it means changing how the threshold is represented in TopKThresholdTracker, which this PR
deliberately leaves untouched.

Comment thread src/Functions/FunctionTopKFilter.cpp Resolved
…depth

The threshold is published to TopKThresholdTracker as a bare Field
(PartialSortingTransform / MergeSortingTransform call IColumn::get), and
ColumnVariant::get keeps only the payload of the active alternative while
discarding its discriminator. ColumnVariant::compareAt, which is what the sorter
uses, ranks by discriminator before payload. TopKThresholdTracker::compareFields
compares the Field with plain Field ordering and has no discriminator axis, so
the published threshold is not ordered the way the sorter orders the column and
the filter can reject rows that belong in the answer.

The previous guard tested isDynamic/isVariant, which are root-only, so a
Tuple(Dynamic) or a JSON reached the filter. Measured on a three-part fixture
holding one constant Dynamic value per part, so the DESC extremum lives only in
the last part: ORDER BY v DESC LIMIT 2 returned (0) where the correct answer is
(1000). All values there share a single runtime type, so the mismatch does not
require mixed alternatives. The same fixture with Tuple(UInt64) agrees, which
attributes the divergence to the Dynamic member rather than to the layout.

Test hardening: the failing DESC arm and its static twin, and presence rows for
the nested Dynamic, root JSON and static-twin carriers. Sorting on a JSON
subcolumn of static type keeps the filter, because the guard tests the sort
column's own type.

Reported by clickhouse-gh[bot] on the PR.
hasDynamicStructure asks whether an alternative is itself runtime-typed, so
Variant(UInt64, UInt8) and Tuple(Variant(String, UInt64)) answered false and kept
the filter. The discriminator is what makes them unsafe, not the alternatives, so
test for Object/JSON, Variant or Dynamic appearing anywhere in the type instead.

Measured on Tuple(Variant(UInt64, UInt8)), three parts, the UInt64 alternative
only in the last one: alternatives are sorted by name so every UInt64 precedes
every UInt8, and ORDER BY v ASC LIMIT 2 returned (3) where the correct answer is
(900). Map(String, Nullable(UInt64)) and the other static carriers keep the
filter.

Also adds float arms for Map and LowCardinality, which reach their children
through their own forEachChild implementations, so the recursion in
hasTypeThatCanContainFloat was asserted only through Array and Tuple.
tryOptimizeTopK rejects a limit strictly above the cap, so a cap of 1 leaves
LIMIT 1 eligible; it is the LIMIT 2 and LIMIT 3 arms that lose the filter.
The `pres jsub` arm sorts by the dotted name `v.f`. `tryOptimizeTopK` can only
reach a dotted sort column through the branch that resolves it to the storage
column name, and that resolution requires the node to be an ALIAS. Only the
analyzer produces an ALIAS there; the old interpreter leaves an INPUT node, so
`optimizeTopK` returns early ("Could not resolve column alias v.f INPUT") and no
filter is installed. The arm therefore asserted 1 unconditionally and failed on
the `old analyzer` job flavour.

Comparing the presence against `getSetting('enable_analyzer')` keeps the
assertion strict in both flavours instead of relaxing it to a wildcard: it still
reddens if the filter disappears under the analyzer, and it now also reddens if
one ever appears without it. The reference is unchanged, since the arm prints 1
either way, and no coverage is dropped from the other assertions in the file.

The early return is pre-existing master behaviour and is not what this PR
changes, so installing the filter for dotted names under the old interpreter
would be a new optimization rather than part of this fix.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bc30337

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted, old_compatibility) / STID 1611-483a Unexpected return type from __topKFilter. Expected UInt8. Got Nullable(UInt8) pre-existing logical error, not introduced here: the fuzzer wrapped this branch's own d_stord fixture into d_stord__fuzz_32 with v Tuple(Nullable(UInt64)), and a comparison over a Nullable nested in a Tuple resolves to Nullable(UInt8) while getReturnTypeImpl declares UInt8. The same signature has 4 hits over 90 days across 4 branches, including one on master, the oldest 2026-07-07, which is 5 weeks before this branch existed #113406 (mine, open)

Not caused by this PR's diff: this branch narrows the dynamic-filtering and skip-index gates for
float and runtime-typed sort columns; it does not touch the __topKFilter return-type path.
#113406 is the fix for that path, adding an isUInt8(elem_compare->getResultType()) guard, and its
own regression test covers Tuple(UInt64, Nullable(UInt64)), the same shape the fuzzer generated
here. That fix is not on this branch yet, so this run predates it.

Session id: cron:our-pr-ci-monitor:20260816-103000

Resolve the two TopK guard conflicts against master's empty-Tuple work:

- FunctionTopKFilter: keep master's hasEmptyTuple() route to executeGeneral and
  add this branch's NULLS FIRST and float conditions to the same disjunction.
- optimizeTopK: keep master's zero-sized-Tuple gate on dynamic filtering. Its
  isDynamic/isVariant checks are dropped because hasRuntimeTypedType subsumes
  them and also covers those types nested inside Array/Tuple/Map. The comment
  keeps the zero-sized-Tuple rationale next to the generalized Field one.

Merged master at 0cba270.
A review comment reported `LowCardinality(Nullable(T))` slipping past the
`isNullable` term of the skip-index eligibility guard in `tryOptimizeTopK` and
its mirror in `ReadFromMergeTree::buildIndexes`. It does not: the guard's first
term `isValueRepresentedByNumber` already rejects the whole family, because
`DataTypeLowCardinality` forwards it to the dictionary type and
`DataTypeNullable` does not override it, so it lands on the `IDataType` default
`false`. Nothing outside `src/DataTypes` overrides that predicate. Measured, the
carrier selects no top-K index and agrees with the answer computed with both
TopK paths off, in all four nulls directions.

Both rejections nevertheless rested on properties no arm asserted, so pin them.
The two carriers added here are the only ones whose disqualifying property is out
of reach of a root-only test: the NULL and the NaN sit in the dictionary, not at
the root, so plain `Nullable(UInt64)` and plain `Float64` cannot stand in for
them. Admitting a nullable dictionary in the first term turns the `NULLS FIRST`
answer from `NULL` into `100`; narrowing the float term to a root-only test turns
it from `nan` into `100`. Each mutation reddens only its own two arms, and the
plain `LowCardinality(UInt64)` column in the same fixture stays eligible
throughout, so neither rejection is attributable to the wrapper.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 8c1153a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_s3_plain_rewritable (4 cases) node death, not caused by this PR: the same signature fired on true master today at 257b90c684dd901835112afb3f7ef9c1eb062ca1 (15:13Z) and 691db87c896bdd3cd19c15cadb58a631cd1a8ab2 (16:27Z), and on #115738 a fix task is created (investigating at full effort, fixing PR link to follow on this PR)
Finish Workflow / new_tests_check.py pure cascade of the row above, not an independent defect: the shard failure DROPPED 103 downstream nodes, all 103 naming that one culprit, including all three Bugfix validation arms the hook reads, so it reported passed: none for arms that never ran a fix task is created, the same one as the row above (one owner for both rows)
CH Inc sync private sync CH Inc sync (private, not actionable by me)

Details on the node death. The 4 failing cases are one event, not four network flakes: the query
issued by each gets Code: 210. DB::NetException: Connection refused (172.16.2.8:9000), and
node1 in that fixture started once (PID 737, Ready for connections. at 17:37:42) and then its
clickhouse-server.log stops dead at 17:38:39.508 with no shutdown line, no Received signal, no
<Fatal> and no sanitizer report. The two surviving nodes both log Received signal 15 at
17:38:59, which is the harness teardown after the failure, so node1 did not get SIGTERM. The
test saw the refused connection 18 seconds later.

This PR cannot reach it: the diff is 7 files confined to TopK filtering
(FunctionTopKFilter.cpp, optimizeTopK.cpp, ReadFromMergeTree.cpp, hasNullable.{h,cpp}, one
stateless test), and nothing in it touches plain_rewritable object-storage metadata.

The shard did not overrun, so this is not the shard-budget family: Failures: 4/1222 in 6635s
against a 7200s session budget, with all five sibling shards green
(0/1172, 0/1182, 0/1668, 0/1032, 0/928).

One caveat recorded so the onset is not over-read: test_s3_plain_rewritable only started running
in the 6/6 shard on 2026-08-28 23:56Z (it has 97452 rows in the 2/6 shard since 2026-07-15),
so the pair has little history. At lane level the failure is low-rate and recurring rather than
brand new: 3 FAILs on 2026-07-16, 3 on 07-17, 3 on 07-24, 7 today, and 0 on every other day in 45.

Session id: cron:our-pr-ci-monitor:20260829-193000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Following up on the Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) row in the CI
finish ledger above (and the Finish Workflow row it cascaded into).

The first PR out of that investigation is #117104. It does not fix the node death: it restores
the diagnostic the death needs. The runners are cgroup v1, where a memcg OOM is charged to the
killed task's cgroup, so a kill inside a test container moves none of the counters the job checks
and matches none of its host patterns. ./ci/tmp/dmesg.log is therefore dumped and then discarded
on exactly the runs that need it, which is why the failing job's result carries files: [] and its
448 KB log holds no kill text at all. #117104 keeps and prints that record whenever a run reports a
failure.

The node death itself stays open and is still being worked. It reproduces on plain master (two
hits on 2026-08-29 at 257b90c684dd9018 and 691db87c896bdd3c), so it is not caused by this PR's
diff, which is confined to topK filtering and cannot reach plain_rewritable object-storage
metadata.

…hat master already does

Review feedback on ClickHouse#114812:

- The `__topKFilter` routing for floats and nested NULLs is on master (ClickHouse#121145, ClickHouse#113406), so the
  PR's `(nulls_direction == -1 && hasTypeThatCanContainNulls(...))` term is dead and is removed.
  The `hasRuntimeTypedType` term there is removed too: where a nested Variant reaches the
  function (the GROUP BY installer admits one), `executeGeneral` returns the same wrong row, since
  the Field threshold has already lost the discriminator. Refusing such keys in all three
  installers is ClickHouse#124984, so the MergeTree installer is left as on master. The format-source
  installer keeps the recursive check, because dropping its float gate would otherwise arm
  `Tuple(Variant(Float64, UInt64, UInt8))`, which that gate refused.
- The float refusal of the skip-index path was too broad. Field ranks NaN greatest, the min of a
  granule ignores NaN unless the whole range is NaN, and merging bounds with `accurateLess` can only
  turn the max into NaN, so ASC NULLS LAST is ranked and skipped correctly. Every other order is
  not: NULLS FIRST misses NaN rows absent from the bounds, and DESC ranks a NaN max first and
  skips it as NaN-last (ClickHouse#116705 case 3, ClickHouse#124313). `tryOptimizeTopK` now refuses a float key only
  outside ASC NULLS LAST, and `buildIndexes` generalizes master's NULLS FIRST check to the same
  rule (it sees NULLS FIRST only through a threshold tracker, which exists whenever the planner
  did not decide the index itself).
- One float predicate: `hasTypeThatCanContainFloat` replaces `hasFloatingPoint` in
  `FunctionTopKFilter.cpp` and the inline lambda in Parquet `Reader.cpp`.

The test is rewritten to what master gets wrong: ASC NULLS FIRST without a threshold tracker,
a leading all-NaN granule under DESC (also behind LowCardinality), the ClickHouse#124313 merged NaN max,
plus the ASC NULLS LAST shapes that must keep the index (including ClickHouse#124313 mirrored for the min)
and the plan-based parallel replicas observable for the planner's direction term. Each guard term
was removed in turn and reddens only its own arms; a root-only float check reddens only the
LowCardinality arms.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks. You are right that the __topKFilter part is on master, so I rebased the scope in bbadb47: this PR is now the float rule for the minmax top-K path (index kept for ASC NULLS LAST, refused otherwise) plus the Parquet float gate, and the description and the test are rewritten to what master still gets wrong. Every guard term reddens only its own arms when removed. Runtime-typed keys are left to #124984.

The branch is 22 commits; I can squash it if you prefer, but that would move your inline anchors.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - bbadb47

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 03752_attach_as_replicated_transaction_metadata flaky, not from this PR (it changes only the topK filtering paths): the DELETE mutation failed with Can't create hardlink for file .../all_1_7_1/txn_version.txt.tmp (FILE_DOESNT_EXIST) on cached_s3_encrypted; the 19 reruns passed. Same signature on one other PR in 90 days, 0 on master. #103599 (merged, present in this head) narrowed this race but does not close it a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the owner of the row above)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261020-213012

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 03752_attach_as_replicated_transaction_metadata failure in the ledger above: #127074

@Ergus

Ergus commented Oct 26, 2026

Copy link
Copy Markdown
Member

@groeneai merge master and fix conflicts

Conflict in src/Functions/FunctionTopKFilter.cpp: master moved the
executeGeneral/executeVectorized dispatch from executeImpl into the new
compareValues (rows equal to the threshold, sparse columns). Took master's
executeImpl and applied this branch's change to compareValues: the float
term uses the shared hasTypeThatCanContainFloat instead of the local
hasFloatingPoint, with the NaN comment at the dispatch.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 3ad9624. The only conflict was in src/Functions/FunctionTopKFilter.cpp: master moved the executeGeneral/executeVectorized dispatch from executeImpl into the new compareValues, so I kept master's code and applied this PR's change there (the shared hasTypeThatCanContainFloat instead of the local hasFloatingPoint). Nothing else in the PR's diff changed. 04899_topk_skip_index_float_nan, 04327_106948_minmax_skip_index_nan and 05025_parquet_top_k_dynamic_filtering pass on the merged build and still fail on today's master.

@fm4v

fm4v commented Oct 27, 2026

Copy link
Copy Markdown
Member

@groeneai I checked this PR against all seven cases of #116705 and against #124313. The code covers all of them: cases 1 to 4 and #124313 through the ASC NULLS LAST-only rule in tryOptimizeTopK and buildIndexes. Cases 5 to 7 (dynamic filtering, no index) are already fixed on master, because floats go through executeGeneral and TopKThresholdTrackerNumeric::testAndSet refuses a NaN boundary.

Since this PR closes #116705, please add regression arms (ON vs OFF) for the cases the tests do not reproduce yet:

  • case 2: ORDER BY v DESC NULLS FIRST LIMIT 1 with a single nan in a mixed granule (only prdist dnf touches DESC NULLS FIRST now, and it checks the plan, not the answer);
  • cases 5 and 6: the tab_late_nan reproducer (late nan rows, ASC/DESC NULLS FIRST, no index, max_threads = 1, max_block_size = 1000). As far as I can see, no master test covers it: 05044_top_k_dynamic_filtering_float_special_values deliberately avoids NULLS FIRST on mixed data;
  • case 7: zlareb1's tab_nan_threshold reproducer (ASC with the default NULLS LAST, first block mostly nan), plus its DESC twin.

While there, the header comment of 05044_top_k_dynamic_filtering_float_special_values.sql still says __topKFilter drops nan rows under NULLS FIRST with a finite threshold. That is no longer true on master.

The test additions don't block anything. CI is green; the PR now waits on a re-review from @Ergus.

The new test `05453_topk_float_nan_nulls_first_wrong_results` compares the top-k answers for a float sort column containing `nan` against the answers with every top-k optimization disabled: case 2 (skip-index top-k under `DESC NULLS FIRST` with a `nan` in a mixed granule), cases 5 and 6 (dynamic filtering under `ASC/DESC NULLS FIRST` with `nan` rows read after a finite threshold was published, `Float64` and `Float32`), and case 7 (dynamic filtering under the default `NULLS LAST` when the first block's top-k ends in `nan`, plus its `DESC` twin).

Also update the header comment of `05044_top_k_dynamic_filtering_float_special_values`, which still claimed that `__topKFilter` drops `nan` rows under `NULLS FIRST` against a finite threshold.

ClickHouse#116705
@fm4v

fm4v commented Oct 27, 2026

Copy link
Copy Markdown
Member

Follow-up to my earlier comment, which this replaces: I added the missing tests myself in 46ee9cf, so groeneai has nothing to do here.

  • New test 05453_topk_float_nan_nulls_first_wrong_results covers cases 2, 5, 6 and 7 of Wrong results for ORDER BY <float> LIMIT n with nan values under top-k optimizations #116705. Case 2 is skip-index top-k under DESC NULLS FIRST. Cases 5 and 6 are late nan rows under NULLS FIRST, for Float64 and Float32. Case 7 is a nan threshold under the default NULLS LAST, plus its DESC twin. Each arm compares the answer against the one with every top-k optimization off, and the optimization settings are pinned in every arm.
  • The header comment of 05044_top_k_dynamic_filtering_float_special_values.sql no longer claims that __topKFilter drops nan rows under NULLS FIRST.

I could not build locally, so the reference file was derived by reasoning and then checked with clickhouse local on two existing binaries:

  • The CI amd_release binary of this PR's previous head (3ad9624) passes the test unchanged.
  • An official 26.8.1.2745 binary returns the reference answers in every off arm, while every on arm reproduces its bug there.

CI on the new head is the real check.

serprex pushed a commit to serprex/ClickHouse that referenced this pull request Nov 2, 2026
upgrade_runner.sh calls configure() twice over one embedded Keeper and data
directory, and with RANDOMIZE_KEEPER_FEATURE_FLAGS=1 each call draws
check_not_exists, create_if_not_exists and remove_recursive again,
independently. When create_if_not_exists goes from 1 to 0, a coordinated
refreshable view created during the stress phase (04811's APPEND view in a
database recreated as Replicated) is attached against a Keeper that lost the
flag, and RefreshTask stops it by design, logging an <Error> that the upgrade
log scan reports. This failed the check on 3 unrelated PRs in 30 days
(ClickHouse#118372, ClickHouse#117784, ClickHouse#114812); all 3 job logs show the 1 -> 0 flip.

A real in-place upgrade does not downgrade its Keeper, so carry the flags the
previous-release configure() drew into the upgraded server's keeper_port.xml
and fail the job if they still differ, the same shape as the codec carry-over
of ClickHouse#121249. Every job still draws random flags.

Validated locally: the real code extracted from both scripts, run 2000 times
in the CI image, restores the first draw 2000/2000 with no FAIL row; with the
restore removed the new check fails 1765/2000. On a master build, restarting
with create_if_not_exists turned off logs exactly the CI line, and restarting
with the flags unchanged logs nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@shankar-iyer

Copy link
Copy Markdown
Member

@groeneai Refresh to latest master and fix the conflict

Conflict in src/Processors/QueryPlan/Optimizations/optimizeTopK.cpp: master split the variable-length check of tryTopKForFormatSource into the statistics-only String path; kept that, with hasRuntimeTypedType in place of the Dynamic/Variant check and without the floating-point gate, as on this branch.

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

Copy link
Copy Markdown
Collaborator Author

Merged master in 2418022, on top of 46ee9cf (no rebase).

One conflict, in tryTopKForFormatSource (optimizeTopK.cpp): master split the variable-length check into the statistics-only String path. I kept that block and, as before on this branch, refuse Dynamic/Variant/JSON anywhere in the key with hasRuntimeTypedType and drop the floating-point gate. The diff against master is the same change as before the merge.

On the merged debug build 04899_topk_skip_index_float_nan, 05453_topk_float_nan_nulls_first_wrong_results, 05044, 04327 and 05025 pass, and randomized runs show no result differences. The anf ON row of 04899 (the query from #130823) returns nan there and 100 on today's master.

@Ergus Ergus 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.

All my comments were addressed, so I approve, (didn't make a full new review, just checked my previous comments)

@shankar-iyer
shankar-iyer added this pull request to the merge queue Nov 13, 2026
Merged via the queue into ClickHouse:master with commit f728a82 Nov 13, 2026
205 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 13, 2026
@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 Nov 13, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
…p-K gates

ClickHouse#114812 added `hasRuntimeTypedType` (Object/JSON, Variant or Dynamic anywhere in the
type tree) and already uses it in `tryTopKForFormatSource`, which is the gate this PR
had changed for format sources. Drop this PR's identical `isTopKThresholdRepresentable`
helper and use `hasRuntimeTypedType` in the two gates that still checked only the top
level: the MergeTree dynamic-filtering path in `tryOptimizeTopK` and the GROUP BY path
in `optimizeGroupByTopK`.

The Parquet case of the test is removed: master already passes it through the
format-source gate, and 05025_parquet_top_k_dynamic_filtering covers that gate for a
nested Variant key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 23, 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-self PR origin: self-found defect (impact-bar validated) 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-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.10-must-backport

Projects

None yet

8 participants