Skip to content

Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset - #111427

Merged
Avogar merged 21 commits into
masterfrom
experiment-icolumn-ref-deserialize
Aug 26, 2026
Merged

Avogar merged 21 commits into
masterfrom
experiment-icolumn-ref-deserialize

Conversation

@Avogar

@Avogar Avogar commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

PR #109105 replaced assumeMutable with IColumn::mutate in the some pars of the deserialization code. When a column is shared via the substreams cache, IColumn::mutate clones the whole accumulated column, giving O(rows × granules) cost and a 3–4× deserialization slowdown.

Rework the deserialize path so it never clones:

  • deserializeBinaryBulkWithMultipleStreams and its helpers take IColumn & instead of ColumnPtr &.
  • The substreams cache never shares a ColumnPtr; consumers copy the current range out via insertRangeFrom.
  • assumeMutable/IColumn::mutate/const_cast are removed from the deserialize paths; mutable children come from non-const accessors.
  • Cache-shared members are dropped from the Deserialize*State structs.
  • The MergeTree reader stack reads into MutableColumns.

Additionally, remove rows_offset from the deserialization API. rows_offset (the number of leading rows to skip while deserializing a range) is provably always 0 for every caller, so it is dropped from deserializeBinaryBulkWithMultipleStreams, deserializeBinaryBulk and all their helpers. This deletes the read-side skip machinery:

  • the skip loops / istr.ignore(size * rows_offset) seeks;
  • the Map bucketed reorder-with-skipped-rows path (which also removes a latent substreams-cache over-count on bucketed Map);
  • the Object shared-data granules_offsets / last_incomplete_granule_offset cursors (the load-bearing StructureGranule continuous-read state is kept);
  • the SerializationArrayOffsets helper (rows_offset-only);
  • assorted dead offset arithmetic.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove the always-zero rows_offset parameter.


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

Version info

  • Merged into: 26.9.1.157 (included in 26.9 and later)
  • Backported to: 26.8.3.8

Avogar and others added 2 commits July 22, 2026 16:28
…ssion

PR #109105 replaced `assumeMutable` with `IColumn::mutate` in the
deserialization code. When a column is shared via the substreams cache,
`IColumn::mutate` clones the whole accumulated column, giving
O(rows × granules) cost and a 3–4× deserialization slowdown.

Rework the deserialize path so it never clones:
- `deserializeBinaryBulkWithMultipleStreams` and its helpers take
  `IColumn &` instead of `ColumnPtr &`.
- The substreams cache never shares a `ColumnPtr`; consumers copy the
  current range out via `insertRangeFrom`.
- `assumeMutable`/`IColumn::mutate`/`const_cast` are removed from the
  deserialize paths; mutable children come from non-const accessors.
- Cache-shared members are dropped from the `Deserialize*State` structs.
- The MergeTree reader stack reads into `MutableColumns`.
- `SerializationDetached` builds its `ColumnBLOB` in
  `IDataType::createColumn` and fills it during deserialization, since
  the `IColumn &` signature can no longer swap the column pointer.

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

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3846f2e]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
Start ClickHouse Server FAIL IGNORED

AI Review

Summary

This PR refactors bulk deserialization to stop mutating shared cached columns, moves detached reads onto pre-wrapped receivers, and removes the now-unused rows_offset plumbing. The overall direction looks reasonable, but the current String size-stream changes still accept one corrupted-input shape silently, and the PR's explicit performance claim is still not backed by actual comparison data.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationString.cpp:857] If the size stream already appended non-zero offsets, the new if (!stream) return; path silently leaves ColumnString with offsets.back() > chars.size() instead of rejecting bad input. The valid schema-evolution case this commit wants to allow is the "both substreams absent" case; once bytes_to_read > 0, a missing regular stream is still corrupted data and should fail.

