Skip to content

Allow flattenable Tuple leaves to participate in Vertical merge - #120225

Open
JasonLi-cn wants to merge 17 commits into
ClickHouse:masterfrom
JasonLi-cn:vertical-merge-tuple-subcolumns-minimal
Open

JasonLi-cn wants to merge 17 commits into
ClickHouse:masterfrom
JasonLi-cn:vertical-merge-tuple-subcolumns-minimal

Conversation

@JasonLi-cn

@JasonLi-cn JasonLi-cn commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

A flattenable Tuple is one gathering column for Vertical merge even though its leaves are independent on-disk streams. Tables that store a few wide Tuple columns therefore stay on Horizontal merge and keep every leaf live at once.

Approach

New experimental MergeTree setting allow_experimental_vertical_merge_tuple_subcolumns (default off). When it is on, flattenable gathering parents are replaced with leaf NameAndTypePairs before chooseMergeAlgorithm, so leaf count (including nested flattenable tuples) feeds vertical_merge_algorithm_min_columns_to_activate. Skip indexes that only need one leaf are re-keyed onto that leaf. After each parent group is gathered, parent columns_substreams are copied from the substreams the leaf writers opened, and parent SerializationInfo is folded from those leaves, so the output part schema is unchanged: columns.txt still lists the original Tuple columns.

Flatten is refused when a source is Compact, a leaf has a dynamic structure (Dynamic or JSON), a skip index or non-implicit statistic needs the parent as a whole, this merge must rebuild parent statistics from the gather pipeline, a leaf name collides with a storage column, or a source/patch part cannot read the leaf as a subcolumn. A Map leaf is gathered; its bucket streams are copied from the leaf writer. Implicit basic statistics on a flattenable Tuple do not pin flatten when existing part stats can be merged by parent name.

Performance

Before/after measurement on a representative wide-Tuple workload: id UInt32, t Tuple(e0 String, ..., e10 String) (11 String leaves, each repeat('x', 100)), two Wide parts merged by OPTIMIZE TABLE ... FINAL. A third shape flattens the same data into standalone columns (id, e0, ..., e10) as the ideal baseline. Metrics are the median of 3 runs from system.part_log (peak_memory_usage, duration_ms), release build.

part size (uncompressed) shape algorithm peak memory duration
~227 MB Tuple, setting off Horizontal 130.3 MiB 391 ms
~227 MB Tuple, setting on Vertical 11.9 MiB 290 ms
~227 MB flattened columns Vertical 11.9 MiB 280 ms
~568 MB Tuple, setting off Horizontal 189.4 MiB 984 ms
~568 MB Tuple, setting on Vertical 20.1 MiB 701 ms
~568 MB flattened columns Vertical 20.0 MiB 685 ms

The setting flattens the Tuple into 11 leaf gathering columns, so Vertical merge holds one leaf in memory at a time instead of the whole row. This cuts peak merge memory by ~90% and matches the ideal manually-flattened-columns baseline exactly (+0.0% memory), while also finishing ~26-29% faster. Data after merge is byte-identical to the flattened-columns table.

Changelog category (leave one):

  • Experimental Feature

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

Added experimental MergeTree table setting allow_experimental_vertical_merge_tuple_subcolumns. When enabled, named Tuple fields can be merged one leaf at a time by Vertical merge, which can cut peak memory for wide tuples. The on-disk table schema is unchanged. Disabled by default.


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

@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization labels Sep 15, 2026
@JasonLi-cn
JasonLi-cn force-pushed the vertical-merge-tuple-subcolumns-minimal branch from f3ee27c to ed29344 Compare September 16, 2026 02:58
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Refuse leaf-by-leaf gathering when a flattened leaf spelling resolves to multiple serialization paths, including synthetic subcolumn collisions.

Add stateless coverage for nested and synthetic ambiguities.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Encapsulate flattened-leaf size accounting, pending serialization state, and parent metadata commits in `MergeTreeVerticalMergeTupleSubcolumns`.

Keep only the required algorithm-selection and per-column hooks in `MergeTask`.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Remove redundant merging and expired-column inputs whose invariants are already established by `MergeTask`.

