Repository navigation
Optimize LIMIT BY by pushing down LIMIT BY into Sort - #104000
Conversation
|
Workflow [PR], commit [1e6abe5] Summary: ✅ AI ReviewSummaryThis PR introduces Final Verdict
|
This is only restriction for in order LIMIT BY? and for normal, we could push any LIMIT BY to sorting step. (Yeah, in that case it will need to build hash table, but it will be build in any case for top limit by statement) |
Yes, this optimization will only work if LIMIT BY is prefix of ORDER BY.
The difference is that for normal case (LIMIT BY is not a prefix of ORDER BY), if we push down LIMIT BY, we will have |
# Conflicts: # src/Processors/QueryPlan/Optimizations/QueryPlanOptimizationSettings.cpp
|
@alexey-milovidov The PR only optimizes the case when My concern was excessive memory usage during worst case scenario when we have extremely high cardinality data but this case should be quite rare. |
|
This was fixed by #105146. Let's update the branch. |
|
@groeneai Why AST fuzzer (amd_debug) (Assertion `px != 0' failed (STID: 2286-2cea)) is failing? Try to produce a reproduction. |
|
@nihalzp Here is what I found. Short version: the failure is unique to this PR run on commit CIDB cross-PR analysisFiltered to last 60 days on
PR-specific runs on #104000:
Two prior runs of the same PR passed the AST fuzzer cleanly — only the run on the latest master-merge commit failed. The actual crashing queryThe AST fuzzer log times out (kills SELECT DISTINCT 1025, toFixedString('%', 1048576), 100
UNION ALL
SELECT 9223372036854775807, '\0', materialize(toLowCardinality(1025))This query has:
The pipeline trace from the same log confirms I grep'd the full 6.9 M-line Why the stack trace is misleadingThe visible stack is the exception-message-formatting path, not the underlying bug: So:
So Why I don't think this is your PR
What I'd suggest
Artifacts I used (for anyone reproducing):
[session: cron:clickhouse-ci-task-worker:20260518-141500] |
|
@groeneai Create a PR trying to fix the issue. |
|
Hi @nihalzp — opened a fix PR: #105264. Root cause for Deterministic reproducer that abort'd master before the fix and now returns a normal SELECT DISTINCT 1025, toFixedString('%', 1048576), 100
UNION ALL
SELECT 9223372036854775807, '\0', materialize(toLowCardinality(1025))
SETTINGS extremes = 1, max_memory_usage = '4Mi'
FORMAT Null;Fix builds into a local The other PRs with This is independent of the |
…ation `ExtremesTransform::transform` resized `extremes_columns` to `N` null entries on the first chunk and filled them one column at a time. If any step inside the loop threw — for example `MEMORY_LIMIT_EXCEEDED` raised by `insert` while copying a large value into the freshly cloned column — the member was left in a half-populated state: leading indices held size-2 columns, the failing index held a column with fewer than 2 rows, and trailing indices were still null. The exception flowed downstream via `ISimpleTransform::work`'s `catch` block, the input port was closed during pipeline shutdown, and `ExtremesTransform::prepare` then ran `ISimpleTransform::prepare` to `Status::Finished`, set `finished_transform = true`, and returned `Ready` because `!extremes && !extremes_columns.empty()`. `work` then called `extremes.setColumns(std::move(extremes_columns), 2)`. The row-count check inside `Chunk::checkNumRowsIsConsistent` spotted the short column, tried to format the error via `Chunk::dumpStructure`, dereferenced one of the still-null intrusive pointers, and aborted the server with `Assertion 'px != 0' failed (STID: 2286-2cea)` on `boost::intrusive_ptr<IColumn>::operator->`. The fix builds into a local vector and moves into the member only on success. A throw during construction destroys the local vector during stack unwinding and leaves `extremes_columns` empty, which is the documented "no chunk processed yet" state. `work` no longer materialises a partial chunk and the client receives a normal `MEMORY_LIMIT_EXCEEDED` (or whatever the original exception was) instead of a server crash. Reference CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/104000/66e1bac24c924afddb3c58be48a8174b37f0f2e3/ast_fuzzer_amd_debug/ Reported via PR: ClickHouse#104000 Co-Authored-By: Claude Opus 4.7 <[email protected]>
LLVM Coverage Report
Changed lines: 89.47% (102/114) · Uncovered code |
Optimize `LIMIT BY` by pushing down `LIMIT BY` into `Sort`
|
Hello! There is an optimization of pushing ORDER BY LIMIT into GROUP BY. Does this optimization also reflect with LIMIT BY? |
ORDER BY ... LIMIT BYqueries currently sort and merge all rows from every stream into a single stream before the finalLIMIT BYdrops the per-key excess rows. This PR adds a per-streamLIMIT BYinside the sort pipeline whenLIMIT BY's columns are a prefix of theORDER BY. Each parallel sort stream appliesLIMIT BYto itself in cheap in-order mode (O(1)memory per stream). Then final merge and subsequent steps then sees only(group_length + offset) × num_streams × distinct_keysrows instead of the entire input.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Speed up
ORDER BY ... LIMIT BYqueries by runningLIMIT BYinside each parallel sorted stream duringSortwhenLIMIT BY's columns are a prefix of theORDER BY. This reduces the number of rows flowing through the final sort merge and any downstream pipeline steps. This optimization is controlled by the new settingquery_plan_push_limit_by_into_sort(enabled by default).Documentation entry for user-facing changes
Version info
26.6.1.131