Skip to content

Compare nested NULLs and collated strings in the TopK threshold tracker the way the sort does - #125288

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-top-k-threshold-nested-null-order
Oct 15, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-top-k-threshold-nested-null-order

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #124788
Related: #122064

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

Fixes a master-only regression from #122064 (in no release yet), reported in #124788: a rerun of SELECT s FROM t ORDER BY s LIMIT 3 over a File(Parquet) table with s Tuple(a UInt64, b Nullable(UInt64)) returns (0,0) (1,NULL) (1204,1004) instead of (0,0) (1,5) (1,NULL).

The TopK query condition cache drops a row group when the threshold tracker says the group's best value sorts beyond the final threshold. The best value is picked with IColumn::compareAt and the sort's nulls_direction, but TopKThresholdTrackerGeneric::compareFields applied nulls_direction and the collation only at the top level and otherwise used Field::operator<, which puts a nested NULL first, a nested NaN last and compares nested strings bytewise. So (1,5) looked beyond (1,NULL) and the row group holding it was skipped on every rerun.

The fix is in the comparator, so every consumer (the File verdict and the same one in #124813, testAndSet, Parquet statistics, primary-key pruning) agrees with the sort. When the sort type has a Nullable or a float anywhere, or a collation, compareFields inserts both values into a column of the sort type and compares them with compareAt / compareAtWithCollation and nulls_direction, as updateTopKBestValue and __topKFilter already do. Other types keep the Field comparison, which already matches the sort.

Validation: the new test (Tuple and Array with a nested NULL, ASC and DESC NULLS FIRST, and a nested String with COLLATE 'en') fails on master in all five arms and passes with the fix, 150/150 in repeated runs. Also checked by hand on master and with the fix: LowCardinality(Nullable), Map(K, Nullable(V)) and a nested Tuple. No measurable cost on a 50M-row ORDER BY s LIMIT 10 over MergeTree and Parquet.


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

Version info

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

groeneai and others added 2 commits October 12, 2026 00:03
…er like the sort

`TopKThresholdTrackerGeneric::compareFields` honoured NULLS FIRST/LAST and the
collation only for a top-level value and otherwise fell back to
`Field::operator<`, which puts a nested NULL first, a nested NaN last and
compares nested strings bytewise. The Parquet reader picks a row group's best
value with `IColumn::compareAt` and the sort's `nulls_direction`, so the TopK
query condition cache verdict of the File engine could record a row group that
holds result rows as holding none, and every rerun skipped it.

For a sort type with a Nullable or a float anywhere, or with a collation,
compare the two values as rows of one column of the sort type with
`compareAt` / `compareAtWithCollation` and `nulls_direction`, the comparison
`updateTopKBestValue` and `__topKFilter` already use. Other types keep the
Field comparison, which already matches the sort, so the per-mark primary key
and skip index pruning (which never see these types) pay nothing. A value that
does not fit the sort type throws from `insert` instead of comparing as equal.

Closes ClickHouse#124788

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the empty_column member comment to its invariant (when it is set).

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 12, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test can pass when run 2 gets no cache verdict; assert QueryConditionCacheHits and tag no-parallel DISAGREE Master fails all 5 arms in 20/20 randomized runs; with the fix every run 2 is a cache hit (QueryConditionCacheHits = 1, 2000 of 3000 rows read). Only a concurrent cache clear by another test can make one run vacuous, never a false failure; I keep the test parallel-safe and asserting rows.
2 💡 A NULL inside a nested Variant/Dynamic still takes the Field comparison noted, not blocking Needs allow_suspicious_types_in_order_by = 1; #124984 keeps runtime-typed keys off every TopK path.
3 💡 The description did not name the same verdict in #124813 AGREE, fixed Description updated.

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

Session id: cron:clickhouse-review-slot-8:20261012-000600

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's script and the new test fail on every master run: run 2 returns (0,0) (1,NULL) (1204,1004); 20/20 randomized runs of the test fail on master.
b Root cause explained? The File TopK cache verdict drops a row group when isValueInsideThreshold(best_value) is false. The best value is chosen with compareAt and nulls_direction, but TopKThresholdTrackerGeneric::compareFields used Field::operator< below the top level, which puts a nested NULL first, a nested NaN last and ignores the collation, so a row group holding result rows looked beyond the threshold.
c Fix matches root cause? Yes. The comparator itself now orders values like the sort (one column of the sort type, compareAt / compareAtWithCollation with nulls_direction) for types with a Nullable or float anywhere or a collation. No guard at the verdict.
d Test intent preserved / new tests added? New test 05367_file_top_k_query_condition_cache_nested_null_order: Tuple and Array with a nested NULL (ASC, DESC NULLS FIRST) and a nested String with COLLATE 'en'; each query runs twice with the cache and once without.
e Both directions demonstrated? Master: fails in all 5 arms. Fix: passes, and run 2 is a real cache hit (QueryConditionCacheHits = 1, 2000 of 3000 rows read). Removing the column path re-fails all 5 arms; dropping the collator re-fails the collation arm.
f Fix is general across code paths? One helper serves the File verdict, the same verdict proposed for object storage in #124813, every testAndSet publisher, Parquet row-group statistics and MergeTree primary-key / skip-index pruning (the last two never see these types and keep the Field path).
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked on master and with the fix: Tuple/Array/Map with a nested Nullable, LowCardinality(Nullable(String)) in a Tuple, a nested Tuple, a collated String in Tuple and Array (all wrong on master, right with the fix); top-level Nullable, String and floats unchanged.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or cache-key change; the query condition cache is in memory.
i Invariants and contracts preserved? The tracker now orders values as the sort does at every level. The top-level NULL handling is unchanged; the comparison still runs under the tracker's lock and allocates only a local column; a value that does not fit the sort type throws instead of comparing as equal. testAndSet now tightens in sort order (results were already right).

Session id: cron:clickhouse-impl-slot-6:20261011-231700

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7f48b68]