Derive the flatten decision directly from whether classification produced leaves.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Traverse the parent serialization tree once and look up gathered leaf data by name instead of rescanning the tree for every leaf.

Pin `materialize_statistics_on_insert` on the INSERT queries whose merge-path assertions require existing part statistics.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Attempt gathering-column flattening only when both the experimental feature and the Vertical merge algorithm are enabled.

Keep `tryFlattenGatheringColumns` focused on classification and transformation.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 16, 2026
Drop cases already covered by dedicated tests, and fold implicit `basic`
copy-stats into 05188 so 05219 only pins flatten when statistics must be rebuilt.

Related: ClickHouse#120225
Co-authored-by: Cursor <[email protected]>
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd34447]

Summary: ✅


AI Review

Summary

This PR adds the experimental MergeTree setting allow_experimental_vertical_merge_tuple_subcolumns and teaches Vertical merge to split flattenable Tuple gathering columns into leaf subcolumns when the surrounding metadata work makes that safe. I reviewed the current diff, reread every existing inline thread and reply, and checked the updated code paths in MergeTask, AlterConversions, MergedColumnOnlyOutputStream, and MergeTreeVerticalMergeTupleSubcolumns. I did not find a remaining correctness, safety, or performance issue that warrants a new review comment in the current revision.

Final Verdict

✅ No actionable findings in the current revision.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Sep 19, 2026
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
Use gathered row counts for leaves without their own `SerializationInfo`, including all-non-sparse leaf groups after row-reducing merges.

Related: ClickHouse#120225
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
Require ambiguous-leaf optimization to succeed and verify that update and rename scenarios actually use Vertical merge.

Related: ClickHouse#120225
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
Expect the duplicate physical stream schema to be rejected while retaining the valid synthetic-subcolumn case for Vertical merge classification.

Related: ClickHouse#120225
JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 20, 2026
Classify parent dependencies from active index and statistics rebuild worklists, and ignore disabled or excluded merge-time materialization.

Related: ClickHouse#120225
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bd3444774 with master 46dfb8152 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

