Skip to content

Add SHUFFLE clause support for SELECT #2 - #105338

Closed
xuir268 wants to merge 9 commits into
ClickHouse:masterfrom
xuir268:shuffle-limit-focused-mr
Closed

xuir268 wants to merge 9 commits into
ClickHouse:masterfrom
xuir268:shuffle-limit-focused-mr

Conversation

@xuir268

@xuir268 xuir268 commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Adds experimental random sampling with LIMIT ... SHUFFLE, using the existing random top-N and lazy materialization paths. The sample does not guarantee random output order.

Changelog category (leave one):

  • Experimental Feature

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

Added the experimental LIMIT ... SHUFFLE clause for SELECT, which returns a random sample of rows. Enable it with allow_experimental_shuffle_query.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f71e7ed]

Summary: ⏳

job_name test_name status info comment
Style check FAIL
test_numbers_check FAIL cidb
settings_changes_history FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 19, 2026
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Analyzer/QueryTreeBuilder.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
@xuir268

xuir268 commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

@shankar-iyer @alexey-milovidov you can review the MR again

Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
@xuir268
xuir268 force-pushed the shuffle-limit-focused-mr branch from 6256575 to 7c731cf Compare May 21, 2026 17:34
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
@xuir268
xuir268 force-pushed the shuffle-limit-focused-mr branch from 7c731cf to a7b92ca Compare May 22, 2026 09:05
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
@xuir268
xuir268 force-pushed the shuffle-limit-focused-mr branch from a7b92ca to 706e14a Compare May 24, 2026 21:02
@xuir268 xuir268 mentioned this pull request May 24, 2026
1 task done
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved

Copilot AI left a comment

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.

Pull request overview

This PR introduces an experimental LIMIT ... SHUFFLE clause for SELECT, gated by a new setting, and wires it through parsing, analyzer/planner, query plan steps, and stateless tests/docs. It also adds an optimization path that may intentionally drop preservation of the final randomized order to reduce overhead for SHUFFLE queries.

Changes:

  • Add SQL syntax/AST support for LIMIT n SHUFFLE, with validation against ORDER BY, OFFSET, and WITH TIES.
  • Add analyzer/planner support by rewriting LIMIT SHUFFLE into ORDER BY rand() LIMIT n and propagating an “unordered output allowed” hint into sorting + lazy materialization.
  • Add an experimental setting allow_experimental_shuffle_query, plus documentation and stateless tests.

Reviewed changes

Copilot reviewed 23 out of 23 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04257_limit_shuffle.sql Adds stateless queries covering parser errors, analyzer gating, and basic behavior.
tests/queries/0_stateless/04257_limit_shuffle.reference Expected outputs for AST/SYNTAX/plan explain and deterministic checks.
src/Processors/Transforms/LazyMaterializingTransform.h Extends transform API with preserve_output_order flag.
src/Processors/Transforms/LazyMaterializingTransform.cpp Implements optional order preservation behavior for lazy materialization join.
src/Processors/QueryPlan/SortingStep.h Adds allow_unordered_output flag + accessors to SortingStep.
src/Processors/QueryPlan/Optimizations/optimizeLazyMaterialization.cpp Threads unordered-output hint into lazy materialization eligibility and join step creation.
src/Processors/QueryPlan/JoinLazyColumnsStep.h Adds preserve_output_order parameter/state to join-lazy-columns step.
src/Processors/QueryPlan/JoinLazyColumnsStep.cpp Passes preserve_output_order into LazyMaterializingTransform.
src/Planner/Planner.cpp Rewrites LIMIT SHUFFLE as ORDER BY rand() and allows unordered output in sorting steps.
src/Parsers/ParserSelectQuery.cpp Parses SHUFFLE after LIMIT and enforces mutual-exclusion constraints.
src/Parsers/CommonParsers.h Adds SHUFFLE keyword.
src/Parsers/ASTSelectQuery.h Adds limit_shuffle flag to ASTSelectQuery.
src/Parsers/ASTSelectQuery.cpp Includes limit_shuffle in hashing and formatting output.
src/Interpreters/InterpreterFactory.cpp Rejects LIMIT SHUFFLE when analyzer is disabled; blocks use in mutation queries.
src/Interpreters/InterpreterExplainQuery.cpp Adds analyzer gating for EXPLAIN variants that require analysis/planning.
src/Databases/enableAllExperimentalSettings.cpp Enables allow_experimental_shuffle_query in “enable all experimental” helper.
src/Core/SettingsChangesHistory.cpp Registers settings history entry for allow_experimental_shuffle_query.
src/Core/Settings.cpp Declares new experimental setting allow_experimental_shuffle_query.
src/Analyzer/QueryTreeBuilder.cpp Enforces allow_experimental_shuffle_query gate and sets query-node shuffle flag.
src/Analyzer/QueryNode.h Adds query-node flags for shuffle and shuffle-for-unordered-output.
src/Analyzer/QueryNode.cpp Adds equality/hash/clone/AST conversion support for new shuffle flags.
docs/en/sql-reference/statements/select/limit-shuffle.md New user docs page for LIMIT SHUFFLE and its experimental gating.
docs/en/sql-reference/statements/select/index.md Adds LIMIT SHUFFLE to SELECT syntax and links to the new doc page.

