Skip to content

Fix wrong ORDER BY, DISTINCT and LIMIT BY results over a Merge table of a sorted Iceberg table - #125383

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:merge-read-in-order-non-mergetree-children
Oct 15, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:merge-read-in-order-non-mergetree-children

Conversation

@groeneai

@groeneai groeneai commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112981
Related: #125275

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 wrong results of ORDER BY, DISTINCT, LIMIT BY and aggregation in order over a Merge table or the merge table function when it reads an Iceberg table with a sort order: the rows came back unsorted or duplicated.

Description

On 26.8.2.3, SELECT k FROM merge(currentDatabase(), '^t$') ORDER BY k over an Iceberg table with a sort order returns the rows unsorted, and LIMIT 1 BY k returns duplicates.

Found by the AST fuzzer as Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-31ed) in DistinctSortedStreamTransform: CI report.

ReadFromMerge::requestReadingInOrder asked only the ReadFromMergeTree steps of each child plan. An Iceberg child reads through ReadFromObjectStorageStep, so it was accepted without being asked, while its metadata has a sorting key. The planner then replaced the full sort with a merge of unsorted streams. A direct read asks ReadFromObjectStorageStep itself, so it does not have this defect.

Now recursivelyApplyToReadingSteps rejects a reading leaf other than ReadFromMergeTree or ReadNothingStep, so the Merge read declines and keeps the full sort. ReadFromMerge::canReadInOrder(direction) replaces canReadInReverseOrder and asks every child before any is switched, so in a mixed Merge no MergeTree child is left reading in order when another child rejects the request. The topKThroughJoin probe asks it for both directions, so it no longer defers to an in-order read that the Merge read declines. A Merge over MergeTree tables only is unchanged.

One design choice: a sorted Iceberg child could be asked through ReadFromObjectStorageStep::requestReadingInOrder instead. I did not, because that read can itself return unsorted rows per stream (#112981).

The new test fails on 11 of its 12 result lines on master and passes 100/100 with the fix (50 randomized runs, 50 with fixed settings).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2449-master (included in 26.10 and later)

groeneai and others added 2 commits October 12, 2026 10:16
…ren cannot deliver

`ReadFromMerge::requestReadingInOrder` asked only the `ReadFromMergeTree`
steps of each child plan. A child plan with no such step (an Iceberg table
read through `ReadFromObjectStorageStep`, whose metadata carries a sorting
key from its Iceberg sort order) was accepted without being asked, so the
planner replaced the full sort with a merge of unsorted streams.
ORDER BY [DESC] [LIMIT n], DISTINCT, LIMIT BY and aggregation in order over
`merge()` of such a table returned wrong results, and in debug builds the
in-order DISTINCT tripped the `checkEqualRangeEndAssumeSorted` assertion
(AST fuzzer, STID 2508-31ed).

`recursivelyApplyToReadingSteps` now rejects a reading leaf that is neither
a `ReadFromMergeTree` nor a `ReadNothingStep`. `ReadFromMerge::canReadInOrder(direction)`
replaces `canReadInReverseOrder` and asks every reading step of every child
plan without switching any of them. `requestReadingInOrder` calls it before
it switches the children, so in a mixed `Merge` no `MergeTree` child is left
reading in order when another child rejects the request. The
`topKThroughJoin` probe calls it for both directions, so for an ascending
`ORDER BY ... LIMIT` over such a `Merge` it no longer defers to an in-order
read that pass 2 declines (which left neither optimization applied).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=125275&sha=68dabec672d4b2e357a16f21849b2eb329fe931d&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29
Found on: ClickHouse#125275

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the requestReadingInOrder pre-check comment to one line that does not claim more than the check does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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; 2 rounds, 4 findings) plus my own cold review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The topKThroughJoin probe asked a Merge read's children only for DESC AGREE, fixed @ cb24f9c one ReadFromMerge::canReadInOrder(direction) used by requestReadingInOrder and the probe; EXPLAIN fixture
2 ⚠️ No test showed the mixed Merge leaving its MergeTree child in the default read type AGREE, fixed @ cb24f9c ReadType assertions for ASC and DESC; they fail with the pre-check removed
3 💡 Link PR #125275, where the CI report comes from AGREE, fixed @ cb24f9c commit message and PR body
4 ⚠️ The pre-check does not mirror the prefix-width rejection of ReadFromMergeTree::requestReadingInOrder, so a child can still be switched before another rejects DISAGREE Reachable only through a concurrent DDL race (05210: failpoint + EXCHANGE TABLES) or a projection child (#122520 declines it); the Merge still declines and the result is correct. 05210 asserts this state (spread with order: 1), which mirroring the check would break.
5 💡 An empty normal-projection read (ReadFromPreparedSource) in a MergeTree child now also declines reading in order AGREE noted, not blocking: a missed optimization in a corner case, never a wrong result

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

Session id: cron:clickhouse-review-slot-9:20261012-102300

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7172333]

Summary: ✅


