Skip to content

Fix order by issue in StorageMerge - #85025

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
wudidapaopao:fix_storage_merge_order_by
Aug 14, 2025
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
wudidapaopao:fix_storage_merge_order_by

Conversation

@wudidapaopao

@wudidapaopao wudidapaopao commented Aug 4, 2025 •

Copy link
Copy Markdown
Contributor

fix #84666

In the example, when a Merge Table is nested within another Merge Table, and the nested Merge Table is further nested with a Distributed Table, the current query plan is similar to the following, where an ORDER BY is missing in the nested Merge Table leading to incorrect sorting.

Expression (Project names)
  Sorting (Merge sorted streams for ORDER BY, without aggregation)
    ReadFromMerge
      Expression (( + ))
        Sorting (Sorting for ORDER BY)
          Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
            ReadFromMemoryStorage
      Expression (( + ))
        ReadFromMerge
          Expression (( + ))
            Sorting (Sorting for ORDER BY)
              Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
                ReadFromMemoryStorage
          Expression (( + ))
            Sorting (Sorting for ORDER BY)
              Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
                ReadFromPreparedSource (Read from NullSource)

Therefore, for such cases—where the nested table engine is a Merge Table and the processed_stage is greater than FetchColumns—it is necessary to re-run the InterpreterSelectQueryAnalyzer to generate the query plan. And the query plan is the following, added a step of Sorting (Sorting for ORDER BY)

Expression (Project names)
  Sorting (Merge sorted streams for ORDER BY, without aggregation)
    ReadFromMerge
      Expression (( + ))
        Sorting (Sorting for ORDER BY)
          Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
            ReadFromMemoryStorage
      Expression (( + ))
        >>>>> Sorting (Sorting for ORDER BY) <<<<<
          ReadFromMerge
            Expression (( + ))
              Sorting (Sorting for ORDER BY)
                Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
                  ReadFromMemoryStorage
            Expression (( + ))
              Sorting (Sorting for ORDER BY)
                Expression ((Before ORDER BY + (Projection + Change column names to column identifiers)))
                  ReadFromPreparedSource (Read from NullSource)

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 potential inaccurate sorting issues in the Merge table engine.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a3cc9dc]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, sequential, 1/2) failure
03532_crash_in_aggregation_because_of_lost_exception FAIL
Killed by signal (in clickhouse-server.log or clickhouse-server.err.log) FAIL

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 4, 2025
@tuanpach

tuanpach commented Aug 5, 2025

Copy link
Copy Markdown
Member

Could you give some description about the cause and the fix?

@wudidapaopao

wudidapaopao commented Aug 5, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @tuanpach, thanks for the reminder. I have supplemented the cause of the issue and the corresponding fix above.

Comment thread src/Storages/StorageMerge.cpp Outdated
QueryPlan plan;

if (processed_stage <= storage_stage)
if (processed_stage <= storage_stage && (!std::dynamic_pointer_cast<StorageMerge>(storage) || processed_stage == QueryProcessingStage::FetchColumns))

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.

Suggested change
if (processed_stage <= storage_stage && (!std::dynamic_pointer_cast<StorageMerge>(storage) || processed_stage == QueryProcessingStage::FetchColumns))
/// Refer to https://github.com/ClickHouse/ClickHouse/pull/85025
bool must_rerun_interpreter_select_query_plan
= processed_stage > QueryProcessingStage::FetchColumns && dynamic_cast<StorageMerge *>(storage.get());
if (processed_stage <= storage_stage && !must_rerun_interpreter_select_query_plan)

I think it would fit more to your explanation

Therefore, for such cases—where the nested table engine is a Merge Table and the processed_stage is greater than FetchColumns—it is necessary to re-run the InterpreterSelectQueryAnalyzer to generate the query plan. And the query plan is the following, added a step of Sorting (Sorting for ORDER BY)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@tuanpach Thanks for the feedback! Updated as suggested.

select sum(e) from (select * from merged order by t limit 10) SETTINGS max_threads = 10;
select sum(e) from (select * from merged order by t limit 10) SETTINGS max_threads = 50;

CREATE TABLE t1 (key Int) ENGINE=MergeTree() ORDER BY key;

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.

Should we separate this test into a different file?
It would be easier to troubleshoot.
It is very minor, feel free to ignore this suggestion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Thanks for the feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Sorting in StorageMerge is occasionally inaccurate

4 participants