Skip to content

Do not inject random ORDER BY into queries planned to an intermediate stage - #113266

Merged
alexey-milovidov merged 8 commits into
masterfrom
fix-inject-random-order-intermediate-stage
Aug 15, 2026
Merged

alexey-milovidov merged 8 commits into
masterfrom
fix-inject-random-order-intermediate-stage

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Related: #110188

With inject_random_order_for_select_without_order_by = 1, InjectRandomOrderIfNoOrderByPass wrapped every top-level query into SELECT * FROM (...) ORDER BY rand(), including queries that are planned only up to an intermediate stage. For a Merge table with a Distributed child, the other children are planned to WithMergeableState; the wrapper made such a child plan complete its aggregation, so blocks without AggregatedChunkInfo reached MergingAggregatedTransform, and the query failed with a logical error (exception) Chunk info was not set for chunk in MergingAggregatedTransform.

Now the injection pass is only added when the query is processed to stage Complete, so intermediate-stage plans (Merge/Distributed children) are left untouched, while the injection still applies to the user-facing query.

Minimal reproducer (found by BuzzHouse on this report, unrelated to that PR's changes — it reproduces on master):

CREATE TABLE t_local (x UInt64) ENGINE = MergeTree ORDER BY x;
INSERT INTO t_local SELECT number FROM numbers(100);
CREATE TABLE t_dist (x UInt64) ENGINE = Distributed('test_shard_localhost', currentDatabase(), 't_local');
SET inject_random_order_for_select_without_order_by = 1;
SELECT count() FROM merge(currentDatabase(), '^t_(local|dist)$'); -- LOGICAL_ERROR before this fix

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 a logical error (exception) Chunk info was not set for chunk in MergingAggregatedTransform when the setting inject_random_order_for_select_without_order_by is enabled and an aggregation query reads from a Merge table containing a Distributed child: the random ORDER BY rand() wrapper is no longer injected into queries planned only up to an intermediate stage.

Version info

  • Merged into: 26.8.1.1453 (included in 26.8 and later)

… stage

With `inject_random_order_for_select_without_order_by = 1`, `InjectRandomOrderIfNoOrderByPass`
wrapped every top-level query into `SELECT * FROM (...) ORDER BY rand()`, including queries that
are planned only up to an intermediate stage. For a `Merge` table with a `Distributed` child,
the other children are planned to `WithMergeableState`; the wrapper made such a child plan
complete its aggregation, so blocks without `AggregatedChunkInfo` reached
`MergingAggregatedTransform`, failing with a logical error (exception)
"Chunk info was not set for chunk in MergingAggregatedTransform".

Now the pass is only added when the query is processed to stage `Complete`.

Found by BuzzHouse: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110188&sha=cdc23648d36878b136bf2c8d87ee9b0a29651412&name_0=PR&name_1=BuzzHouse%20%28arm_asan_ubsan%29
On: #110188

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dd20b50]

Summary: ✅


AI Review

Summary

This PR moves the inject_random_order_for_select_without_order_by guard into buildContext so analyzer builds for non-Complete stages no longer add the synthetic ORDER BY rand() wrapper, and it adds focused stateless regressions for the Merge/Distributed and parallel-replicas paths. I did not find any remaining correctness or compatibility issues in the current version of the diff.

Final Verdict

✅ No blocking issues found in the current version of this PR.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.70% 86.70% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.10% +0.00%

Changed lines: Changed C/C++ lines covered: 5/5 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole red check, AST fuzzer (amd_debug), is unrelated to this PR: the logical error Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 (STID 2270-3258, window function over a remote constant subquery) is a pre-existing master bug — the same STID has hit unrelated PRs since at least 2026-06-20 (#85138, and #112650, #112930, #104510, #112871, #113399 in the last two days). A fix is already in progress: #108045, which cites exactly this STID. Once it merges, updating this branch will clear the red.

…without_order_by

The AI review suggested that analyzer parallel replicas fragment builders could
replan an already wrapped query tree to an intermediate stage. Verified that the
fragment is built from the inner, unwrapped query tree (the wrapper interposes a
QueryNode boundary and each subquery planner passes its own tree), so replicas
return partially aggregated blocks and the initiator merges them correctly.
This test pins that behavior.
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing dd20b500b with master 0eb658995 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.30 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

Comment thread src/Analyzer/QueryTreePassManager.cpp Resolved
… parameter

Address review: instead of threading a bool parameter through
addQueryTreePasses and branching on it, disable the setting
inject_random_order_for_select_without_order_by in buildContext
when the query is processed up to an intermediate stage.
InjectRandomOrderIfNoOrderByPass already gates itself on that setting,
and buildContext is the existing place where the interpreter context
is adjusted based on SelectQueryOptions, so addQueryTreePasses keeps
its uniform pass list and its original signature.

#113266 (comment)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both red checks on 08c5496eecf are unrelated to this PR:

Merged master (clean, the PR diff is unchanged: the gating in buildContext plus the two tests), rebuilt, and re-validated 04727_merge_distributed_inject_random_order and 04816_parallel_replicas_inject_random_order locally (pass with and without randomized settings).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole red check on bb73dbd7, Stress test (arm_debug) — "Hung check failed, possible deadlock found" — is unrelated to this PR. The hung query is DROP TABLE prometheus; stuck in DatabaseCatalog::waitTableFinallyDropped, the known fleet-wide stress-test storm affecting many PRs since 2026-08-10. The fix is in progress: #114326 (revert of the PromQL topk/limitk streaming plan). Once it merges, a master merge or rerun will clear this red.

Everything else is green (160 successful checks), and the AI Review on this head is ✅.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Looks perfect.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 15, 2026
Merged via the queue into master with commit ee44a3b Aug 15, 2026
358 of 359 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-inject-random-order-intermediate-stage branch August 15, 2026 01:36
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 15, 2026
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.

3 participants