AI Review

Summary

This PR correctly closes the Iceberg / non-MergeTree leaf hole and adds focused coverage for that shape, but it still leaves Merge-over-Merge reads able to advertise sorted input without ever putting the nested ReadFromMerge step itself into read-in-order mode. Because that can still produce wrong results for ORDER BY, DISTINCT, LIMIT BY, and aggregation-in-order, I cannot approve it yet.

Findings
  • ❌ Blocker — [src/Storages/StorageMerge.cpp:1892] A nested ReadFromMerge child is accepted as long as its leaves are ReadFromMergeTree, but requestReadingInOrder is later sent only to those leaves. The nested ReadFromMerge step therefore keeps query_info.input_order_info == nullptr, so its own initializePipeline may still narrow() the child streams and destroy the promised order before the outer Merge consumes them. Suggested fix: either propagate requestReadingInOrder / canReadInOrder to nested ReadFromMerge nodes themselves, or conservatively reject nested ReadFromMerge children in this path.
Tests
  • ⚠️ Add a focused regression for Merge over another Merge table (for example ORDER BY or DISTINCT through two levels of Merge). The new Iceberg test only covers a non-MergeTree leaf, so it would not catch the nested-ReadFromMerge case above.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions: fix the nested ReadFromMerge path so the parent cannot announce sorted input unless every nested Merge step is itself switched into read-in-order mode (or rejected), and add the focused two-level Merge regression.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-storage-merge Merge table engine (logical union over tables) and related mechanics. labels Oct 12, 2026
if (auto * read_from_merge_tree = typeid_cast<ReadFromMergeTree *>(node->step.get()))
ok &= func(*read_from_merge_tree);
else if (node->children.empty() && !typeid_cast<ReadNothingStep *>(node->step.get()))
return false; /// Only a `ReadFromMergeTree` can be asked to read in order; any other read does not promise it.

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 lets a nested ReadFromMerge child through as long as its leaves are ReadFromMergeTree, but the nested ReadFromMerge step itself never receives requestReadingInOrder. Later it still sees query_info.input_order_info == nullptr, so its own initializePipeline can narrow() those sorted child streams (should_not_narrow checks only the step's own query_info.input_order_info), which destroys the order before the outer Merge/DISTINCT/LIMIT BY path consumes it. That leaves the same wrong-results class for Merge over another Merge table.

Could we either propagate the request into nested ReadFromMerge nodes themselves, or conservatively reject them here instead of recursing past them?

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 doesn't happen, for two independent reasons:

  1. recursivelyApplyToReadingSteps walks node->children of the child plan. It does not descend into the step-owned child plans of a nested ReadFromMerge. A nested ReadFromMerge is a source step with no children, so it is a leaf that is not ReadFromMergeTree or ReadNothingStep. With this PR, that makes canReadInOrder return false, and the outer Merge read declines. That is the conservative rejection suggested above.
  2. Even before that, getReadingStep in optimizeReadInOrder.cpp requires every selected table to have a sorting key in its metadata. StorageMerge never sets a sorting key, so a Merge table among the selected tables already stops the optimization there.

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

I don't see modifications for Iceberg here, please explain.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @alexey-milovidov, the Iceberg code doesn't need any changes. The bug is in StorageMerge; Iceberg is just the only engine that reaches it.

How a Merge read decides it can read in order:

  1. optimizeReadInOrder (getReadingStep) accepts a ReadFromMerge when every selected table's metadata has a non-empty sorting key.
  2. ReadFromMerge::requestReadingInOrder then goes through each child plan and calls requestReadingInOrder only on ReadFromMergeTree steps. On master, any other reading leaf was skipped without being asked, and the Merge read still reported that it reads in order.

So the defect shows up for a child whose metadata has a sorting key but whose plan leaf is not ReadFromMergeTree. Among the storages outside MergeTree, only IcebergMetadata sets a sorting key (the Iceberg sort order, IcebergMetadata.cpp:1527). An Alias of an Iceberg table forwards that metadata too. An Iceberg child reads through ReadFromObjectStorageStep, which was never asked, so the planner replaced the full sort with a merge of streams that were not sorted.

The Iceberg reader was already correct: a direct read of the same table does ask ReadFromObjectStorageStep::requestReadingInOrder. Only the Merge path skipped it. The fix is on the Merge side, in recursivelyApplyToReadingSteps: a reading leaf other than ReadFromMergeTree or ReadNothingStep now makes the Merge read decline, and the full sort stays. It is engine-agnostic. The test uses Iceberg only because no other engine can trigger the bug today.

I could have forwarded the request to ReadFromObjectStorageStep for Iceberg children instead. I didn't, because that read can itself return unsorted rows per stream (#112981).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed, the explanation above is accurate: no Iceberg change is needed, the fix is in StorageMerge and is engine-agnostic.

@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
Merged via the queue into ClickHouse:master with commit 8b02267 Oct 15, 2026
177 of 178 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 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-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

3 participants