Repository navigation
Add SHUFFLE clause support for SELECT - #100305
Conversation
|
Hi @alexey-milovidov , if you have time, please take a look. if need anything more, please do let me know |
|
Workflow [PR], commit [85dece6] Summary: ✅
AI ReviewSummaryAdds the experimental Output consumers traced: distributed merges retain key order; Missing context / blind spots
Final VerdictStatus: ✅ Approve. No new inline findings to post. |
Switch `SHUFFLE LIMIT` to bounded reservoir sampling, add the experimental `allow_experimental_shuffle_query` setting, update docs/tests, and fix style issues from the CI report. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100305&sha=latest&name_0=PR&name_1=Style+check
Remove the global alias restriction for `SHUFFLE` so disabled mode keeps legacy alias parsing, and update regression tests to use unambiguous clause forms. PR comment: ClickHouse#100305
Apply the optimization only for positive limits, add to , normalize , and add a stateless regression test for . PR comment: ClickHouse#100305
Add to the first runnable example so it works under default settings. PR comment: ClickHouse#100305
Keep alias-behavior checks in and move the expected query into a dedicated error-only test so does not fail the whole file with return code . Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100305&sha=0095e031faec3babd928dbe81c9b6c436a116255&name_0=PR&name_1=Fast%20test&name_2=Tests
- Remove trailing whitespace on line 633 of `CommonParsers.h`
- Move `-- { serverError SUPPORT_IS_DISABLED }` inline with the semicolon in `04054_shuffle_disabled_error.sql` so the test runner correctly associates the expected error with the query
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100305&sha=12f6e74bde27f51c8223a68221c984c4581c3ce1&name_0=PR&name_1=Fast%20test
When `allow_experimental_shuffle_query = 1` but `allow_experimental_analyzer = 0`, `TreeRewriter` previously passed the guard and let the query proceed. The old planner has no `ShuffleStep`, so `SHUFFLE` was silently ignored and non-randomized results were returned — a correctness bug. Fix: after the `SUPPORT_IS_DISABLED` gate, always throw `NOT_IMPLEMENTED` in the old planner path, matching the pattern used for `LIMIT BY ALL`. Add `04055_shuffle_old_interpreter` to cover the setting-enabled / old-planner case.
Retain sorting for finite UInt64 random-key limits until the replacement can preserve the full integer distribution. Add low-bit regressions. ClickHouse#100305 (comment)
Cover direct and nested queries under throw and ignore policies. ClickHouse#100305 (comment)
Preserve the generated wrapper setting when rebuilding SQL on parallel replicas without relaxing the user-query gate. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=a4378b05b4b37771dc2bceb2de6b97aec1284d54&name_0=PR ClickHouse#100305
Preserve optional key replacement, sort direction, limit, and block size, and validate deserialized headers and flags. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=a4378b05b4b37771dc2bceb2de6b97aec1284d54&name_0=PR ClickHouse#100305
Correct order-statistic initialization, retain external sorting and limited `rand64` keys, count input rows before sampling, guard view pushdown and cache policies, and propagate injected settings. Register and serialize `ShuffleStep` for remote plans, with numeric formatting for byte flags. Update documentation. ClickHouse#100305 https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=ba3dbe139b1f26d210ce1f1debf4f25b4bb47843&name_0=PR
Cover key distributions and low bits, unequal shards, external sorting, exact row counts, view pushdown, cache policies, injection and serialization. Remove unneeded cache resets and avoid integer overflow in distribution assertions. Static and numerical checks passed. Full compilation and SQL execution remain unverified locally; CI must validate this revision. ClickHouse#100305 https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=ba3dbe139b1f26d210ce1f1debf4f25b4bb47843&name_0=PR
ba3dbe1 to
ffe0dd8
Compare
Prevent an outer `LIMIT` from truncating the shuffle population and exclude shuffled views from trivial distributed pushdown. Add population and shard-distribution regression tests. ClickHouse#100305 ClickHouse#100305 (comment) ClickHouse#100305 (comment)
Run global `DISTINCT` before final randomization, including inputs from after-aggregation stages. Preserve all shard candidates by disabling distinct limit hints and deferring `LIMIT BY` to the finalizer. Keep existing shard shuffle-key transport intact. Add duplicate-heavy local and distributed sampling regressions and computed `LIMIT BY` coverage for after-aggregation stages. ClickHouse#100305 ClickHouse#100305 (comment)
…thout parallel replicas With parallel replicas the plan also contains `ReadFromRemoteParallelReplicas` and the merge of the local and the remote shuffled streams, so the reference did not match in the `ParallelReplicas` stateless tests job. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel) ClickHouse#100305 Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a shard, `ShuffleStep` appends `__shuffle_key`, by which the initiator merges the shuffled streams of the shards. The expression before `LIMIT BY` is built by the analysis, which does not know about this column, so it was projected away and a distributed `SHUFFLE LIMIT n BY ...` failed with `NOT_FOUND_COLUMN_IN_BLOCK`. Add the column to the outputs of that expression when it is present in the header. Address review: ClickHouse#100305 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nested `Distributed` With nested `Distributed` tables, an intermediate server processes the query from `WithMergeableState` to `WithMergeableState`. Its incoming streams were already shuffled by the shards below and carry the internal `__shuffle_key` column, so appending another key threw `The column name __shuffle_key is reserved for SHUFFLE`. Merge the incoming streams by the key instead, as the initiator does. Address review: ClickHouse#100305 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
The style check now lints `src/Processors/Transforms` for standard containers (after merging master). Replace `std::vector` and `std::deque` in `ShuffleTransform` and the new code of `ScatterByPartitionTransform` with `VectorWithMemoryTracking` and `DequeWithMemoryTracking`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=100305&sha=e222a2837309af5f038db8c650a6689a5b504e78&name_0=PR&name_1=Style%20check PR: ClickHouse#100305 Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
The implementation is clean and beautiful. LGTM.
Adds the
SHUFFLEclause, which is used in place ofORDER BYand returns the rows in a uniformly random order:SELECT ... SHUFFLE [LIMIT n]. The shuffle is implemented by first-class processors, as described in #105338 (comment), and works in O(n) instead of O(n * log(n)).The random choices are made just in time: no random values are generated or stored for the rows in advance.
max_threadsstreams; every stream is shuffled in parallel (scattered into cache-sized buckets at random, Fisher-Yates within a bucket); the streams are concatenated. A random scatter followed by uniform shuffles of the parts is a uniformly random permutation, so no keys and no merge are needed.LIMIT n: every stream keeps a uniformly random sample ofnrows by reservoir sampling (Algorithm L), which skips the rows that cannot get into the sample without looking at them.SHUFFLEworks withoutLIMIT, and withLIMIT,OFFSET,LIMIT BY,DISTINCT,GROUP BY,WITH TOTALS, window functions, in distributed queries, and with lazy materialization (SHUFFLE LIMIT nneeds no columns before the limit, so the other columns are read only for the sampled rows). Everywhere rows could be limited early (reading from storage, theDISTINCTlimit hint, the trivialGROUP BY ... LIMIT,LIMITpushdown into MongoDB,optimize_distributed_group_by_sharding_key,Mergetables),SHUFFLEis treated likeORDER BY.ORDER BY rand()andORDER BY rand64()are executed by the shuffle processors (settingquery_plan_use_shuffle_for_order_by_rand, enabled by default) at the end of the plan optimization, after the optimizations working withSortingStep: the values of therand()column are replaced by sorted random keys, which have the same distribution, so the result is still sorted by this column. It applies when the random value is not used in other expressions, and when there is aLIMITor the external sorting is disabled (the shuffle does not spill to disk).The setting
inject_random_order_for_select_without_order_by(for tests) injectsSHUFFLEinstead ofORDER BY rand().The clause is experimental:
allow_experimental_shuffle_query.Benchmarks (
numbers_mt, best of several runs on a loaded 96-core aarch64 machine, external sorting disabled):ORDER BY rand()with sortingStringcolumn, 16 threadsLIMIT 10LIMIT 1000LIMIT 1000000The full shuffle still uses about 7% more memory than sorting: the rows a thread receives are copied into its buckets before being shuffled. This could be avoided by scattering into buckets on arrival.
Related: #105338
Related: #87836
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the experimental
SHUFFLEclause, used in place ofORDER BY:SELECT ... SHUFFLE [LIMIT n]returns the rows in a uniformly random order (or a uniformly random sample ofnrows) in O(n) time, in parallel and in distributed queries. Queries withORDER BY rand()are executed the same way, up to ten times faster. Enable the clause withallow_experimental_shuffle_query.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/100305]
Version info
26.11.1.1626-master(included in26.11and later)