⚠️ Majors

  • [src/DataTypes/Serializations/SerializationString.cpp:795] deserializeStringOffsetsAndGetDataSize promises to append to the existing column, but the new monotonicity check starts at prev_num_rows, so it never compares the previous tail against the first appended absolute offset. A multi-call absolute-offset read can therefore append a decreasing first offset and leave ColumnString inconsistent. SerializationArray::deserializeOffsetsBinaryBulk already handles this boundary by starting one element earlier.
  • [tests/performance/subcolumn_deserialization_tuple_map.xml:9] [dismissed by author -- https://github.com/Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset #111427#discussion_r3758603347] The PR description still claims a 3–4× deserialization speedup, but the Performance Comparison shards for this PR were skipped because the PR is not labeled pr-performance, so there is still no before/after measurement attached to the change. The new arm perf workloads are useful future coverage, but they are not evidence for this PR's stated improvement.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Make the missing-regular-stream path in SerializationString::deserializeBinaryBulkWithSizeStream fail whenever the already-read sizes imply bytes_to_read > 0.
    2. Fix the absolute-offset monotonicity check to validate the boundary between the previously appended tail and the first newly read offset.
    3. Attach actual performance comparison data for the claimed deserialization speedup, or drop/reword the claim.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.50% +0.10%

Changed lines: Changed C/C++ lines covered: 1598/1736 (92.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 22, 2026
@StackSlayerAI

Copy link
Copy Markdown
Contributor

CI Triage (bot) — head 6a9e4ad4 — 2026-07-22

Verdict: REAL FAILURE — build error introduced by this PR

Fast test and Build (arm_tidy) both fail with a compilation error in src/DataTypes/Serializations/SerializationQuantizedVector.cpp:

SerializationQuantizedVector.cpp:119:44: error: non-virtual member function marked 'override' hides virtual member function
  119 |         SubstreamsCache * /*cache*/) const override
      |                                            ^
SerializationWrapper.h:49:10: note: hidden overloaded virtual function
  'DB::SerializationWrapper::deserializeBinaryBulkWithMultipleStreams' declared here:
  type mismatch at 1st parameter ('IColumn &' vs 'ColumnPtr &')

The deserialization refactor in this PR changed the first parameter of deserializeBinaryBulkWithMultipleStreams from IColumn & to ColumnPtr & (i.e. immutable_ptr<DB::IColumn> &) in some overrides, causing a signature mismatch with the base class SerializationWrapper::deserializeBinaryBulkWithMultipleStreams(IColumn &, ...). The override keyword hides rather than overrides the virtual function. A matching test in gtest_object_serialization.cpp:380 also fails for the same reason.

Action needed: Fix the parameter type mismatch in SerializationQuantizedVector (and the gtest) so that the override correctly matches the base class signature.

Run ID: 29940791453

…lization

After merging master, the new `SerializationQuantizedVector` per-part codebook
subcolumn deserializes into a `ColumnConst` (one value broadcast over the whole
range), which the `IColumn &` deserialize contract cannot swap in.

Add `ISerialization::wrapColumnForDeserialization`, which wraps the base
`type->createColumn()` into the column layout a serialization deserializes into.
Each layer composes through the serialization chain, replacing the kind-stack
loop in `IDataType::createColumn`:
- `SerializationSparse`/`SerializationReplicated`/`SerializationDetached` wrap into
  `ColumnSparse`/`ColumnReplicated`/`ColumnBLOB`.
- `SerializationWrapper` forwards to nested; `SerializationTuple` wraps each element
  by its element serialization, so `DataTypeTuple::createColumn(serialization)` is removed.
- `SerializationProductQuantizationCodebook` wraps into a `ColumnConst` that its
  deserialize fills in place (`ColumnConst::setValue`) and grows, so the (large)
  codebook is never materialized per row.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/DataTypes/IDataType.cpp Resolved
Avogar and others added 2 commits July 23, 2026 15:47
`LogSource` allocated the destination column with the plain `createColumn()`
and, before the `IColumn &` deserialize refactoring, relied on the swappable
`ColumnPtr &` to turn it into a wrapped column during deserialization. That
escape hatch is gone, so build the column with `createColumn(*serialization)`
instead. This matters for subcolumns whose serialization wraps the column
(e.g. the quantized-vector codebook, deserialized into a `ColumnConst`).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`DataTypeTuple` no longer overrides `createColumn(const ISerialization &)`, so on a
`DataTypeTuple`-typed pointer that name is hidden by the derived `createColumn()`
(name hiding applies to every IDataType subclass; real callers use a base DataTypePtr).
Call it through a `DataTypePtr` in gtest_datatypetuple_createcolumn_detached, matching
real callers. Also drop `virtual` from `IDataType::createColumn(const ISerialization &)`
since nothing overrides it now (it just wraps the virtual createColumn()).

https://s3.amazonaws.com/clickhouse-test-reports/PRs/111427/71fcf5a9cccdfcada11346e7aceb4e90f4ba419d/build_arm_tidy/job.log

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

clickhouse-gh Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 1114/1208 (92.22%) · Uncovered code

Full report · Diff report

Resolve conflicts from master's substreams-cache-ownership-checks work and
the bucketed Map key-order preservation.

- Keep the branch's IColumn& deserialize contract and the copy-out (no-share)
  substreams cache; keep master's size >= num_read_rows chassert guards.
- Remove the ColumnsOwnershipValidator subsystem (base hooks, per-serialization
  forEachColumn/forEachNestedState overrides, and reader/StorageLog call sites);
  it is vacuous under the branch's ownership model. Preserve the co-located
  non-validator fixes (Variant/Dynamic popBack, Dynamic/SubObjectSharedData
  deep-clone in clone(), quantized-vector part-metadata keying).
- SerializationNullableWithParentNullMap: deserialize the nested element into a
  temporary published clean to the cache, then apply the parent null map to an
  independent insertRangeFrom copy and append it, never mutating a published
  column.
- SerializationMap/SerializationMapKeysOrValues: adopt master's bucket-index
  order preservation (has_bucket_index, reorder_with_skipped_rows,
  collect...WithOrder, check_stream_exists_callback plumbing) adapted to the
  branch's IColumn& model.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rialize API

The arm_tidy build is the only CI build that compiles unit_tests_dbms, so it
caught two serialization gtests that were never migrated to the refactored
`deserializeBinaryBulkWithMultipleStreams(IColumn & column, ...)` signature:
they still passed a `ColumnPtr` (which no longer binds to the non-const
`IColumn &`), and one used the removed
`insert_only_rows_in_current_range_from_substreams_cache` setting.

Migrate both tests to create a mutable column and pass it by reference. The
removed setting's behavior is now the only behavior of `insertDataFromCachedColumn`
(it always inserts the current range from the cache), so the cache-reuse test
still exercises the same path; update its comment accordingly.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111427&sha=8e19cadaa417bb9239a937fd28b5c1dca48beee0&name_0=PR&name_1=Build%20%28arm_tidy%29

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

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3846f2ee6 with master 86a433ccd (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
Binary Master PR Δ
programs/clickhouse-stripped 710.09 MiB 706.99 MiB -3.10 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

755 object files changed (-184.54 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationVariant.cpp.o 377.57 KiB 353.00 KiB -24.57 KiB (-6.51%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationDynamicHelpers.cpp.o 165.01 KiB 181.84 KiB +16.83 KiB (+10.20%)
src/CMakeFiles/dbms.dir/DataTypes/Serializations/SerializationObjectCombinedPath.cpp.o 113.18 KiB 97.09 KiB -16.09 KiB (-14.22%)

738 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

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

Job report

Avogar and others added 2 commits August 6, 2026 18:02
…:ClickHouse/ClickHouse into experiment-icolumn-ref-deserialize
rows_offset (the number of leading rows to skip while deserializing a
range) is provably always 0 for every caller, so drop it from
deserializeBinaryBulkWithMultipleStreams, deserializeBinaryBulk and all
their helpers. Removing it deletes the read-side skip machinery:

- the skip loops / istr.ignore(size * rows_offset) seeks,
- the Map bucketed reorder-with-skipped-rows path (which also removes
  the latent substreams-cache over-count on bucketed Map),
- the Object shared-data granules_offsets / last_incomplete_granule_offset
  cursors (StructureGranule.offset/.limit continuous-read state is kept),
- the SerializationArrayOffsets helper (rows_offset-only),
- assorted dead offset arithmetic (e.g. Sparse max_rows_to_read).

Load-bearing continuous-read and substreams-cache tail cursors
(num_read_rows, discriminators_offset, num_pending_rows, ...) are
preserved.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Avogar Avogar changed the title Refactor columns deserialization to avoid all assumeMutable calls and to simplify the substreams cache. Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset Aug 7, 2026
Avogar and others added 2 commits August 10, 2026 18:52
The CI performance comparison measures only 10 queries per test file,
chosen at random each run (ci/jobs/performance_tests.py passes
--max-queries 10 for every non-benchmark test, and perf.py does an
unseeded random.sample). The combined subcolumn_deserialization.xml had
20 queries, so only a rotating random half was ever measured per run.

Split it into two files of exactly 10 queries each so every query is
measured on every run:
- subcolumn_deserialization_tuple_map.xml: Tuple + Map (basic + bucketed)
- subcolumn_deserialization_variant_json_string_array.xml: Variant + JSON + String + Array

Also drop the stale "non-zero rows_offset" phrasing from the header
comment (rows_offset was removed; the skip index skips whole granules).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Avogar and others added 2 commits August 20, 2026 14:50
deserializeBinaryBulkWithSizeStream threw LOGICAL_ERROR when the data
stream getter returned null, but that is a valid case: a column missing
from the part (e.g. a Nested member dropped and re-added, read from a
Compact part) has no substreams, so the reader must leave the column
empty and fill defaults instead. Match the behavior of the size-stream
String serialization on master. Fixes
04845_type_evolution_matrix_nested_multi.

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

clickhouse-gh Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 1c3bbaee-783e-454a-bbfa-17dfb23711b4
  • MIRAI run: 1ac80c55-f92b-4247-9e65-419a3868bb20
  • PR check IDs:
    • clickbench_384064_1787699457
    • clickbench_384076_1787699457
    • clickbench_384082_1787699458
    • tpch_adapted_1_official_384091_1787699457
    • tpch_adapted_1_official_384107_1787699458
    • tpch_adapted_1_official_384135_1787699457

@Avogar
Avogar added this pull request to the merge queue Aug 26, 2026
@Avogar

Avogar commented Aug 26, 2026

Copy link
Copy Markdown
Member Author

Added 26.8 backport label to avoid performance regression after #109105

Merged via the queue into master with commit c4cdf57 Aug 26, 2026
179 of 181 checks passed
@Avogar
Avogar deleted the experiment-icolumn-ref-deserialize branch August 26, 2026 12:17
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 26, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Aug 26, 2026
Cherry pick #111427 to 26.8: Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset
robot-clickhouse added a commit that referenced this pull request Aug 26, 2026
…ll assumeMutable calls, simplify the substreams cache, and remove rows_offset
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 26, 2026
Avogar added a commit that referenced this pull request Sep 1, 2026
Backport #111427 to 26.8: Refactor columns deserialization to avoid all assumeMutable calls, simplify the substreams cache, and remove rows_offset
hah23255 pushed a commit to hah23255/ClickHouse that referenced this pull request Sep 1, 2026
…nt from a part

`IDataType::createColumn(const ISerialization &)` builds the read column from the type and
then hands it to the serialization. With `allow_nullable_tuple_in_extracted_subcolumns = 1`
an extracted whole-`Tuple` subcolumn of a `Dynamic` or `Variant` column is typed
`Nullable(Tuple(...))`, so that column is a `ColumnNullable`.
`SerializationWrapper::wrapColumnForDeserialization` forwards it unchanged to the nested
serialization, so `SerializationTuple::wrapColumnForDeserialization` receives a
`ColumnNullable` and its `assert_cast<const ColumnTuple &>` fires: `Bad cast from type
DB::ColumnNullable to DB::ColumnTuple`.

That forward is wrong for these two wrappers because they own that `Nullable` level
themselves. `SerializationVariantElement::deserializeBinaryBulkWithMultipleStreams` peels
exactly that level off the result column, fills its null map from the discriminators, and
only then recurses into `nested_serialization`. The wrap now mirrors that unwrap.

`SerializationDynamicElement` also needs an early return for a null map subcolumn: there
the result column is a `ColumnUInt8` read through `SerializationVariantElementNullMap`,
`nested_serialization` is not used at all, and the blanket forward produced a second
signature, `Bad cast from type DB::ColumnVector<char8_t> to DB::ColumnTuple`.

`LowCardinality(Nullable(T))` results stay on the forwarding path on purpose:
`isColumnNullable` is false for them and the unwrap side keeps them whole for the same
reason. `LowCardinality` cannot hold a `Tuple`, so no non-identity nested serialization can
appear under one.

Introduced by ClickHouse#111427, commit 8fa5b9b "Deserialize const subcolumns via
ISerialization::wrapColumnForDeserialization", which replaced type-driven column
construction with serialization-driven construction. Before it the tuple rebuild lived in
`DataTypeTuple::createColumn(const ISerialization &)`, a virtual reached only when the type
itself was a `Tuple`, so a `Nullable(Tuple(...))` never entered it. Measured: master
snapshot 82cfa6a returns the correct values, 19a501b aborts.

Rejected alternatives: relaxing the `assert_cast` in `SerializationTuple`, since that class
did not add the `Nullable` and tolerating it there would mask every genuine type-against-
serialization mismatch for every caller; making `SerializationWrapper`'s default
non-forwarding, since forwarding is required by `SerializationNamed`, which is what
`SerializationTuple` calls for each element; restoring a type-side
`DataTypeNullable::createColumn(const ISerialization &)` virtual, which reintroduces the
type-side dispatch ClickHouse#111427 removed.

Reachable only with `allow_nullable_tuple_in_extracted_subcolumns = 1`, which is read from
the global context and can only be set in a startup profile. The AST fuzzer jobs set it for
every run, which is where this surfaced.

Co-Authored-By: Claude Opus 5 <[email protected]>
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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-not-for-changelog This PR should not be mentioned in the changelog 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.

6 participants