Comment thread src/Planner/Planner.cpp Resolved
@alexey-milovidov alexey-milovidov mentioned this pull request May 30, 2026
Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
Comment thread src/Storages/StorageView.cpp Resolved
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Jun 1, 2026
Move the old-analyzer rejection into `InterpreterSelectQuery` and `InterpreterSelectWithUnionQuery` so stored and refreshable materialized-view queries cannot silently treat `LIMIT SHUFFLE` as plain `LIMIT`.

Also fix the `04257_limit_shuffle` `INSERT ... VALUES` syntax from the failed Fast test report.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105338&sha=324cb72454d492eeb2feb730fd2e6f256cbf0824&name_0=PR&name_1=Fast%20test

PR: ClickHouse#105338
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Aug 29, 2026
Move `allow_experimental_shuffle_query` to the current `26.9` settings-history block, add the standalone `LIMIT SHUFFLE` page to navigation without editing generated `SELECT` overview content, and refresh the `04257_limit_shuffle` reference for single-record `EXPLAIN SYNTAX` output.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105338&sha=02cd45685d7b812d834c5ea45767137fd81b2d8d&name_0=PR

PR: ClickHouse#105338
@abashkeev abashkeev added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@xuir268

xuir268 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov , is there any more changes do we need

@clickhouse-gh clickhouse-gh Bot added comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 7, 2026
xuir268 added a commit to xuir268/ClickHouse that referenced this pull request Sep 8, 2026
The latest PR build failed in  because the  compatibility entry was split into its own  block, leaving the rest of the  initializer outside . Keep the entry inside the existing  list.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105338&sha=d4c42fc960f61f7b0240cc0658051a249a82371a&name_0=PR&name_1=Fast%20test

PR: ClickHouse#105338
@clickhouse-gh clickhouse-gh Bot added comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. and removed comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Sep 8, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @xuir268 — I updated the branch for you (pushed 2e4631836b3). The pull request was CONFLICTING and the Fast test / Build (arm_tidy) jobs were red on d4c42fc9; both are now addressed and the pull request is MERGEABLE.

Merged master (the branch was 438 commits behind). Four conflicts:

  • src/Core/SettingsChangesHistory.cpp — kept both entries in the 26.9 block.
  • src/Interpreters/InterpreterSelectQuery.cpp — kept both new includes.
  • src/Parsers/ParserSelectQuery.cpp — master added the LIMIT AFTER ... UNTIL ... range syntax and moved the count parsing under if (!parseLimitRange(...)). Worth flagging: the mechanical merge placed the SHUFFLE branch as an else of that outer check, where it is dead code — parseLimitRange returns false for LIMIT n SHUFFLE, so the block is entered and the branch is never reached, and LIMIT n SHUFFLE would have silently parsed as a plain LIMIT n with no SHUFFLE and no error. I chained it onto the LIMIT BY branch inside the block instead, matching the pre-merge structure, and also parsed SHUFFLE in the post-LIMIT BY second LIMIT.
  • src/Parsers/ASTSelectQuery.cpp — kept both the SHUFFLE output and master's AFTER/UNTIL output in formatImpl, and both sets of AST JSON deserialization guards.