Summary: ✅


AI Review

Summary

The PR fixes the File(Parquet) TopK cache verdict for nested NULL values and collated strings by comparing thresholds through the sort column implementation. The regression test passed 34 targeted CI runs on commit 112d62f8476f78057487538d0ce8ada3829f8475. One previously reported correctness gap remains in the current code; no new inline findings were identified.

Findings

❌ Blockers

  • src/Processors/TopKThresholdTracker.cpp:96 [dismissed by author -- https://github.com/Compare nested NULLs and collated strings in the TopK threshold tracker the way the sort does #125288#discussion_r4243981016] The threshold order must agree with ORDER BY, but nested Variant keys still use raw Field comparison when they contain neither a float nor a Nullable and have no collation. For example, Tuple(Variant(Array(UInt64), UInt64)) sorts its array alternative before its integer alternative, whereas Field puts the integer first. With allow_suspicious_types_in_order_by = 1 and use_top_k_dynamic_filtering_for_variable_length_types = 1, the optimizer admits this key, so a best array value can be classified as beyond an integer threshold and its result-bearing row group cached away. The author deferred runtime-typed keys to PR #124984, but that PR remains open and its recursive exclusion is absent here. Make this merge contingent on that exclusion, or include the equivalent guard at every tracker creation path; merely reconstructing a Variant column from a Field also loses alternative identity.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build tree was available. Current-head targeted CI had no completed test result when inspected; a completed run of 05367_file_top_k_query_condition_cache_nested_null_order on commit 7f48b687c73db289761411f18553fce6ed4e828d would close this execution gap.
Final Verdict

❌ Block until nested runtime-typed keys are excluded from every TopK threshold path, either through PR #124984 or an equivalent change. Preserve a focused regression test for that exclusion. The existing inline thread was left unchanged; no duplicate comments were posted.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 12, 2026
Comment thread src/Processors/TopKThresholdTracker.cpp Outdated
TopKThresholdTrackerGeneric::TopKThresholdTrackerGeneric(const SortColumnDescription & sort_desc_, DataTypePtr data_type_)
: ITopKThresholdTracker(sort_desc_)
{
if (sort_desc.collator || anyInTypeTree(*data_type_, [](const IDataType & node) { return node.isNullable() || isFloat(node); }))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still leaves nested Variant sort keys on the raw Field path. The new guard only switches to column-based comparison for collation / nested Nullable / float, but ColumnVariant::compareAt does not use the same cross-type order as Field::operator<: for example Variant(UInt64, Int64) is canonically ordered by type name (Int64 before UInt64), while Field orders them by Field::Types tag (UInt64 before Int64). Because the TopK optimizer only rejects top-level Variant/Dynamic, a key like Tuple(Variant(UInt64, Int64)) can still reach this tracker with allow_suspicious_types_in_order_by = 1, and then testAndSet / isValueInsideThreshold can disagree with the actual ORDER BY and skip or cache away result-bearing data. Please either route nested runtime-typed keys through the column-based comparator too, or add a deep type-tree eligibility check that keeps them off every TopK path.

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

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7f48b687c with master 61a00a8a1 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 8b022670c; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 112d62f

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 (arm_binary, 2/4) / test_database_disk/test.py::test_copy_of_temporary_table_under_unrelated_name not from this PR (it only changes the TopK threshold comparison and adds a stateless test): the test still expected a startup failure that the duplicate-UUID rule of #123902 no longer produces. The tree that ran does not contain the test fix #125292 (mine, merged), merged master @ 3e6d10f
Mergeable Check, PR praktika rollups of the row above #125292 (mine, merged), merged master @ 3e6d10f

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

Session id: cron:our-pr-ci-monitor:20261012-193011

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

Ok.

@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
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 15, 2026
…-nested-null-order

# Conflicts:
#	src/Processors/TopKThresholdTracker.h
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict with #125221 (both PRs changed the TopKThresholdTrackerGeneric constructor). The fix itself is unchanged: the diff against master is the same 5 files.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 15, 2026
Merged via the queue into ClickHouse:master with commit 5ed0c9f Oct 15, 2026
178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 3, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 3, 2026
Backport #125288 to 26.10: Compare nested NULLs and collated strings in the TopK threshold tracker the way the sort does
leshikus pushed a commit that referenced this pull request Nov 13, 2026
…in the TopK threshold tracker the way the sort does
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-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog 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.

File TopK cache verdict misorders NULL in Tuple sort key; rerun drops rows

5 participants