Skip to content

Avoid quadratic time in merge() over tables with many columns - #124115

Merged
murphy-4o merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-many-columns-linear
Oct 6, 2026
Merged

murphy-4o merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/merge-many-columns-linear

Conversation

@groeneai

@groeneai groeneai commented Oct 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118156
Related: #118318
Related: #123926

Changelog category (leave one):

  • Performance Improvement

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

Queries to the merge table function and creation of Merge tables are faster when the source tables have many columns: combining the source columns took time quadratic in the number of columns.

Description

StorageMerge::getColumnsDescriptionFromSourceTablesImpl adds each source column with ColumnsDescription::add(column, prev_column_name) to keep the source order, and getNameRange found the after column by a linear scan of the sequenced index, although the container has an ordered_unique index on the name. So every merge(...) query paid N^2/2 name comparisons (2.4M for the 2202 columns of system.metric_log, which 97 system.dashboards charts read through merge('system', '^metric_log')).

getNameRange now looks the exact name up in the name index and keeps the linear prefix scan only for the Nested-prefix fallback. Names are unique, so it returns the same column as before. Two read-only whole-ColumnsDescription copies on the same path (each clones every default expression) become references.

This is the StorageMerge part of the slowdown asked about in #118156; the analyzer part is #123926.

Debug build, median of 30 queries over an N-column table with one row:

columns 1000 2000 4000 8000
merge(), before 8.8 ms 19.9 56.2 174.2
merge(), after 6.8 12.3 23.9 48.5
direct read 2.6 4.6 8.6 16.8

What merge() adds over the direct read grew 3.1-3.3x per doubling before and 2.0-2.1x after. Over system.metric_log that overhead drops from 20 to 12 ms (wide schema) and from 29 to 19 ms (bucketed). The new performance test merge_table_function_many_columns uses 2049 columns and times 20 merge() queries as one.


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

Version info

  • Merged into: 26.10.1.1667-master (included in 26.10 and later)

`StorageMerge::getColumnsDescriptionFromSourceTablesImpl` inserts each
source column with `ColumnsDescription::add(column, prev_column_name)`,
and `getNameRange` resolved the after-column by a linear scan of the
sequenced index, so building the columns of a `merge()` table function
or a `Merge` table was quadratic in the column count. Look the exact
name up in the existing `ordered_unique` name index instead and keep
the linear prefix scan only for the Nested-prefix fallback. Names are
unique, so the result is the same element the old loop found.

Also stop copying the whole `ColumnsDescription` (which deep-clones
every default expression) where it is only read: the source table's
columns in `getColumnsDescriptionFromSourceTablesImpl` and the child's
columns in `ReadFromMerge::getModifiedQueryInfo`.

Add a performance test with a 2049-column source table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 6, 2026
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review: my own cold review plus an independent model (engine: codex, 1 round, 0 findings).

# Sev Finding Verdict Evidence / action
1 💡 The performance test queries are short (a few ms on a release build), below the 0.1 s guidance in tests/performance/scripts/README.md AGREE, not changed the change is 2-3x, well above the noise; if the comparison marks the queries unstable, the fixture grows to 64x64 columns

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-8:20261006-004600

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. An N-column UInt8 MergeTree table with one row, 30 merge() and 30 direct count() queries, medians from system.query_log (debug build): without the fix the merge() overhead over the direct read grows 3.12x (N 2000 to 4000) and 3.30x (4000 to 8000) on every run.
b Root cause explained? getColumnsDescriptionFromSourceTablesImpl adds each source column with ColumnsDescription::add(column, prev_column_name); getNameRange resolved the after column by a linear scan of the sequenced index, so building the columns of a merge() table was O(N^2) in the column count.
c Fix matches root cause? Yes. getNameRange uses the existing ordered_unique name index for the exact name (O(log N)) and keeps the prefix scan only for the Nested-prefix fallback. No caller-side workaround, no cache.
d Test intent preserved / new tests added? New tests/performance/merge_table_function_many_columns.xml (2049 columns). No existing test changed.
e Both directions demonstrated? Before: overhead 6.2 / 15.3 / 47.6 / 157.4 ms at N = 1000 / 2000 / 4000 / 8000 (3.1-3.3x per doubling). After: 4.1 / 7.6 / 15.3 / 31.5 ms (2.0-2.1x per doubling). The new perf test: 23 ms before, 14-15 ms after (debug).
f Fix is general across code paths? All getNameRange users share it (add, remove, modifyColumnOrder, getNested, hasNested, hasColumnOrNested); the merge table function and ENGINE = Merge use the same function. 81 Merge, Nested and ALTER ... AFTER/FIRST stateless tests pass with and without randomized settings.
g Fix generalizes across inputs (params/datatypes/wrappers)? The lookup is by name and independent of types. Measured on plain columns and on the ALIAS-heavy bucketed system.metric_log schema (merge() overhead 29 to 19 ms; wide 20 to 12 ms).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or behaviour change; names are unique, so the lookup returns the same column as the old loop.
i Invariants and contracts preserved? getNameRange still returns the exact-name column if it exists, else the contiguous range of name.-prefixed columns, as sequenced iterators. The two new references are read-only and outlive their use; add still copies each column, so it never mutates the source table's metadata.

Session id: cron:clickhouse-impl-slot-5:20261006-000110

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1a3c94f]

Summary: ✅


AI Review

Summary

This PR removes the quadratic exact-name lookup from Merge schema construction by teaching ColumnsDescription::getNameRange to use the existing ordered name index, and it also avoids two read-only ColumnsDescription copies on the same path. I verified the changed ColumnsDescription and StorageMerge paths against the current diff, checked the prior inline discussion, and do not see a remaining contract violation or evidence gap: the exact-name / nested-prefix behavior is preserved, the reference lifetimes stay backed by immutable metadata snapshots, and the performance fixture now batches 20 statements in one <query file=...> entry, which the harness times as a single measurement.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 1a3c94f.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 15/15 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Oct 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-storage-merge Merge table engine (logical union over tables) and related mechanics. label Oct 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: fc1fb62c-390d-4cd2-a980-7df33fdb8699
  • MIRAI run: 58f94372-96dd-4c3c-b514-54bd9d73566e
  • PR check IDs:
    • clickbench_3485504_1791264645
    • clickbench_3485517_1791264645
    • clickbench_3485523_1791264645
    • tpch_adapted_1_official_3485530_1791264646
    • tpch_adapted_1_official_3485560_1791264645
    • tpch_adapted_1_official_3485574_1791264646

@clickhouse-gh

clickhouse-gh Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1a3c94ff8b7db249253d4d69c0fcdd36734409f2 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

A single merge() query over the 2049-column table runs in about 10 ms
on a release build, below the 0.1 s minimum of the performance tests.
Run 20 of them from a query file, as one measured entry. They are
separate queries because identical table functions in one query are
resolved only once.

With the CI amd_binary builds and tests/performance/scripts/perf.py
on two local servers: master 0.337 s, this PR 0.174 s, p = 1e-16
(previously 19.2 ms and 10.0 ms).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Make merge over tables with many columns linear in the column count Avoid quadratic time in merge() over tables with many columns Oct 6, 2026
@murphy-4o murphy-4o self-assigned this Oct 6, 2026
@murphy-4o
murphy-4o added this pull request to the merge queue Oct 6, 2026
Merged via the queue into ClickHouse:master with commit 3975bec Oct 6, 2026
149 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 6, 2026
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-storage-merge Merge table engine (logical union over tables) and related mechanics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants