Skip to content

Read only the used sorting key prefix in a read split into layers - #132720

Merged
Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:read-by-layers-prefix-columns
Nov 21, 2026
Merged

Algunenano merged 5 commits into
ClickHouse:masterfrom
Algunenano:read-by-layers-prefix-columns

Conversation

@Algunenano

@Algunenano Algunenano commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

A read in order that is split into layers by a prefix of the sorting key read every column of the sorting key, although its streams are merged and its layers are filtered only by that prefix. Two plans read this way: a single uniqExact counted in order (optimize_aggregation_in_order = 1) and a merge join by ranges of the primary key (query_plan_join_shard_by_pk_ranges). Now only the columns of the used prefix are read, besides those of the query.

On ClickBench hits (100M rows, sorting key CounterID, EventDate, UserID, EventTime, WatchID), 16 threads: SELECT count(DISTINCT CounterID) FROM hits SETTINGS optimize_aggregation_in_order = 1 reads 589 KB instead of 1.24 GB and takes 12 ms instead of 90 ms. A full_sorting_merge join on k of two tables sorted by (k, s) reads 105 KB instead of 52 MB and takes 410 ms instead of 620 ms.

Related: #129508

Changelog category (leave one):

  • Performance Improvement

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

A read in order split into layers by a prefix of the sorting key (a single uniqExact with optimize_aggregation_in_order, or a merge join by ranges of the primary key) reads only the columns of that prefix instead of the whole sorting key.


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

Version info

  • Merged into: 26.12.1.128-master (included in 26.12 and later)

A read in order split into layers by a prefix of the sorting key read every column of the
sorting key, although its streams are merged and its layers are filtered only by that prefix.
This affects a single `uniqExact` counted in order (`optimize_aggregation_in_order`) and a
merge join by ranges of the primary key (`query_plan_join_shard_by_pk_ranges`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f2feee5]

Summary: ✅


AI Review

Summary

Reviewed PR #132720 at f2feee5c469418742cd16826f9d38e4e975ab0a1. The change derives the required sorting-key prefix from the stored ActionsDAG, preserving its function bindings, result names, and required input columns. No actionable findings remain. The previous expression-name blocker is fixed and covered by the new regression test. The PR provides before/after performance measurements, and current-head Fast test results confirm that 05829_read_by_layers_reads_only_key_prefix passes, including the compressed-byte assertions. Validation used existing CI results; no local build or tests were run.

Consumer coverage for the reduced expression output:

  • ExpressionTransform retains the required input passthroughs and unrelated read columns; PREWHERE and row-policy restoration preserve inputs needed by the prefix.
  • MergingSortedTransform receives the requested sorting prefix, while layer-border widths are included when selecting the expression prefix.
  • FilterSortedStreamByRange composes the stored primary-key expression with its filter and prunes unused suffix computations while preserving stream columns.
  • Sampling and final header conversion preserve query columns and remove temporary outputs before downstream aggregation, merge joins, and window processing. Ordinary preliminary merges and independent-partition reads use the same helper; FINAL retains its separate full-key path.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 18, 2026
Analyzing the sorting key again in the query context can name its expressions differently from
the sort description, which uses the names of the stored key: with `transform_null_in`, `in`
becomes `nullIn`, and the merge of a read in order threw `NOT_FOUND_COLUMN_IN_BLOCK`. Take the
prefix from the stored expression instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... label Nov 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f2feee5c4 with master a2c6c5559 (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

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.

Compile time of recompiled translation units

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

Job report

Algunenano and others added 2 commits November 19, 2026 12:13
The self-join returned 200M rows and took up to 285 s under TSan. Use nearly unique keys,
so that it returns 400k rows, and fewer, incompressible strings for the column that must
not be read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`SHA256` is not available in the fast test build without OpenSSL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fix-columns

# Conflicts:
#	src/Processors/QueryPlan/ReadFromMergeTree.cpp
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-query-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... labels Nov 20, 2026
@Algunenano
Algunenano enabled auto-merge November 20, 2026 16:58
@stresshouse

stresshouse Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=25 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 5254a923-726a-4185-9620-7f965e7a0052
  • MIRAI run: 5b8ad81c-c91b-4a94-8d52-e34cc4a42056
  • PR check IDs:
    • clickbench_683875_1795281670
    • clickbench_683881_1795281670
    • tpch_adapted_1_official_683919_1795281670
    • tpch_adapted_1_official_683940_1795281670

@Algunenano
Algunenano added this pull request to the merge queue Nov 21, 2026
Merged via the queue into ClickHouse:master with commit 1baff78 Nov 21, 2026
199 checks passed
@Algunenano
Algunenano deleted the read-by-layers-prefix-columns branch November 21, 2026 16:27
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 21, 2026
Algunenano pushed a commit to Algunenano/ClickHouse that referenced this pull request Nov 23, 2026
The measured merge join loads the column statistics of the table on a
statistics cache miss, and the compressed bytes of that load count in
`ReadCompressedBytes`, which the test compares with a tenth of the
compressed size of `s`. The `EXPLAIN PIPELINE` before the join normally
warms the statistics cache. A concurrent test that drops a table in an
`Ordinary` database empties the server-wide caches in between
(`MergeTreeData::dropAllData` calls `Context::clearCaches` for a table
without a UUID), so the join loads the statistics again. With the
randomized `uniq` statistic (about 408 KB here) and the randomized server
codec `ZSTD(1)` (threshold about 326 KB) the oracle prints 0. The read
itself is unchanged.

Create the table without statistics, so the measured queries count only
their column reads.

Related: ClickHouse#132720, ClickHouse#119664

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

2 participants