Since SHUFFLE and LIMIT AFTER/UNTIL are mutually exclusive shapes, I rejected the combination in both places master validates: ParserSelectQuery (Can not use SHUFFLE with LIMIT AFTER/UNTIL) and the deserializeJSON invariant check.

Two build failures, both mechanical merge artifacts where master changed code immediately adjacent to this branch's insertions (e2e045b1cf6, 2c3e950d07c):

  • InterpreterCreateQuery.cpp — master added getNumberOfTablesToCreate exactly where hasLimitShuffleWithDisabledSetting ended, and the merge swallowed the latter's closing brace, so the rest of the file parsed as nested inside it (the 20 function definition is not allowed here errors in the Fast test log).
  • Settings.cpp — master removed the DECLARE of allow_experimental_codecs (it is now MAKE_OBSOLETE), and the merge resurrected it next to the new allow_experimental_shuffle_query declaration: redefinition of enumerator. The same artifact also resurrected the now-orphaned extern const SettingsBool allow_experimental_codecs; in InterpreterCreateQuery.cpp, which compiled fine but failed the style check.

Also regenerated 04257_limit_shuffle.reference: master changed the default of explain_syntax_single_record to 1, so EXPLAIN SYNTAX returns one row with \n-escaped newlines rather than one row per line.

Verified locally (release build, aarch64):

  • ninja clickhouse clean.
  • 04257_limit_shuffle, 04305_limit_shuffle_mutation_guards, 02494_query_cache_system_tables pass.
  • All 43 of master's LIMIT AFTER/UNTIL tests pass alongside them (45/45) — this was the main risk of the parser reconciliation.
  • Lazy-materialization sweep: 83/90 pass; the 7 remaining need S3/Iceberg/stateful/stateless-worker infrastructure I do not have locally.
  • Hand checks: LIMIT n SHUFFLE returns n rows and genuinely randomizes across runs; SHUFFLE with ORDER BY / OFFSET / WITH TIES / AFTER / UNTIL all rejected; LIMIT 1 BY x LIMIT 2 SHUFFLE works; the pass-2 loop(view ORDER BY rand() LIMIT 1) regression and the FINAL + filter + LIMIT-without-ORDER BY path are both fine.
  • Style check: the cpp check passes; the only remaining local failures are the environmental symlinks (my build/ directory) and settings_changes_history (needs the CI changed_files hook).

There are no unresolved review threads. The pull request still needs a maintainer review.

@clickhouse-gh clickhouse-gh Bot added comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. and removed comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. labels Sep 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8b90f4ef2 with master 41199c347 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of ddae0611a; 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.

Object file sizes

