Repository navigation
Do not re-create nested Tuple elements when creating a column for deserialization - #127859
Conversation
…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]>
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).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20261026-163300 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20261026-152200 |
|
cc @Avogar @KochetovNicolai, could you review this and add the |
|
Workflow [PR], commit [404287b] Summary: ✅
AI ReviewSummaryPR #127859 replaces column wrapping with serialization-driven column creation, eliminating repeated allocation of nested Final VerdictStatus: ✅ Approve |
CI finish ledger - 453c238Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The first run of this head stopped at Session id: cron:our-pr-ci-monitor:20261027-203012 |
|
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
|
| 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 + 1factor 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, nouse_count, noIColumn::mutatewalk, 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
SerializationWrapperpeeling and notypeid_castchain, so theSerializationDetachedcase pinned bygtest_datatypetuple_createcolumn_detachedstays fixed. Handing a type to a serialization is already the established pattern,enumerateStreamsreceives it inSubstreamData. - Preconditions are no weaker than today: the column the current code inspects is
type->createColumn(), so a matching structure is already assumed, andassert_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 inMergeTreeReaderCompact,MergeTreeReaderTextIndex,SerializationNullableWithParentNullMap(on_disk_typetogether with its ownnested_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.
|
Thanks for the detailed analysis. Agreed, I am reworking this PR as you describe: |
…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]>
|
Done in 499f7b7, as you laid it out: Release build, the issue's reproducer ( #107436 adds a |
…-127427 # Conflicts: # src/DataTypes/Serializations/ISerialization.cpp
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units3249 translation units recompiled, 18331 s compile time in total, 3248 of them have a recent master baseline. Translation units without a recent master baseline:
|
Cherry pick #127859 to 26.10: Do not re-create nested Tuple elements when creating a column for deserialization
…n creating a column for deserialization
Backport #127859 to 26.10: Do not re-create nested Tuple elements when creating a column for deserialization
`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]>
Cherry pick #127859 to 26.8: Do not re-create nested Tuple elements when creating a column for deserialization
… creating a column for deserialization
Cherry pick #127859 to 26.9: Do not re-create nested Tuple elements when creating a column for deserialization
… creating a column for deserialization
Backport #127859 to 26.9: Do not re-create nested Tuple elements when creating a column for deserialization
Backport #127859 to 26.8: Do not re-create nested Tuple elements when creating a column for deserialization
Closes: #127427
Related: #111427
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Parsing row-based input formats and
Nativeinto tables with nestedTuplecolumns 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::wrapColumnForDeserializationre-created every element withcloneEmpty()at each nesting level, and each clone materialized the element's whole subtree, so a column nestedkTuples deep was createdk + 1times. Row input formats create the columns once per block throughBlock::cloneEmptyColumns, so with small blocks the clones dominated parsing (#127427: up to 3.1x slower on 26.9).ISerialization::wrapColumnForDeserialization(MutableColumnPtr)is replaced byISerialization::createColumnForDeserialization(const IDataType &), whichIDataType::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;SerializationWrapperforwards; the product quantization codebook creates its placeholderColumnConst;SerializationVariantElementandSerializationDynamicElementpeel the extraction-addedNullableoff the type.Release build, the issue's reproducer (
RowBinary,max_block_size = 1, 5000 rows of 256UInt8leaves, best of 5):a8fbea0)Nativewith 1-row blocks: 5.46 s -> 4.41 s. The newtests/performance/nested_tuple_small_blocks.xmlcovers 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); theDataTypeTupleCreateColumnand serialization gtests pass.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/127859]
Version info
26.11.1.2458-master(included in26.11and later)26.10.6.9,26.9.34.14,26.8.42.11