Skip to content

Optimize LIMIT BY by removing redundant key expressions - #106818

Merged
nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:limit-by-query-tree-optimize-keys
Jun 15, 2026
Merged

nihalzp merged 28 commits into
ClickHouse:masterfrom
nihalzp:limit-by-query-tree-optimize-keys

Conversation

@nihalzp

@nihalzp nihalzp commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

LIMIT n BY ... evaluates and hashes its key expressions for every row. When a key is a function of another key, or wraps a key in an injective function, it adds nothing to the partitioning but is still computed per row. This PR adds two analyzer passes (the LIMIT BY counterparts of the existing GROUP BY optimizations) that simplify the key list:

  • optimize_limit_by_function_keys: drops a key that is a deterministic function of the other keys, e.g. LIMIT 5 BY x, f(x) becomes LIMIT 5 BY x.
  • optimize_injective_functions_in_limit_by: replaces an injective function of a key by its argument, e.g. LIMIT 5 BY toString(x) becomes LIMIT 5 BY x.

Both are enabled by default.

image

Changelog category (leave one):

  • Performance Improvement

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

Speed up LIMIT BY queries by removing redundant key expressions: a key that is a deterministic function of the other keys is dropped (e.g. LIMIT 5 BY x, f(x) becomes LIMIT 5 BY x), and an injective function of a key is replaced by its argument (e.g. LIMIT 5 BY toString(x) becomes LIMIT 5 BY x). This evaluates fewer and cheaper expressions per row. Controlled by the new settings optimize_limit_by_function_keys and optimize_injective_functions_in_limit_by, both enabled by default.

Version info

  • Merged into: 26.6.1.839

@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ad62d4]

Summary: ✅


AI Review

Summary

This PR adds analyzer passes and settings to simplify LIMIT BY keys by dropping keys that are functions of other keys and by unwrapping injective functions. The high-level optimization is well covered for the ordinary numeric, aggregate/window, Variant, Dynamic, and non-deterministic cases, and the PR body includes before/after benchmark rows for the new LIMIT BY cases. The remaining blocker is correctness for Nullable keys: the default-enabled function-key pass can remove an expression that distinguishes hidden nested values behind SQL NULL, changing LIMIT BY partitions.

Missing context / blind spots
  • ⚠️ The current Praktika report for head 8ad62d44489929acbf542171a4836fa6ab3fecb4 has only Config Workflow and Style check completed; functional, stateless, fuzzer, and performance comparison jobs are still pending. Completed CI for this head would close that gap.
  • ⚠️ There is no local clickhouse executable in PATH, so I could not run an ad hoc SQL repro locally in this checkout.
Findings

❌ Blockers

  • [src/Analyzer/Passes/OptimizeLimitByFunctionKeysPass.cpp:36] LIMIT BY must partition by SQL key values, but removeKeysThatAreFunctionsOfOtherKeys treats assumeNotNull(n) as removable whenever nullable key n is also present. For SQL NULL, ColumnNullable groups by the null map, while assumeNotNull exposes the nested value; rows such as materialize(NULL::Nullable(UInt64)) + number are one partition under LIMIT BY n but separate partitions under LIMIT BY n, assumeNotNull(n). With optimize_limit_by_function_keys enabled by default, the rewrite can keep different rows or row counts. Keep null-unsafe functions such as assumeNotNull when a dependency can be Nullable, or otherwise require proof that the removed function depends only on the surviving key's SQL value.
Tests
  • ⚠️ Add a focused regression where multiple rows have SQL NULL in a nullable LIMIT BY key but different hidden nested values, and compare optimized and unoptimized LIMIT 1 BY n, assumeNotNull(n).
Final Verdict

Status: ❌ Block

Minimum required actions: preserve Nullable key partitioning for removed function keys, and add the focused regression above.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 38 analysed

This sync PR adds LIMIT BY query-tree optimization passes and moves the GROUP BY key logic into shared helpers — behavior-preserving for queries that don't use LIMIT BY. None of the flagged ClickBench/TPC-H queries use LIMIT BY, so the change can't directly speed them up. Q22's -23% improvement sits on a very high-variance query and is downgraded as run-to-run noise. The other three (Q23 -32%, TPC-H Q7 -36%, Q20 -50%) are large and consistent enough that their verdicts stand, but since the PR doesn't touch their execution path, the magnitudes most likely reflect measurement conditions rather than a direct effect of this change.

clickbench

🟢 1 improved · ⚠️ 1 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 23 improvement 297 201 -32.3% <0.0001 plan_change: Large, consistent -32% delta locks the verdict. Q23 has no LIMIT BY, so read magnitude as likely measurement, not direct
⚠️ 22 not_sure 334 258 -22.8% <0.0001 plan_change: ClickBench Q22 uses plain LIMIT, not LIMIT BY; this analyzer change can't touch its path. Source CV ~83% — run-to-run no

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
🟢 7 improvement 113 72 -36.3% <0.0001 plan_change: Big consistent -36% delta; verdict stands. History is noisy and Q7 uses no LIMIT BY, so treat magnitude cautiously.
🟢 20 improvement 248 125 -49.6% <0.0001 plan_change: -50% delta holds on magnitude alone, but history is noisy (base CV ~88%) and no LIMIT BY here; likely measurement, not t

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 882b86bc-1a4c-452c-83a3-c2ede246d7da
  • MIRAI run: 3ffa6211-32a7-4f52-b88a-a4bee9af5a6d
  • PR check IDs:
    • clickbench_169239_1781528419
    • clickbench_169244_1781528420
    • clickbench_169254_1781528421
    • tpch_adapted_1_official_169261_1781528422
    • tpch_adapted_1_official_169265_1781528421
    • tpch_adapted_1_official_169688_1781528526

@vdimir vdimir self-assigned this Jun 15, 2026

@vdimir vdimir left a comment

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.

Since we're reusing the same code for GROUP BY, it should be totally safe, LGTM

@clickhouse-gh

clickhouse-gh Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.10% 85.10% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 149/154 (96.75%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jun 15, 2026
Merged via the queue into ClickHouse:master with commit 3eb4c7b Jun 15, 2026
327 of 328 checks passed
@nihalzp
nihalzp deleted the limit-by-query-tree-optimize-keys branch June 15, 2026 20:57
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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.

4 participants