174 object files changed (+116.86 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Cache/QueryResultCache.cpp.o 303.31 KiB 367.84 KiB +64.54 KiB (+21.28%)
src/CMakeFiles/dbms.dir/Planner/Planner.cpp.o 779.44 KiB 796.25 KiB +16.81 KiB (+2.16%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@xuir268

xuir268 commented Sep 9, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Thanks for your help and I really hope we can the review as earliest possible

@xuir268

xuir268 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov @shankar-iyer @novikd Could you please take another look at this PR when you have time? I have pushed the latest merge-conflict resolutions and CI fixes, and CI is running again. This PR has been open for several months; I would appreciate a maintainer review of the current design and any remaining changes needed before it can be merged. Thank you.

Comment thread src/Interpreters/InterpreterFactory.cpp Resolved
xuir268 and others added 4 commits September 25, 2026 15:58
Plan explicit `LIMIT SHUFFLE` through random top-N selection and lazy materialization without promising output ordering. Preserve plain `ORDER BY` semantics, add query-cache and mutation guards, regression tests, and documentation. Includes stored and parameterized view mutation review fixes.

PR: ClickHouse#105338
Review: ClickHouse#105338 (comment)
Review: ClickHouse#105338 (comment)
Gate the exclusion on the old unreadable reference spelling; retain corrected-test coverage and all upgrade error checks. The replica-test race fix is now included in master and is not duplicated here.

Related: ClickHouse#121506
PR: ClickHouse#105338
CI: https://github.com/ClickHouse/ClickHouse/actions/runs/35963033445/job/107560097729?pr=105338
…ed-mr

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@xuir268

xuir268 commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov , can you tag someone from maintainer repo to review this MR

@xuir268

xuir268 commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Hi @rschu1ze , can you review the MR or tag anyone from maintainer , it is now really long time for review

@mintlify

mintlify Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit f71e7ed.

Approve preview

alexey-milovidov and others added 3 commits October 31, 2026 10:16
Git merged the master and PR changes to `LazyMaterializingTransform` and
`JoinLazyColumnsStep` constructors without conflict markers, but left two
parameter lists side by side. Keep master's `index_column_name` parameter in
its place and append the PR's `preserve_output_order` after it, so that no
existing caller passing a `String` can silently bind to the `bool`. Force
ordered output when the index column is `Nullable`: the permutation then covers
only the matched rows and cannot reorder the main chunk.

Master switched `ExplainAnalyzedSyntaxMatcher` from `InterpreterSelectQuery`
to the analyzer, so the PR's workaround that kept `LIMIT SHUFFLE` selects away
from that interpreter is obsolete. `QueryTreeBuilder` already checks
`allow_experimental_shuffle_query`. Take master's version of
`InterpreterExplainQuery.cpp`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master added sealed `SQL SECURITY DEFINER` views, and
`inlineViewSubqueryIfNeeded` returned for them before the dry-run validation
of view bodies in mutations. So `ALTER TABLE ... UPDATE value = (SELECT ...
FROM view)` over a view with `LIMIT SHUFFLE` was queued and failed only while
the mutation ran. Treat a sealed view as not inlinable instead, so it goes
through the same validation.

A view whose body is a bare `{source:Identifier}` cannot be created on current
master (`Both table name and UUID are empty`), so the test now parameterizes
the database of the view it reads.

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

Copy link
Copy Markdown
Member

🕵 Merged master and fixed the issues it exposed:

  • LazyMaterializingTransform / JoinLazyColumnsStep: master added an index_column_name constructor parameter next to the PR's preserve_output_order. Git merged the two without conflict markers and the result did not compile. preserve_output_order now comes after index_column_name. Output order is also forced when the index column is Nullable, because the permutation then covers only the matched rows.
  • InterpreterExplainQuery.cpp: master moved ExplainAnalyzedSyntaxMatcher to the analyzer, so the workaround for InterpreterSelectQuery is no longer needed (QueryTreeBuilder already checks allow_experimental_shuffle_query). The file now matches master.
  • QueryAnalyzer::inlineViewSubqueryIfNeeded: master's new sealed views returned early and skipped the mutation dry-run validation of the view body. Because of that, ALTER TABLE ... UPDATE value = (SELECT ... FROM view) was queued and failed only during execution. Sealed views now go through the validation.
  • 83522_limit_shuffle_stored_view_mutations: on current master a view whose body is a bare {source:Identifier} cannot be created, so the test now parameterizes only the database ({pdb:Identifier}.shuffle_mutation_view). This test was added after the last CI run, so CI has never run it.

04257_limit_shuffle, 04305_limit_shuffle_mutation_guards, 83522_limit_shuffle_stored_view_mutations, the lazy-materialization tests and the inline-view tests pass locally.

@alexey-milovidov

Copy link
Copy Markdown
Member

The changes are understandable, but they are not what was initially planned.

The shuffle transform should be a first-class processor in the pipeline, including full shuffle, partial shuffle, and merging shuffled streams. This is more efficient than ORDER BY, because it works in O(n) instead of O(n*log(n)), and some operations like merging shuffled streams from remote servers can work with O(1) memory instead of O(n) memory.

The shuffle clause should replace ORDER BY, not LIMIT. And we should be able to write SELECT ... SHUFFLE without LIMIT.

Queries with ORDER BY rand() can be optimized to use the new shuffle transforms (not the opposite way around).

A setting that adds random ORDER BY for testing will be adapted to add the SHUFFLE clause.

@alexey-milovidov

Copy link
Copy Markdown
Member

I see that it was confused here: #100305 (comment)

But @rschu1ze and @shankar-iyer set this task in the wrong direction... Let's close this and reopen the previous PR.

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. manual approve Manual approve required to run CI pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants