Skip to content

Prepare each column type once per streaming exchange sender and receiver - #129831

Merged
davenger merged 7 commits into
masterfrom
exchange-native-reader-type-cache
Nov 10, 2026
Merged

davenger merged 7 commits into
masterfrom
exchange-native-reader-type-cache

Conversation

@davenger

@davenger davenger commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

A streaming exchange of the distributed query plan makes a new NativeWriter and a new NativeReader for each packet. So for each column of each packet, the reader parsed the type name with DataTypeFactory::get, and the writer made the type name and the serialization again. For AggregateFunction columns this also makes the aggregate function or its state type each time.

Now each receiver (StreamingExchangeDeserializingTransform, and StreamingExchangeSource when it gives rows) keeps a map from the type name to the parsed type and passes it to the reader. Each sender (StreamingExchangeSerializingTransform) keeps a map from the column type to the type name and the serialization for each kind of column, and passes it to the writer. The bytes on the wire do not change.

Changelog category (leave one):

  • Performance Improvement

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

The senders and the receivers of the streaming exchanges of a distributed query plan prepare each column type once, not once per packet.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1880-master (included in 26.11 and later)

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5c5534f]

Summary: ✅


AI Review

Summary

The PR caches parsed column types per streaming-exchange receiver and type names and serializations per sender, preserving the Native wire format. Review of head 5c5534f81116111273b1f3da14308e5b51163652 found no new or unresolved findings. The layout cache is now bounded, and the author's independent reader measurements and writer measurements address the prior performance-evidence concerns. The remaining bot-authored thread was resolved.

Missing context / blind spots
  • ⚠️ Tests were inspected but not run locally because this checkout has no compiled build or unit-test binary. CI execution of the added cache and transport tests would provide runtime confirmation.
Final Verdict

Status: ✅ Approve. No outstanding review findings.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 6, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Nov 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5c5534f81 with master 0710b90bd (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.

Object file sizes

35 object files changed (+58.49 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Formats/NativeWriter.cpp.o 91.94 KiB 119.65 KiB +27.71 KiB (+30.14%)

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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.89, programs/clickhouse-keeper ×1.10 (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&) 8.1 s 16.6 s +9.4 s (+132%)
Compile time of recompiled translation units

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

Job report

@davenger

davenger commented Nov 7, 2026

Copy link
Copy Markdown
Member Author

A repro on one server with the stateless-worker config. The readers aggregate partially and send the states to one merge task (Aggregating (partial) -> GatherExchange -> MergingAggregated). Forced two-level aggregation makes each of the 50 readers send 257 packets, so the merge task receives 12,850 packets of 33 columns.

CREATE TABLE pixels (x UInt32, y UInt32, date Date) ENGINE = MergeTree ORDER BY (x, y);
INSERT INTO pixels SELECT rand(1) % 1280000, rand(2) % 800000, toDate('2026-03-01') + rand(3) % 30 FROM numbers(20000000);
OPTIMIZE TABLE pixels FINAL;

SELECT
    date AS dt,
    toUInt16(x % 100) AS k,
    toUInt16(countIf(date = toDate('2026-03-01') + 0)) AS d0,
    toUInt16(countIf(date = toDate('2026-03-01') + 1)) AS d1,
    -- ... d2 to d28 in the same way ...
    toUInt16(countIf(date = toDate('2026-03-01') + 29)) AS d29
FROM pixels
GROUP BY dt, k
SETTINGS make_distributed_plan = 1, enable_cascades_optimizer = 0, max_rows_to_group_by = 0,
    distributed_plan_default_reader_bucket_count = 50, max_threads = 8,
    group_by_two_level_threshold = 1, group_by_two_level_threshold_bytes = 1, enable_adaptive_aggregator = 0;

The metrics are from system.query_log, for the merge task (query_id LIKE '%::main') and for all tasks of the query. Both columns use the same binary: for "without the fix", a temporary change passed no map to the reader. The values are the mean of 6 runs.

Without the fix With the fix
Merge task: CPU time (OSCPUVirtualTimeMicroseconds) 8.6 s 4.4 s
Merge task: StreamingExchangeDeserializeMicroseconds 8.3 s 4.2 s
All tasks: CPU time 15.9 s 11.6 s

In the CPU profile of the merge task, the type parse (DataTypeFactory::getImpl) goes from 2,226 of 5,153 samples to 0 of 2,606.

@davenger davenger changed the title Parse each column type once per streaming exchange receiver Prepare each column type once per streaming exchange sender and receiver Nov 7, 2026
Comment thread src/Formats/NativeWriter.cpp Resolved
davenger and others added 3 commits November 7, 2026 18:29
…ause `LOGICAL_ERROR` aborts in sanitizer builds

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Formats/NativeWriter.cpp Resolved
@CheSema CheSema self-assigned this Nov 9, 2026
@davenger
davenger enabled auto-merge November 10, 2026 16:27
@davenger
davenger added this pull request to the merge queue Nov 10, 2026
Merged via the queue into master with commit da9125b Nov 10, 2026
189 checks passed
@davenger
davenger deleted the exchange-native-reader-type-cache branch November 10, 2026 17:42
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
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]>
@clickhouse-gh clickhouse-gh Bot added comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... and removed comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed-query-exchange Distributed Query Execution with Exchange operators: cloud-native query distribution using stream... pr-performance Pull request with some performance improvements 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.

3 participants