8 object files changed (+272.67 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeVerticalMergeTupleSubcolumns.cpp.o new 268.97 KiB +268.97 KiB

719 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

380 translation units recompiled, 3663 s compile time in total, 379 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/MergeTree/MergeTreeVerticalMergeTupleSubcolumns.cpp: 8.2 s

Job report

JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 21, 2026
`Fast test (arm_darwin)` exposes part data streams as symbolic links, so
`find -type f` omitted them. Include both regular files and symbolic links
when checking generated stream, index, and statistics files.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=c508767ac1793df9d7cf5c13e1ab49366435b322&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
PR: ClickHouse#120225
@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the unrelated Build profile diff failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=c508767ac1793df9d7cf5c13e1ab49366435b322&name_0=PR&name_1=Build%20profile%20diff and provide a fix in a separate PR. It matches the open fleet-wide infrastructure issue #120462. If a fix is already in progress, link it here.

JasonLi-cn added a commit to JasonLi-cn/ClickHouse that referenced this pull request Sep 21, 2026
BSD `find` on macOS does not support `-maxdepth`, and the trailing `sort`
masked that failure. Enumerate immediate children with a shell glob while
preserving regular-file and symbolic-link filtering.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=c508767ac1793df9d7cf5c13e1ab49366435b322&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
PR: ClickHouse#120225
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in flight: #121048 ("CI: Build profile diff is green when the CI logs cluster does not answer"), so I am not opening a separate one.

It covers your shape exactly. In your job log the readiness probe passed every time (zero LogCluster not ready) and no attempt ever came back with an HTTP status (zero LogCluster select failed with code); the reads only timed out at the transport level against the CI logs endpoint, 15 requests.exceptions.ReadTimeout with read timeout=60, the final read on all 8 of its attempts between 21:19:10Z and 21:28:31Z. At #121048's head that is the path which sets post_attempted and raises LogClusterUnavailable("every POST attempt failed with an exception"), and main() completes the job green on it.

Two things about clearing the red in the meantime, since #121048 is not merged:

  • Merging master will not clear it. None of the fix is on master yet.
  • A plain re-run of Build profile diff can, because the endpoint is flapping rather than down. In CIDB, check_name = 'Build profile diff' over the last 24 hours is 119 green against 267 errored, in bursts; your run (21:02Z to 21:29Z) fell inside one of them, 22 errored runs in that hour alone, and inside the job itself an earlier read timed out 7 times and then got through. The most recent green run finished at 03:22:53Z, so it is answering at the moment.

Related: #120462

@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the unrelated performance failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=528c7f8d6a280795ecf4672dcd51e549b878bbc5&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. order_by_read_in_order #1 was slower in 33/660 master runs and unstable in 44/660 master runs over the preceding 30 days; the same query is also documented on unrelated PRs in #121090. If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

I confirmed this is not your change.

That shard's Select historical data step timed out three times against play.clickhouse.com (read timeout=10) and fell open with WARNING: Failed to fetch historical thresholds, will proceed without them, leaving historical-thresholds.tsv empty. Every query in the shard was then judged against the bare floor instead of its learned per-query bar. In the shard's own all-query-metrics.tsv, order_by_read_in_order #1 carries changed_threshold = 0.15; the bar it actually earns is 0.65 (quantileExact(0.99)(abs(diff)) * 1.5 = 0.642 over 1974 master samples in the window the harness itself queries). The measured diff is 0.335, below even the unscaled 0.99 quantile of abs(diff) for this query (0.428), and the same row's stat_threshold is also 0.335, so it cleared abs(diff) >= stat_threshold by equality alone. In absolute terms, 16.2 ms to 21.6 ms. Three of the four queries the floor flagged in that shard were then demoted by the confirmation rerun.

Fixes are already in flight, so I am not opening a separate PR:

@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the unrelated Storage memory check failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=37c55ad1f0e0f1fcab849019ffdfcf3ad521db8d&name_0=PR&name_1=Storage%20memory%20check and provide a fix in a separate PR. If the fix is already in progress, link it here.

The failing 03_add_secondary_indexes.sql delta was +1,120 bytes, only 96 bytes above the 1,024-byte absolute threshold. CIDB shows 3 failures among 201 runs on 2026-09-21, including the same quantized ~1–2 KiB variation on unrelated PRs such as #121251 and #76867. This PR does not change secondary-index marks loading or the profiler.

Comment thread src/Storages/MergeTree/MergeTask.cpp Resolved
Flattenable `Tuple` inner fields can be gathered as stream-scheduling tasks
of their parent storage column. The output schema stays one column. The
feature is experimental and off by default; classify and I/O still need
follow-up tuning.

Squashes the 24 feature commits on `vertical-merge-tuple-subcolumns-minimal`
onto the latest `master`.

Related: ClickHouse#120225
@JasonLi-cn
JasonLi-cn force-pushed the vertical-merge-tuple-subcolumns-minimal branch from cd4781a to 97b5846 Compare September 23, 2026 08:22
The classifier received the full `text_indexes_to_merge` list, so a parent
`Tuple` stayed pinned whenever any text index referenced it, even on ordinary
merges where `MergeTextIndexStage::prepare` reuses the index's existing
segment files (every source part already has the materialized index) and the
merge never reads the parent Tuple data at all. That kept steady-state tables
with e.g. `INDEX idx toString(t) TYPE text` on Horizontal forever, defeating
the setting's memory-saving path.

Compute an effective rebuild worklist instead, mirroring the skip-index and
statistics handling: when `merge_may_reduce_rows` is false, a text index pins
the parent only if some non-empty source part lacks the materialized index
(`getDeserializedFormat`), matching `MergeTextIndexStage::prepare` and
`addBuildTextIndexesStep`. A row-reducing merge always rebuilds text indexes
from column data, so every text index still pins in that case. The full
`text_indexes_to_merge` is left untouched for the merge itself.

`05234_vertical_merge_tuple_subcolumns_effective_metadata` now expects
Vertical for a fully materialized parent text index, and gains two cases that
keep the parent pinned: a source part missing the index, and a row-reducing
`ReplacingMergeTree` merge.

Addresses review feedback on ClickHouse#120225
…e-subcolumns-minimal

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]>
…n column list

