Skip to content

Do not re-create nested Tuple elements when creating a column for deserialization - #127859

Merged
Avogar merged 4 commits into
ClickHouse:masterfrom
groeneai:tuple-wrap-in-place-127427
Nov 16, 2026
Merged

Avogar merged 4 commits into
ClickHouse:masterfrom
groeneai:tuple-wrap-in-place-127427

Conversation

@groeneai

@groeneai groeneai commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #127427
Related: #111427

Changelog category (leave one):

  • Performance Improvement

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

Parsing row-based input formats and Native into tables with nested Tuple columns is faster for small blocks (streaming engines, async inserts): the per-block columns are now created once per nested element instead of once per nesting level. Closes #127427.

Description

Since #111427, SerializationTuple::wrapColumnForDeserialization re-created every element with cloneEmpty() at each nesting level, and each clone materialized the element's whole subtree, so a column nested k Tuples deep was created k + 1 times. Row input formats create the columns once per block through Block::cloneEmptyColumns, so with small blocks the clones dominated parsing (#127427: up to 3.1x slower on 26.9).

ISerialization::wrapColumnForDeserialization(MutableColumnPtr) is replaced by ISerialization::createColumnForDeserialization(const IDataType &), which IDataType::createColumn(const ISerialization &) calls. Each serialization creates the column from the type in the layout it deserializes into, so every column is created exactly once and nothing is rebuilt or mutated afterwards: the Tuple serialization creates each element from the element type with the element serialization; Sparse, Replicated and Detached create the nested column and wrap it; SerializationWrapper forwards; the product quantization codebook creates its placeholder ColumnConst; SerializationVariantElement and SerializationDynamicElement peel the extraction-added Nullable off the type.

Release build, the issue's reproducer (RowBinary, max_block_size = 1, 5000 rows of 256 UInt8 leaves, best of 5):

schema master (a8fbea0) previous in-place version this PR
depth 8 1.569 s 0.483 s 0.462 s
depth 4 0.644 s 0.343 s 0.323 s
flat 0.337 s 0.336 s 0.335 s

Native with 1-row blocks: 5.46 s -> 4.41 s. The new tests/performance/nested_tuple_small_blocks.xml covers it in CI.

Validation on a debug build: of 1766 stateless tests matching sparse|tuple|native|subcolumn|marshalling|quantize_codec|lazy_replication|variant|dynamic|json|qbit|codebook, 1728 pass, 16 are skipped and the 22 failures all come from the local rig (S3 and object storage, named collections, custom disks, schema registry, WebAssembly, PostgreSQL, non-default ports); the DataTypeTupleCreateColumn and serialization gtests pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2458-master (included in 26.11 and later)
  • Backported to: 26.10.6.9, 26.9.34.14, 26.8.42.11

groeneai and others added 2 commits October 26, 2026 16:30
…erialization

SerializationTuple::wrapColumnForDeserialization cloned every element with
cloneEmpty() and rebuilt the ColumnTuple at each nesting level, so a column
with k Tuple ancestors was created k + 1 times. IDataType::createColumn(serialization)
runs once per block in row input formats (Block::cloneEmptyColumns), so for
the depth-8 schema of ClickHouse#127427 (510 columns) every block paid 3076 extra
column creations. It came with ClickHouse#111427, which replaced
DataTypeTuple::createColumn(const ISerialization &).

Wrap the elements in place instead: the input is the freshly created base
column, whose elements are not shared, so each element is passed to its
serialization's wrap and the result is stored back in the same slot.

Release build, RowBinary, max_block_size = 1, 5000 rows, best of 5:
  depth 8: 1.558 s -> 0.478 s (26.7: 0.425 s)
  depth 4: 0.641 s -> 0.339 s (26.7: 0.308 s)
  flat:    0.333 s -> 0.332 s
Taking the element through IColumn::mutate instead of assumeMutable gives
0.679 s at depth 8, because mutate walks the whole subtree again at every
level.

Extend tests/performance/parse_engine_file.xml with a small-block read of
16-deep nested Tuples (perf.py locally: 2.03 s -> 0.62 s).

Closes ClickHouse#127427

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Condense the wrapColumnForDeserialization comment to two lines and backtick SerializationNamed.

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

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

Pre-publication review by an independent model (engine: codex; 2 findings) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new perf query is randomly skipped in PR runs (CI samples 10 of the test's 18 queries) DISAGREE Nightly runs every query (max_queries=0); PR CI samples amd and arm independently (~80% per PR); reviewers asked not to add separate perf files; also measured locally with perf.py (2.03 s -> 0.62 s).
2 💡 SerializationNamed is not in backticks in the new comment AGREE, fixed Backticked in the trimmed comment.
3 💡 The PR body table did not say that the 26.7 column is an official build AGREE, fixed in the description Column header now says so.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261026-163300

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's reproducer on a release build (RowBinary, max_block_size = 1, 5000 rows of 256 UInt8 leaves): master reads the depth-8 schema in 1.558 s against 0.333 s for the flat schema, 5/5 runs within 5%.
b Root cause explained? SerializationTuple::wrapColumnForDeserialization re-created every element with cloneEmpty() at each Tuple level, so a column with k Tuple ancestors was created k + 1 times, once per block through Block::cloneEmptyColumns. Introduced by #111427.
c Fix matches root cause? Yes. The elements of the freshly created tuple are wrapped in place, so the clone is gone at its only site. No new flag or virtual.
d Test intent preserved / new tests added? The change preserves behaviour, so the existing tests are the oracle. One query added to the existing tests/performance/parse_engine_file.xml checks the speed-up (perf.py: 2.03 s -> 0.62 s).
e Both directions demonstrated? Depth 8: 1.558 s -> 0.478 s (26.7.22.4: 0.425 s). Depth 4: 0.641 s -> 0.339 s. Flat control: 0.333 s -> 0.332 s. Native with 1-row blocks: 5.39 s -> 4.35 s.
f Fix is general across code paths? All callers reach it through IDataType::createColumn(serialization) (row input formats, Native, MergeTree and Log readers). Of the other overrides, Sparse, Replicated and Detached wrap the column they receive; Variant/Dynamic element subcolumns re-create one Nullable level, a constant cost, unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Depth 4/8 and a 16-deep chain measured; zero-element tuples keep the old early-return behaviour; Sparse, Detached, Replicated and codebook elements covered by the stateless sweep; Nullable/Array/Map/LowCardinality do not override the wrap.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format, protocol or on-disk change.
i Invariants and contracts preserved? The input is a freshly created base column whose elements are not shared (chassert(use_count() == 1) in debug builds); sizes stay 0 and the returned layout is unchanged. 912 stateless tests on a debug build have no failure that master does not also have.

Session id: cron:clickhouse-impl-slot-6:20261026-152200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @KochetovNicolai, could you review this and add the can be tested label so CI runs? SerializationTuple::wrapColumnForDeserialization now wraps the elements of the freshly created tuple in place instead of re-creating each of them with cloneEmpty() at every nesting level, which made row-format inserts into nested Tuple columns up to 3x slower since #111427.

@clickhouse-gh

clickhouse-gh Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [404287b]

Summary: ✅


AI Review

Summary

PR #127859 replaces column wrapping with serialization-driven column creation, eliminating repeated allocation of nested Tuple subtrees. Reviewed head: 404287b530ce2e60a04815da42eff2a61475dba0. No actionable findings remain in the current revision. The reported before/after measurements and focused performance test support the improvement.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Oct 26, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
@Avogar Avogar self-assigned this Oct 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 453c238

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 282 of 286 runs since 2026-10-26 22:00 UTC are red, on 236 PRs #126200 (mine, open)
PR praktika rollup of the row above #126200 (the owner of the row above)

The first run of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261027-203012

@Avogar

Avogar commented Nov 3, 2026

Copy link
Copy Markdown
Member

Thanks for digging into this, the regression is real and the direction (stop doing the redundant work) is right, but the mechanism cannot go in as is, and I think the measurements point at a cleaner fix.

Why not assumeMutable plus use_count

#111427 (8fa5b9b15ae) was specifically a refactoring to remove every assumeMutable from the deserialization path, and wrapColumnForDeserialization exists so that nothing in that path takes a mutable reference to a column whose ownership it cannot prove. Concretely:

  • element->assumeMutable() creates a second owner: the tuple slot still holds the element, so while elems[i]->wrapColumnForDeserialization(...) runs, that MutableColumnPtr has use_count() == 2, and a MutableColumnPtr is by contract the unique owner. Anything that relies on that breaks or silently pessimizes: IColumn::mutate / shallowMutate would deep-copy instead of reusing, and the natural chassert(column->use_count() == 1) on entry would fire. The function asserts uniqueness for the elements it takes while passing a non-unique mutable pointer one level down.
  • chassert is compiled out in release builds ((void)sizeof(!(x)) in base/base/defines.h), so the stated precondition does not exist in production. wrapColumnForDeserialization is a public virtual that accepts an arbitrary MutableColumnPtr, so the first caller that passes a column whose elements are shared (a cached prototype, a column taken from a Block, a future create-once-and-clone-per-block optimization) would write into columns that other owners can see, with nothing to catch it.
  • ColumnTuple::create(const Columns &) deliberately returns Ptr and not MutablePtr, with the comment "Use IColumn::mutate in order to make mutable column and mutate shared nested columns": the class refuses to hand out a mutable tuple over element pointers whose uniqueness it cannot prove. Assigning through the non-const ColumnTuple::getColumnPtr, which returns a reference to the internal immutable_ptr, goes around that.

Your measurement of IColumn::mutate being slower is correct (it re-walks the subtree at every level), but that is a sign the fix is in the wrong place rather than that the unsafe variant is needed.

What the cost actually is

I instrumented the issue's schema (2 top-level columns, 254 Tuples, 256 UInt8 leaves, so 510 column nodes) with breakpoint hit counters, one RowBinary row, max_block_size = 1:

counter per block expected
IDataType::createColumn(const ISerialization &) 2 2, one per top-level column
SerializationTuple::wrapColumnForDeserialization 254 254, one per Tuple node
ColumnTuple::cloneEmpty 1284 5x the number of Tuple nodes

So the wrap itself is called exactly once per node, nothing is called twice. The multiplier is tuple.getColumn(i).cloneEmpty(): ColumnTuple::cloneEmpty is recursive, so each call materializes the element's entire subtree, and then the recursive wrapColumnForDeserialization on that element clones its own children's subtrees again and discards everything it was handed. Per block that schema creates 3840 column objects of which 510 survive, so 87% of them exist only as a template for the next cloneEmpty (the measured 1284 matches sum over k >= 1 of 2^k * k exactly). Creating one column is cheap, about 70 ns judging by the numbers in the issue; the problem is doing 3330 pointless ones per block.

Suggested fix: drive the creation from the serialization

The two-phase shape (build the plain column, then rebuild it into the layout we want) is what forces the template clones, and in-place mutation is only needed because the tree already exists when we find out what shape it should have. Letting the serialization create the column removes both:

/// ISerialization
virtual MutableColumnPtr createColumnForDeserialization(const IDataType & type) const { return type.createColumn(); }
MutableColumnPtr IDataType::createColumn(const ISerialization & serialization) const
{
    return serialization.createColumnForDeserialization(*this);
}
MutableColumnPtr SerializationTuple::createColumnForDeserialization(const IDataType & type) const
{
    const auto & tuple_type = assert_cast<const DataTypeTuple &>(type);
    if (elems.empty())
        return tuple_type.createColumn();

    MutableColumns tuple_columns(elems.size());
    for (size_t i = 0; i != elems.size(); ++i)
        tuple_columns[i] = elems[i]->createColumnForDeserialization(*tuple_type.getElement(i));
    return ColumnTuple::create(std::move(tuple_columns));
}

The existing overrides translate mechanically: SerializationWrapper (and so SerializationNamed) forwards to nested; SerializationSparse, SerializationReplicated and SerializationDetached become ColumnSparse|ColumnReplicated|ColumnBLOB::create(nested->createColumnForDeserialization(type), ...); SerializationProductQuantizationCodebook creates its own base column, inserts the placeholder value and wraps it into a ColumnConst exactly as today; SerializationVariantElement and SerializationDynamicElement peel the extraction-added Nullable off the type with typeid_cast<const DataTypeNullable *> instead of off the column, which is the same shape test as isColumnNullable, so LowCardinality(Nullable(T)) still falls through to the nested serialization. wrapColumnForDeserialization then disappears entirely.

What this buys:

  • Exactly one creation per node, always: 510 instead of 3840 per block for the issue's schema. It removes the depth + 1 factor instead of making each repetition cheaper, so it should beat the numbers in the description, since it does not even allocate the base column at the wrapped levels.
  • No assumeMutable, no use_count, no IColumn::mutate walk, and no precondition on the caller: the layout is decided before anything is allocated, so there is nothing to mutate.
  • It keeps the composable dispatch that Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset #111427 introduced: no SerializationWrapper peeling and no typeid_cast chain, so the SerializationDetached case pinned by gtest_datatypetuple_createcolumn_detached stays fixed. Handing a type to a serialization is already the established pattern, enumerateStreams receives it in SubstreamData.
  • Preconditions are no weaker than today: the column the current code inspects is type->createColumn(), so a matching structure is already assumed, and assert_cast<const DataTypeTuple &> on the type is safer than indexing the column's elements. All call sites pass a matched type and serialization pair: NativeReader, Block::cloneEmptyColumns, MergeTreeReaderWide, both sites in MergeTreeReaderCompact, MergeTreeReaderTextIndex, SerializationNullableWithParentNullMap (on_disk_type together with its own nested_serialization) and the gtest.

The perf test is a good addition and should show a larger win with this; consider moving it to its own file, since parse_engine_file.xml is parameterized over formats.

@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the detailed analysis. Agreed, I am reworking this PR as you describe: ISerialization::createColumnForDeserialization(const IDataType &) with the overrides you listed, wrapColumnForDeserialization removed, and the perf query moved to its own file. I will post the new numbers here with the push.

…wrapping them

Replace `ISerialization::wrapColumnForDeserialization(MutableColumnPtr)` with
`ISerialization::createColumnForDeserialization(const IDataType &)`, and route
`IDataType::createColumn(const ISerialization &)` through it.

The wrap took an already created column and rebuilt it into the layout the
serialization deserializes into. For a Tuple that meant `cloneEmpty()` of every
element (each clone materializing the element's whole subtree) and then a
recursive rebuild of each clone, so a node under k Tuple levels was created
k + 1 times per block. Row formats with small blocks (Kafka, async inserts)
create a column per block, so deeply nested Tuples got up to 3x slower in 26.9.

Now each serialization creates its own column from the type: the Tuple
serialization creates every element from the element type with the element
serialization, so every node is created exactly once and nothing is mutated
or rebuilt afterwards. Sparse, Replicated and Detached create the nested
column and wrap it; the wrapper forwards; the product quantization codebook
creates its placeholder `ColumnConst` as before; VariantElement and
DynamicElement peel the extraction-added `Nullable` off the type instead of
off the column.

This replaces the previous in-place wrap in this PR, which needed
`assumeMutable` on tuple elements.

The perf query moves from `parse_engine_file.xml` to its own file.

Closes ClickHouse#127427

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

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 499f7b7, as you laid it out: ISerialization::createColumnForDeserialization(const IDataType &) with the overrides for Tuple, SerializationWrapper, Sparse, Replicated, Detached, the product quantization codebook, VariantElement and DynamicElement (Nullable peeled off the type), wrapColumnForDeserialization removed, and the perf query moved to tests/performance/nested_tuple_small_blocks.xml.

Release build, the issue's reproducer (RowBinary, max_block_size = 1, best of 5): depth 8 1.569 s on master, 0.483 s with the previous in-place version, 0.462 s now; depth 4 0.644 / 0.343 / 0.323 s; flat unchanged (0.337 / 0.335 s). Native with 1-row blocks 5.46 s -> 4.41 s.

#107436 adds a SerializationLowCardinality::wrapColumnForDeserialization override; it maps onto the new method directly (createEmptyLowCardinalityColumn(*dictionary_type, false) for the automatic encoding, type.createColumn() otherwise).

…-127427

# Conflicts:
#	src/DataTypes/Serializations/ISerialization.cpp
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 404287b53 with master c0f0d4bf6 (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

3249 translation units recompiled, 18331 s compile time in total, 3248 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.6 s

Job report

@Avogar
Avogar added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit 9fed72b Nov 16, 2026
186 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 17, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Nov 17, 2026
Cherry pick #127859 to 26.10: Do not re-create nested Tuple elements when creating a column for deserialization
robot-clickhouse added a commit that referenced this pull request Nov 17, 2026
robot-clickhouse added a commit that referenced this pull request Nov 17, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 17, 2026
Backport #127859 to 26.10: Do not re-create nested Tuple elements when creating a column for deserialization
alexey-milovidov added a commit that referenced this pull request Nov 19, 2026
`master` (#127859) replaced
`ISerialization::wrapColumnForDeserialization` with `createColumnForDeserialization`,
which takes the data type instead of an already created column.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 19, 2026
Cherry pick #127859 to 26.8: Do not re-create nested Tuple elements when creating a column for deserialization
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Nov 19, 2026
Cherry pick #127859 to 26.9: Do not re-create nested Tuple elements when creating a column for deserialization
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
robot-clickhouse added a commit that referenced this pull request Nov 19, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 19, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #127859 to 26.9: Do not re-create nested Tuple elements when creating a column for deserialization
clickhouse-gh Bot added a commit that referenced this pull request Nov 19, 2026
Backport #127859 to 26.8: Do not re-create nested Tuple elements when creating a column for deserialization
@clickhouse-gh clickhouse-gh Bot added comp-data-types Type system & core datatypes used across query planning/execution. and removed comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Nov 22, 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-data-types Type system & core datatypes used across query planning/execution. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

26.9: Row-format inserts into nested Tuple tables are up to 3x slower (Kafka ingest 1.8x)

7 participants