Skip to content

Reject non-default serialization kinds in data received over the native protocol - #130895

Merged
vdimir merged 5 commits into
masterfrom
vdimir/fix-async-insert-sparse-type-confusion
Nov 13, 2026
Merged

vdimir merged 5 commits into
masterfrom
vdimir/fix-async-insert-sparse-type-confusion

Conversation

@vdimir

@vdimir vdimir commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

In the Native protocol the sender picks each column's serialization kind (Default, Sparse, Replicated, Detached). The server rebuilt a ColumnSparse/ColumnReplicated from the peer-chosen kind while the block kept the declared dense type, so a consumer that assert_casts to the dense column hit a type confusion: a logical error (abort in debug) and, in release, an unchecked static_cast — an out-of-bounds read, heap disclosure, or an implausible allocation. It is reachable from an asynchronous insert, an external table, input, or a client scalar, and from a Tuple with a Replicated element.

Data received from any peer now accepts only the default serialization kind, and Replicated is rejected as a tuple element in every Native reader — the same treatment PR #117699 gave to Detached. The result/interserver direction is unchanged, so sparse/replicated stays on the wire there; external tables are materialized before being sent to a shard.

Related: #117699

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fixed a type confusion (possible crash or out-of-bounds read) triggered by a client sending a column with a Sparse or Replicated serialization kind, or a Tuple with a Replicated element, in data over the native protocol.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.2204-master (included in 26.11 and later)
  • Backported to: 26.10.6.19, 26.9.32.9, 26.8.40.9, 26.3.67.25

@mintlify

mintlify Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 12, 2026, 6:45 PM

…ve protocol

In the Native protocol the sender chooses each column's serialization kind
(Default, Sparse, Replicated, Detached). The server rebuilt a `ColumnSparse` or
`ColumnReplicated` from a peer-chosen kind while the block kept the declared
dense type, so a downstream consumer that `assert_cast`s the column to the dense
representation hit a type confusion: a debug abort, and in release an unchecked
`static_cast` (out-of-bounds read, heap disclosure, or an implausible
allocation). The asynchronous-insert flush was the original vector, but an
external table or a client scalar wrapping `Sparse`/`Replicated`, and a `Tuple`
carrying a `Replicated` element, reach the same dense consumers.

No legitimate sender needs a non-default kind in data sent to a server: inserts
and forwarded external tables and scalars are materialized before sending, and
the storage representation is re-decided at write time.

- `TCPHandler::initBlockInput` and `TCPHandler::skipDataPacket` accept only the
  default kind in every block a peer sends (`INSERT` and `input` data, external
  tables, scalars), for every peer: `query_kind` is client-declared and an
  initiator forwards client data to shards unchanged.
- `SerializationInfoTuple` rejects `Replicated` as a tuple element in every
  Native reader, as it already did for `Detached`. `Replicated` wraps a whole
  column and is unwrapped only at the top level, so a nested one is a layout no
  writer builds; this also protects a client reading results from a malicious
  server.
- `RemoteQueryExecutor::sendExternalTables` materializes each external table
  before sending it to a shard, because a materialized CTE keeps its `Sparse`
  columns and would otherwise be rejected by the gated shard reader.
- `AsynchronousInsertQueue::pushQueryWithBlock` keeps a defense-in-depth check
  that a queued block carries no wrapped column.
- `SerializationInfo::checkKindStack` validates the stack shape first, then the
  allowed kinds from the outermost one, so a disallowed outer kind is reported
  even when an inner kind is also out of place.

Result and interserver traffic keeps sparse/replicated on the wire: the client's
result reader `Connection::initBlockInput` is unchanged.

Tests: `05617` covers the gate for insert, external table and scalar data;
`05618` covers a materialized CTE over a sparse column sent to a shard;
`04616` and `05473` now reach the `SerializationReplicated` and
`SerializationSparse` validators through a result block served by a fake server,
the only direction a client can still reach them. The `Native` format spec is
updated.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@vdimir
vdimir force-pushed the vdimir/fix-async-insert-sparse-type-confusion branch from b24aa96 to 1fa96f5 Compare November 11, 2026 17:15
@clickhouse-gh

clickhouse-gh Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [994a883]

Summary: ✅


AI Review

Summary

The PR rejects non-default serialization kinds in incoming Native protocol data, rejects Replicated tuple elements, and materializes forwarded external tables. The security fix needs a safe transition for older initiators: upgrading a shard first breaks sparse materialized CTE forwarding.

Findings

⚠️ Majors

  • src/Server/TCPHandler.cpp:3208: Rolling upgrades reject legitimate external-table data. With the experimental enable_materialized_cte = 1, the base revision's RemoteQueryExecutor::sendExternalTables forwards Sparse CTE columns unchanged. An upgraded shard now rejects them with INCORRECT_DATA. The new sender-side MaterializingTransform only protects upgraded initiators. Normalize valid legacy layouts before header conversion and dense consumers, or provide a staged deployment of sender normalization before enforcing rejection.
Tests
  • ⚠️ Run the workload from 05618_materialized_cte_sparse_columns_to_shards.sql with the base-revision initiator and the upgraded shard. Its current same-version coverage does not prove rolling-upgrade compatibility. This finding is based on tracing both revisions; no local two-binary reproduction was run.
Final Verdict

Status: ⚠️ Request changes. Provide a safe transition for old initiators sending sparse CTE external tables and verify the mixed-version workload.

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Nov 11, 2026
@Avogar Avogar self-assigned this Nov 11, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
vdimir and others added 4 commits November 12, 2026 16:43
…rmat readers

`NativeInputFormat` and `NativeSchemaReader` create a `NativeReader` with
revision 0, whose layout has no serialization kinds, so the format cannot
receive a `Sparse` or `Replicated` column and the kind set is not consulted
there. Passing `{Default}` explicitly makes the format fail closed if a
revision is ever passed to these readers, as the output format already does
with `client_protocol_version`.

The two reader constructions in `NativeInputFormat` now go through `makeReader`.
In `TCPHandler` the kind set is written inline instead of a named constant.

No behavior change.

Review comment: #130895 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…umns

An async `INSERT` without data queues `squashing.getHeader()->cloneWithoutColumns()`
from `TCPHandler::processAsyncInsertQuery`, a block whose elements have no column.
The check of wrapped columns in `AsynchronousInsertQueue::pushQueryWithBlock`
dereferenced every element, so the server got a segmentation fault on such an
insert. The check now skips elements without a column; the flush already skips
blocks without rows.

Found by `03561_async_insert_crash` in Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130895&sha=1fa96f589c48e405cffad930dcb5836aa29381bd&name_0=PR&name_1=Fast%20test
#130895

Co-Authored-By: Claude Fable 5.2 <[email protected]>
- `04616_replicated_serialization_oob_index_native_protocol` goes back to its
  original structure: every block function takes the packet type and returns
  the bytes instead of sending them, and every scenario passes them to the fake
  server. The two new scenarios (a `Replicated` tuple element, a `Replicated`
  column on insert) are kept.
- The fake server that answers `clickhouse-client` with a crafted result block
  moves to `helpers/fake_native_server.py`, shared by `04616` and
  `05473_sparse_truncated_values_native_protocol`.
- `05617_async_insert_native_serialization_kind_gate` loses the sparse `String`
  case: the kind is rejected before any data is read, so the column type does
  not matter and the sparse `UInt64` case covers it.

No scenario of the existing tests is removed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…lify a test comment

- In `format.mdx` the sentence about `REPLICATED` and `DETACHED` in a `Tuple`
  element stack moves to its own line at the end of its paragraph, and the new
  "Kinds in blocks sent to a server" paragraph is written one sentence per line.
  The paragraphs render the same; the diff against master is easier to read.
- The header comment of `05617_async_insert_native_serialization_kind_gate` is
  reworded in shorter sentences, with the same content.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Server/TCPHandler.cpp
getNativeWireFormatSettings(state.query_context),
/*block_missing_values_=*/ nullptr,
/*type_cache_=*/ nullptr,
ISerialization::KindSet{ISerialization::Kind::DEFAULT});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve sparse CTE forwarding during rolling upgrades

With enable_materialized_cte = 1, an initiator running the pre-PR code still sends Sparse columns from a materialized CTE as external-table data: RemoteQueryExecutor::sendExternalTables on the base revision has no materialization step, and Connection::sendData preserves the serialization kind. Once its destination shard is upgraded, this unconditional gate rejects that legitimate block with INCORRECT_DATA (Unexpected serialization kind Sparse in the received data). The query added in 05618_materialized_cte_sparse_columns_to_shards.sql exercises this workload, but only with both endpoints upgraded.

Adding MaterializingTransform to the sender in the same PR fixes new-to-new traffic; it leaves old initiators unable to query upgraded shards. Please provide a safe transition, for example by normalizing valid legacy Sparse layouts before header conversion or any dense consumer on receipt, or by staging sender normalization everywhere before enabling this rejection. Add coverage with the base-revision initiator and an upgraded shard.

@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 994a88374 with master be68a48d1 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.62 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 6.0 s 12.4 s +8.9 s (+249%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.1 s +5.1 s (+249%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×0.95 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -273.7 s (-6%) in total before that adjustment.

Job report

vdimir added a commit that referenced this pull request Nov 18, 2026
The change is taken as in the original (1a44640, #130895); only the following is adapted.

- `src/Formats/NativeReader.h`, `src/Formats/NativeReader.cpp`: the new `allowed_kinds_` parameter and the
  `allowed_kinds(allowed_kinds_)` initializer go after `block_missing_values_`. The master-only `type_cache_`
  parameter and initializer are not added: `NativeReaderTypeCache` (#129831) is not on the branch, and the
  change does not use it. The branch keeps its own `format_settings_ = std::nullopt` default.
- `src/Processors/Formats/Impl/NativeFormat.cpp` (`makeReader`) and `src/Server/TCPHandler.cpp`
  (`initBlockInput`): the `/*type_cache_=*/ nullptr,` argument is dropped, because the constructor on the
  branch has no such parameter. These two files merged without a conflict, but would not compile as merged.
- `tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python` and
  `.reference`: the huge-element-count scenario (`replicatedBlockWithHugeElementCount`,
  `hugeElementCountScenario`, its call in `main`, its reference line) is left out. It comes from #129932,
  which is not on the branch: the test there never had the scenario or the `expectException` helper, and
  `SerializationReplicated` has no 'Suspiciously many elements' check. The new
  `replicatedTupleElementScenario` and `replicatedOnInsertScenario` are kept, with their reference lines.
- `tests/queries/0_stateless/05473_sparse_truncated_values_native_protocol.python`, `.reference`, `.sh`:
  left out. The original only edits this test, and it comes from #128363, which is not on the branch
  (modify/delete conflict).
- `docs/reference/interfaces/specs/NativeFormat.mdx`: git applied the hunks of
  `docs/resources/develop-contribute/native-protocol/format.mdx` here, where the same document lives on
  the branch. The added and removed lines are the same as in the original.

Everything else merged without conflicts and has the same changed lines as the original.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
vdimir added a commit that referenced this pull request Nov 18, 2026
The change is taken as in the original (1a44640, #130895); only the following is adapted.

- `src/Formats/NativeReader.h`, `src/Formats/NativeReader.cpp`: the new `allowed_kinds_` parameter and the
  `allowed_kinds(allowed_kinds_)` initializer go after `block_missing_values_`. The master-only `type_cache_`
  parameter and initializer are not added: `NativeReaderTypeCache` (#129831) is not on the branch, and the
  change does not use it. The branch keeps its own `format_settings_ = std::nullopt` default.
- `src/Processors/Formats/Impl/NativeFormat.cpp` (`makeReader`) and `src/Server/TCPHandler.cpp`
  (`initBlockInput`): the `/*type_cache_=*/ nullptr,` argument is dropped, because the constructor on the
  branch has no such parameter. These two files merged without a conflict, but would not compile as merged.
- `tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python` and
  `.reference`: the huge-element-count scenario (`replicatedBlockWithHugeElementCount`,
  `hugeElementCountScenario`, its call in `main`, its reference line) is left out. It comes from #129932,
  which is not on the branch: the test there never had the scenario or the `expectException` helper, and
  `SerializationReplicated` has no 'Suspiciously many elements' check. The new
  `replicatedTupleElementScenario` and `replicatedOnInsertScenario` are kept, with their reference lines.
- `tests/queries/0_stateless/05473_sparse_truncated_values_native_protocol.python`, `.reference`, `.sh`:
  left out. The original only edits this test, and it comes from #128363, which is not on the branch
  (modify/delete conflict).

Everything else merged without conflicts and has the same changed lines as the original.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
vdimir added a commit that referenced this pull request Nov 18, 2026
The change is taken as in the original (1a44640, #130895); only the following is adapted.

- `src/Formats/NativeReader.h`, `src/Formats/NativeReader.cpp`: the new `allowed_kinds_` parameter and the
  `allowed_kinds(allowed_kinds_)` initializer go after `block_missing_values_`. The master-only `type_cache_`
  parameter and initializer are not added: `NativeReaderTypeCache` (#129831) is not on the branch, and the
  change does not use it. The branch keeps its own `format_settings_ = std::nullopt` default.
- `src/Processors/Formats/Impl/NativeFormat.cpp` (`makeReader`) and `src/Server/TCPHandler.cpp`
  (`initBlockInput`): the `/*type_cache_=*/ nullptr,` argument is dropped, because the constructor on the
  branch has no such parameter. These two files merged without a conflict, but would not compile as merged.
- `tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python` and
  `.reference`: the huge-element-count scenario (`replicatedBlockWithHugeElementCount`,
  `hugeElementCountScenario`, its call in `main`, its reference line) is left out. It comes from #129932,
  which is not on the branch: the test there never had the scenario or the `expectException` helper, and
  `SerializationReplicated` has no 'Suspiciously many elements' check. The new
  `replicatedTupleElementScenario` and `replicatedOnInsertScenario` are kept, with their reference lines.
- `tests/queries/0_stateless/05473_sparse_truncated_values_native_protocol.python`, `.reference`, `.sh`:
  left out. The original only edits this test, and it comes from #128363, which is not on the branch
  (modify/delete conflict).
- `docs/reference/interfaces/specs/NativeFormat.mdx`: git applied the hunks of
  `docs/resources/develop-contribute/native-protocol/format.mdx` here, where the same document lives on
  the branch. The added and removed lines are the same as in the original.

Everything else merged without conflicts and has the same changed lines as the original.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
vdimir added a commit that referenced this pull request Nov 18, 2026
The change is taken as in the original (1a44640, #130895), with the adaptations below.

Adapted:
- `src/Formats/NativeReader.h`, `src/Formats/NativeReader.cpp`: the new `allowed_kinds_` parameter and the
  `allowed_kinds(allowed_kinds_)` initializer go after `block_missing_values_`, without the master-only
  `type_cache_` (`NativeReaderTypeCache`, #129831). The branch keeps its own
  `format_settings_ = std::nullopt` default.
- `src/Processors/Formats/Impl/NativeFormat.cpp` (`makeReader`): the `/*type_cache_=*/ nullptr,` argument is
  dropped. The file merged without a conflict, but would not compile as merged.
- `src/Server/TCPHandler.cpp`: the original only adds the `ISerialization::KindSet{ISerialization::Kind::DEFAULT}`
  argument; `getNativeWireFormatSettings` (#123649) is on its context lines and is not on the branch.
  `skipDataPacket` passes no format settings here, so an explicit `std::nullopt` stands in that position.
  `initBlockInput` keeps `getFormatSettings(state.query_context)`, with an explicit `nullptr` for
  `block_missing_values_` and without `type_cache_`. Both comments of the original are kept.
- `src/Interpreters/AsynchronousInsertQueue.cpp`: `IColumn::convertToFullIfWrapped` (#107773) is not on the
  branch, and `convertToFullIfNeeded` also strips `LowCardinality`. The check uses a file-local
  `hasWrappedColumn` instead: a `ColumnBLOB`, `ColumnConst`, `ColumnReplicated` or `ColumnSparse` at any
  nesting depth, `LowCardinality` left alone, nothing converted. The exception and its message are as in the
  original. The only producers of `pushQueryWithBlock` on the branch are the two calls in
  `TCPHandler::processAsyncInsertQuery`: a header without columns, and the squashed blocks that
  `initBlockInput` reads, which now accepts only the default kind.

Left out:
- `tests/queries/0_stateless/04616_replicated_serialization_oob_index_native_protocol.python` and `.reference`:
  the scenarios the branch does not have: invalid index type size, index row count mismatch, sparse over
  replicated (#114186) and huge element count (#129932). The rewrite of the two existing scenarios and the new
  `replicatedTupleElementScenario` and `replicatedOnInsertScenario` are kept, with their reference lines.
- `tests/queries/0_stateless/05473_sparse_truncated_values_native_protocol.python`, `.reference`, `.sh`: the
  original only edits this test, and it comes from #128363, which is not on the branch (modify/delete
  conflict).
- `docs/resources/develop-contribute/native-protocol/format.mdx`: the branch has no English specification of
  the `Native` format, so the hunks have nowhere to go (modify/delete conflict).

`tests/queries/0_stateless/helpers/fake_native_server.py` is as in the original here. It does not work with
the client of this branch, which sends a `Ping` before each query; the next commit adapts it.

Everything else merged without conflicts and has the same changed lines as the original.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
vdimir added a commit that referenced this pull request Nov 18, 2026
Cherry pick #130895 to 26.10: Reject non-default serialization kinds in data received over the native protocol
vdimir added a commit that referenced this pull request Nov 18, 2026
Cherry pick #130895 to 26.9: Reject non-default serialization kinds in data received over the native protocol
vdimir added a commit that referenced this pull request Nov 18, 2026
Cherry pick #130895 to 26.8: Reject non-default serialization kinds in data received over the native protocol
vdimir added a commit that referenced this pull request Nov 18, 2026
Cherry pick #130895 to 26.3: Reject non-default serialization kinds in data received over the native protocol
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
robot-clickhouse added a commit that referenced this pull request Nov 18, 2026
robot-clickhouse added a commit that referenced this pull request Nov 18, 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 18, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #130895 to 26.9: Reject non-default serialization kinds in data received over the native protocol
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #130895 to 26.10: Reject non-default serialization kinds in data received over the native protocol
clickhouse-gh Bot added a commit that referenced this pull request Nov 18, 2026
Backport #130895 to 26.8: Reject non-default serialization kinds in data received over the native protocol
PedroTadim added a commit that referenced this pull request Nov 19, 2026
Backport #130895 to 26.3: Reject non-default serialization kinds in data received over the native protocol

This branch was successfully deployed

1 active deployment
staging - docs — 994a8837 Deployed Nov 12, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

5 participants