`tryGetColumn` answers from the shared `columns_description` cache, so part load order could count a leaf the source part's parent type cannot express and unlock Vertical merge.
…e leaf writers

Synthesizing the parent substreams from an empty column dropped data-dependent streams, so a multi-bucket `Map` leaf was recorded as a single bucket in `columns_substreams.txt`.
`Map` reports `hasDynamicSubcolumns` because bucket streams depend on the data, so flatten was refused and `05259_vertical_merge_tuple_subcolumns_map_buckets` stayed on Horizontal merge. Refuse only a dynamic structure (`Dynamic`, `JSON`). The leaf writer still records `Map` bucket streams for the parent `columns_substreams`.

CI: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=971f4f117da8443a93c689d0e10b376cfe86b8c6&name_0=PR&name_1=Fast%20test
Related: ClickHouse#120225
@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 Fast test 05259_vertical_merge_tuple_subcolumns_map_buckets stayed on Horizontal merge because a Map leaf reports hasDynamicSubcolumns, so flatten was refused before the leaf-writer columns_substreams path could run. Flatten now refuses only a dynamic structure (Dynamic, JSON). Map bucket streams are still copied from the leaf writer.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=971f4f117da8443a93c689d0e10b376cfe86b8c6&name_0=PR&name_1=Fast%20test

`MergeTask` only needs to call flatten before `chooseMergeAlgorithm` and finalize each gathering unit. Keep the text-index rebuild worklist, checksum split, and parent `columns_substreams` commit in `MergeTreeVerticalMergeTupleSubcolumns`.

Related: ClickHouse#120225
@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 Tagged 05186_vertical_merge_tuple_subcolumns_rename with no-fasttest so Style check failpoint_tests_are_isolated passes. Merged current master (the branch was more than a week behind).

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=035454121a6bb48d1309ac50943998dc051d3d10&name_0=PR&name_1=Style%20check

…hecks

`getPatchesForColumns` already maps `t2` back to the `t` a patch still stores after `RENAME COLUMN`. The readability proof must use the same mapping, or a rename plus `apply_patches_on_merge` silently keeps the merge on Horizontal.

ClickHouse#120225
@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=fcfa631c1bc25eed8d42bd205bccb9e9acdeab8b&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The job hit its 9000 s timeout after 1170/1176 tests with no failing test. This matches the open split in #123849.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123849 splits Stateless tests (arm_asan_ubsan, azure, sequential) into 2 hash batches. The job.log for fcfa631 has the same shape as the earlier kills: 1170 of 1176 tests reached (1072 OK, 98 skipped, 0 failed), then Timeout exceeded [9000]. It is not caused by this PR: the same job timed out on 15 master commits in the last 7 days. Both batches pass on the latest run of #123849; it is waiting for review.

`SYSTEM STOP MERGES` also stops mutations, so `ALTER TABLE ... RENAME COLUMN` never finished. Start merges first so the rename can rewrite ordinary parts while the patch still stores `t`.

ClickHouse#120225
…he dynamic serialization fuzzer.

The setting was renamed on `master`; keep the fuzzer compiling after the merge. Same adaptation as ClickHouse#124798.

ClickHouse#120225
@JasonLi-cn

Copy link
Copy Markdown
Contributor Author

🕵 Merged current master (the branch was red and behind). Build (arm_tidy, 2/4) failed on the merge with master because parkOneRequest from #113697 still instantiates the removed FifoQueue. Replaced it with RequestQueue, and renamed object_and_dynamic_read_statistics to read_statistics in the dynamic serialization fuzzer, matching #124798.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120225&sha=520b56a12537be7c7c34950caa17a042c6d7ac8d&name_0=PR&name_1=Build%20(arm_tidy,%202/4)

The earlier Stateless tests (arm_asan_ubsan, azure, sequential) timeout on fcfa631c is the open split in #123849 (job hit 9000s after 1170/1176 tests, 0 failed).

@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... external Author is not a member of the ClickHouse organization pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants