Skip to content

Add size-stream String serialization to the Native protocol - #110320

Merged
Avogar merged 53 commits into
ClickHouse:masterfrom
vahid-sohrabloo:native-string-size-stream
Aug 19, 2026
Merged

Avogar merged 53 commits into
ClickHouse:masterfrom
vahid-sohrabloo:native-string-size-stream

Conversation

@vahid-sohrabloo

@vahid-sohrabloo vahid-sohrabloo commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #110126

Changelog category (leave one):

  • Performance Improvement

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

The native protocol now sends String columns as a separate stream of cumulative byte offsets (the same layout Array uses for its offsets) followed by the concatenated data, instead of a per-value varint length prefix, once both peers are on protocol revision 54489 or newer. A client can then read String columns with exact buffer preallocation and a single bulk copy, about 4 times faster than the per-value layout. Old clients and servers are unaffected: the layout is negotiated through the protocol revision. The same layout is available in the Native and Buffers formats through the new settings output_format_native_write_string_with_size_stream / input_format_native_read_string_with_size_stream (off by default, so the formats stay portable).

Documentation entry for user-facing changes

Over the native TCP protocol a String column is written as num_rows cumulative UInt64 little-endian offsets (offset i is the end of value i in the data blob; size of value i is offset[i] - offset[i-1]) followed by all the data, starting at protocol revision DBMS_MIN_REVISION_WITH_STRING_WITH_SIZE_STREAM_SERIALIZATION (54489). This is the same wire shape Array uses for its offsets, so the reader preallocates the exact size and copies the data in one go. The layout applies to String nested inside Array / Nullable / Map / Tuple / Variant / Dynamic / JSON; the dictionary of a LowCardinality column keeps the per-value layout (it is always written with the default nested serialization). On disk the MergeTree WITH_SIZE_STREAM format is unchanged (per-row sizes, position-independent).

The Native and Buffers formats keep the portable per-value layout by default. Set output_format_native_write_string_with_size_stream = 1 to write the offsets layout and input_format_native_read_string_with_size_stream = 1 to read it; both peers must agree.

Measured with a Go client (chconn) against this branch, SELECT s FROM bench_strings with 5M rows (avg length 29.5, localhost TCP): 152-158 ms with the per-value layout, 39 ms with the offsets layout, with zero allocations in the String decode loop. Details and client-side decode benchmarks are in the linked issue.

Notes:

  • The offsets layout reuses the serialization tree that MergeTree's WITH_SIZE_STREAM version builds, selecting it by SerializationInfoSettings::enableAllSupportedSerializations; over the wire the offsets are written/read as-is (SerializationNumber<Offset>), on disk the same tree writes position-independent sizes.
  • NativeFormat.md and Buffers.md are updated in the same change (revision gate table, String type section with both layouts, LowCardinality exception, the new format settings).

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

Behind a new protocol revision (`DBMS_MIN_REVISION_WITH_STRING_WITH_SIZE_STREAM_SERIALIZATION`),
`NativeWriter` and `NativeReader` exchange `String` columns as all sizes
(`UInt64`, little-endian) followed by the concatenated data, instead of a
varint length prefix per value. This lets clients decode with exact buffer
preallocation and bulk reads (~4x faster String decode measured in a Go
client). The size-stream serialization is reused from MergeTree
(`MergeTreeStringSerializationVersion::WITH_SIZE_STREAM`) and propagates to
`String` nested in composite types; the `LowCardinality` dictionary keeps the
per-value layout.
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [acbdd04]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-3319) FAIL cidb, issue ISSUE CREATED

AI Review

Summary

This PR switches String columns on the native TCP protocol to the cumulative-offsets layout at revision 54492, threads that through nested types, and updates the protocol/format specs. The performance goal is sound, but the current head has regressed several earlier correctness and compatibility fixes, and it still leaves the public Buffers contract out of sync with the code, so it is not ready to merge.

PR Metadata

Changelog category Performance Improvement matches the actual change. A changelog entry is required, and the current one is user-readable but stale: it still says revision 54489 and still mentions output_format_native_write_string_with_size_stream / input_format_native_read_string_with_size_stream, which are not part of the current implementation. Exact replacement text:

The native TCP protocol now sends String columns as a separate stream of cumulative byte offsets once both peers negotiate protocol revision 54492 or newer. This lets clients preallocate exact buffers and decode String columns much faster while older peers keep the previous per-value layout automatically. FORMAT Native over HTTP uses the same layout when client_protocol_version >= 54492; Buffers keeps the portable per-value layout.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationString.cpp:839-857] The seeked WITH_SIZE_STREAM read path no longer rejects short size streams before subtracting rows_offset. deserializeBinaryBulk can append fewer than rows_offset + limit sizes, but current code still indexes sizes_begin + rows_offset and passes num_read_rows - rows_offset to appendStringSizesToColumnStringOffsets, so a truncated on-disk size stream can underflow back into out-of-bounds reads / huge reserve instead of returning INCORRECT_DATA.
    Suggested fix: restore the num_read_rows < rows_offset guard before the subtraction and keep the focused truncated-stream regression.
  • [src/DataTypes/Serializations/SerializationString.cpp:708-739] The writer still has no explicit empty-slice exit after both stream getters run. For an all-empty nested Array(String) / Map(String, String), limit stays 0 and the data-stream half still computes offsets[offset + limit - 1], so the round-trip only works via the padded-array SIZE_MAX -> -1 fallback instead of intentional logic.
    Suggested fix: return early when limit == 0 after visiting both getters and before the offset arithmetic.
  • [src/Formats/NativeWriter.cpp:102-121, src/DataTypes/DataTypeTuple.cpp:419-435] Older peers can still receive nested REPLICATED kinds they do not understand. Both the < 54482 branch and the revision-0 no-marker branch only materialize a top-level ColumnReplicated before getSerializationInfo(...), while DataTypeTuple::getSerializationInfoImpl still preserves replicated tuple children. A tuple built from lazily replicated inputs can therefore serialize in a way that only current peers can round-trip.
    Suggested fix: fully densify wrapped subcolumns on both paths before deriving serialization info, using the same recursive conversion that BuffersWriter already applies.
  • [src/DataTypes/Serializations/SerializationString.cpp:812-823] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/110320#discussion_r3766950232] The matching empty-slice read path is still relying on padding too. When the network branch sees limit == 0, deserializeBinaryBulk(offsets, ..., 0) appends nothing and offsets stays empty, but the function still returns offsets.back(). That is the same padded-container accident as the writer-side bug, not an explicit 0-byte contract.
    Suggested fix: return {0, 0} when limit == 0 / offsets.empty() before touching back().

⚠️ Majors

  • [src/Processors/Formats/Impl/BuffersFormat.cpp:106] The public Buffers description still promises the same per-column representation and the same Native format settings, but current code keeps Buffers on getDefaultSerialization() (src/Formats/BuffersWriter.cpp:41-45, src/Formats/BuffersReader.cpp:65-70) and the stateless test explicitly asserts that client_protocol_version=54492 changes FORMAT Native but leaves FORMAT Buffers unchanged. That leaves external readers implementing the documented contract with the wrong wire layout.
    Suggested fix: narrow the Buffers doc/source-of-truth to the current per-value contract, or intentionally make Buffers follow the same revision-gated layouts as Native.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.90% +0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 298/301 (99.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jul 13, 2026
Comment thread src/Formats/NativeReader.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

PR 64351 (synced from public 110320) changes only the native-protocol String column layout — switching from per-value length prefixes to a separate offsets stream (revision 54492) — plus docs and tests. It does not touch the query-execution engine (scans, filters, aggregation, joins), and it only affects String result serialization over the wire, which is negligible for these LIMIT-bounded, tiny result sets. Every flagged query — the improvements and the single +5.8% Q28 regression — therefore lands off the path this PR changes, so all are downgraded to inconclusive. The consistent one-directional shift and outsized ×8.5/×2.2 magnitudes point to variance between the 6 new-build runs and the 30 baseline runs rather than a real effect of this change.

clickbench

⚠️ 8 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 13 not_sure 422 338 -19.9% <0.0001 aggregation: This PR only changes native-protocol String wire serialization (offsets layout), not the group-by path Q13 runs; the -19.9% shift is run-to-run variance, not a PR effect.
⚠️ 16 not_sure 734 599 -18.4% <0.0001 aggregation: String wire-serialization changes cannot speed up Q16's group-by execution; the -18.4% delta is off-path and reads as environment variance.
⚠️ 18 not_sure 1244 1055 -15.2% <0.0001 aggregation: The execution engine is untouched by this protocol-serialization PR, so the -15.2% improvement on Q18 is not attributable to the change.
⚠️ 23 not_sure 164 76 ×2.2 faster <0.0001 io: Q23's scan/filter path is untouched, and a 10-row result set can't gain ×2.2 faster from a String wire-format change; treating as variance (source runs were also noisy).
⚠️ 28 not_sure 1051 1112 +5.8% <0.0001 cpu: The +5.8% sits on regexp/aggregation CPU work this PR does not touch (only String wire serialization changed); borderline and likely run-to-run variance.
⚠️ 30 not_sure 279 230 -17.6% <0.0001 aggregation: Off-path for a protocol-serialization PR; the -17.6% on Q30's group-by execution is not something this change can cause.
⚠️ 31 not_sure 408 306 -25.0% <0.0001 aggregation: The -25.0% improvement is on aggregation execution the PR leaves unchanged; reads as environment/run-to-run variance.
⚠️ 33 not_sure 1250 1168 -6.5% <0.0001 aggregation: Q33's execution is untouched by the String serialization change; the -6.5% is off-path and inconclusive.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 2 inconclusive

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 7 not_sure 560 66 ×8.5 faster <0.0001 join_operator: A ×8.5 faster swing on a join-heavy query cannot come from a String wire-serialization change; the execution engine is untouched, so this is environment/era variance.
⚠️ 8 not_sure 166 77 ×2.2 faster <0.0001 join_operator: Same off-path story as Q7: the ×2.2 faster delta lands on join execution this protocol-serialization PR does not touch.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 3b954727-10e3-433c-93b8-3398e95970b4
  • MIRAI run: b19a6ee9-902f-4d86-bb61-a117ac9ac9b8
  • PR check IDs:
    • clickbench_1990057_1787087015
    • clickbench_1990063_1787087015
    • clickbench_1990069_1787087015
    • tpch_adapted_1_official_1990086_1787087015
    • tpch_adapted_1_official_1990097_1787087015
    • tpch_adapted_1_official_1990128_1787087015

…eads

Address review: `NativeInputFormat` and `NativeSchemaReader` now pass
`FormatSettings::client_protocol_version` to `NativeReader` (default `0`, so
nothing changes unless the version is requested explicitly). Native output
produced with `client_protocol_version=54487` can be inserted back at the same
protocol version; a round trip is added to the test. The async-insert flush
re-parses buffered data in a context without `client_protocol_version`, so a
nonzero version needs a synchronous insert.

Fix the `04299_move_assignment_memory_limit` failures: when the stream is
corrupted or desynchronized (for example, a partially written block after an
allocation failure on the server), the sizes read by
`deserializeBinaryBulkWithSizeStream` are garbage and the computed total
reached the allocator sanity check, which is a logical error and aborts debug
and sanitizer builds. Report `INCORRECT_DATA` instead, before the allocation.
Also write the sizes value by value instead of buffering them, so the
serialization itself does not allocate in the middle of writing a block.
@vahid-sohrabloo

Copy link
Copy Markdown
Contributor Author

About the 04299_move_assignment_memory_limit failures (3 shards): the root cause is not the wire format change itself. That test injects allocation faults, and when a fault lands while the server is writing a block, the rollback in TCPHandler::sendData can not undo bytes that were already flushed, so the stream to the client breaks. This can also happen with the per-value layout (I reproduced broken streams locally with an old 25.x client against this branch, where the negotiation uses the per-value layout), and the test swallows such soft errors by design.

What was new from this PR: when the client reads the broken stream with the size-stream layout, 8 garbage bytes become a UInt64 size (in CI it was exactly 2^63), and that reached the allocator sanity check, which throws a logical error — and debug and sanitizer builds abort on logical errors. That abort is what failed the test.

Fixed in 96b6eb3: deserializeBinaryBulkWithSizeStream now reports INCORRECT_DATA before attempting the allocation when the total from the size stream is absurdly large, and serializeStringSizes writes the sizes value by value instead of buffering them, so the serialization itself no longer allocates in the middle of writing a block. I added a corrupted-stream case to 04512_native_string_with_size_stream that pins the INCORRECT_DATA behavior.

The protocol version lives on the `Context`, not in `Settings`, so the
async-insert queue neither keyed batches by it nor restored it before
re-parsing the buffered data: `INSERT ... FORMAT Native` bytes written at
revision 54487 were parsed as revision 0 on the flush, and entries written at
different revisions could be batched together under one queue key.

`InsertQuery` now carries `client_protocol_version`: it participates in the
batching key (both the hash and the comparison) and is restored on the flush
context before parsing. The round-trip test covers `async_insert=1` with
`wait_for_async_insert=1` at both protocol versions, and the corrupted-stream
case goes through the async path as well.
…w signature

Also add a test that entries written at different protocol revisions get
different batching keys (they use revision-dependent data formats and must
never be parsed as one batch), while the same revision still batches.
The previous check ran after `appendStringSizesToColumnStringOffsets` had
already committed the raw sizes into the offsets, so a corrupted multi-row
size stream could bypass it by overflowing the cumulative offsets (for
example, sizes `[0xfffffffffffffff0, 0x20]` wrap to a total of `0x10`), and
the reader accepted an internally inconsistent column with offsets pointing
past the data.

The sizes are now validated in one pass with overflow-free arithmetic before
anything is mutated, and the mutation order is exception-safe: reserve the
offsets, read the data with a rollback on failure, and append the offsets
last, so a throw leaves the column exactly as it was. A two-row wraparound
regression test checks the reader reports `INCORRECT_DATA`.
The spec said `FORMAT Native` input is hardcoded to revision `0`, that
`client_protocol_version` is output-only, and that HTTP round-trips at a
raised revision cannot work. The input side honors the requested protocol
version now (including asynchronous inserts, which key batches by it), so the
`revision-input` and `revision-round-trip` sections and the channel table are
updated to match.
auto info = column.type->getSerializationInfo(*result_column);
auto info = column.type->getSerializationInfo(
*result_column,
SerializationInfoSettings::enableAllSupportedSerializations(

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.

client_protocol_version=54487 now makes NativeWriter pick the size-stream String serialization here, but Buffers still hardcodes getDefaultSerialization() on both sides (src/Formats/BuffersWriter.cpp:39-43, src/Formats/BuffersReader.cpp:65-70). Buffers is documented as using “the same per-column binary representation as Native” and “the same Native format settings” (docs/en/interfaces/formats/Buffers.md:22), so after this change the two formats diverge: SELECT ... FORMAT Buffers with ?client_protocol_version=54487 still emits per-value varints, and a consumer that reuses a Native column decoder at that revision will misdecode it.

Please either make Buffers derive its read/write serialization from the same revision-aware settings as Native, or narrow the Buffers contract/docs so client_protocol_version does not claim to affect it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 0a5eecf, first option. You are right that the two formats diverged — and Buffers was already half revision-aware, because it passes client_protocol_version into NativeWriter::writeData, which selects the V2 Dynamic/JSON serialization since revision 54473. So narrowing the docs would have documented something that was already not true.

Both BuffersWriter and BuffersReader now derive the serialization from the same revision-dependent settings as Native (type->getSerialization(SerializationInfoSettings::enableAllSupportedSerializations(...))). One deliberate difference, now stated in Buffers.md: only type-level serialization versions apply — the Buffers framing has no has_custom_serialization byte, so column-derived kinds such as Sparse are never used. At the default revision the stream is unchanged byte for byte (getSerialization with default settings produces the default serialization tree).

The test now pins the Buffers byte layout at both protocol versions (the raised one shows the size-stream layout, matching what a Native column decoder expects) and round-trips the data through the format.

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.

The current head diverged again after the explicit format-setting rework. NativeOutputFormat still passes settings.client_protocol_version into NativeWriter (src/Processors/Formats/Impl/NativeFormat.cpp:78-80, 600-608), and NativeWriter::getSerializationAndColumn still treats any client_revision >= 54489 as enough to enable the offsets String layout (src/Formats/NativeWriter.cpp:107-109). BuffersWriter, however, now enables that layout only through format_settings.native.write_string_with_size_stream (src/Formats/BuffersWriter.cpp:42-47). So ?client_protocol_version=54489 with the new setting left off once again produces offsets in FORMAT Native but varint lengths in FORMAT Buffers, contrary to the current docs/PR text.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 6f89bf3. The offsets String layout is now an explicit input to NativeWriter/NativeReader instead of being derived from client_revision: the native protocol leaves it unset and follows the negotiated revision, while NativeOutputFormat/NativeInputFormat set it from output_format_native_write_string_with_size_stream / input_format_native_read_string_with_size_stream. So ?client_protocol_version=54489 no longer enables the layout in FORMAT Native — it now matches FORMAT Buffers (setting only), and client_protocol_version still can't leak the layout onto the protocol wire toward an older peer.

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.

This diverged again on the current head. src/Formats/BuffersWriter.cpp:41-45 and src/Formats/BuffersReader.cpp:65-70 still hardcode getDefaultSerialization(), while the new stateless test explicitly asserts that client_protocol_version=54489 changes FORMAT Native but leaves FORMAT Buffers unchanged (tests/queries/0_stateless/04512_native_string_with_size_stream.sh:29-34 vs 50-54). But the public Buffers page still says the opposite at docs/reference/formats/Buffers.mdx:23 ("same per-column binary representation" / "same Native format settings"). So the original doc/contract mismatch is back on the current head.

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.

Current head no longer matches the 0a5eecf8f04 fix. src/Formats/BuffersWriter.cpp:41-45 and src/Formats/BuffersReader.cpp:65-70 are back to getDefaultSerialization(), so Buffers no longer follows Native's revision-gated String encoding. The updated stateless test codifies that behavior too: tests/queries/0_stateless/04512_native_string_with_size_stream.sh:50-54 expects FORMAT Buffers output to stay identical when client_protocol_version=54490 is raised.

But the public Buffers description is still the old one at src/Processors/Formats/Impl/BuffersFormat.cpp:106 (which regenerates docs/reference/formats/Buffers.mdx:23): it still says Buffers uses the same per-column representation and the same Native format settings. So the original contract mismatch is still present on the current head.

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.

src/Processors/Formats/Impl/BuffersFormat.cpp:106 still says Buffers uses the same per-column representation and the same Native format settings. But current code still hardcodes getDefaultSerialization() in src/Formats/BuffersWriter.cpp:41-45 and src/Formats/BuffersReader.cpp:65-70, and the stateless test now explicitly asserts that client_protocol_version=54492 changes FORMAT Native but leaves FORMAT Buffers unchanged at tests/queries/0_stateless/04512_native_string_with_size_stream.sh:50-54. So the doc/source-of-truth is still out of sync with the current contract.

`Buffers` is documented as using the same per-column representation as
`Native` and it already passed `client_protocol_version` to
`NativeWriter::writeData` (which gates the V2 `Dynamic`/`JSON` serialization),
but both sides hardcoded `getDefaultSerialization`, so at revision 54487 the
`String` encoding diverged from `Native`. The writer and the reader now derive
the serialization from the same revision-dependent settings. Only type-level
serialization versions apply: the `Buffers` framing has no per-column
serialization kind, so column-derived kinds such as `Sparse` are never used.
At the default revision the stream is unchanged byte for byte.

The test pins the `Buffers` byte layout at both protocol versions and
round-trips the data through the format.
`client_protocol_version` is copied into `FormatSettings` from the whole query
context, so using it directly in `NativeInputFormat` made every `FORMAT
Native` read in the request revision-sensitive: a revision-0 file read through
`file()`/`s3()`/`url()` inside a request that carries
`?client_protocol_version=54487` would be parsed at that revision and lose
sync.

The input side now uses a dedicated
`FormatSettings::native::input_client_protocol_version` (default `0`), set in
one place — `getInputFormatFromASTInsertQuery` — so it covers the INSERT body
on the synchronous path and the async-insert flush (which builds its input
format through the same function), and nothing else. `NativeSchemaReader` and
`BuffersReader` read the same scoped field, so schema inference and
table-function reads always parse at revision `0`. The test covers reading a
revision-0 file through `file()` inside a request with a raised version.

/// Grow the data first and append the offsets last, so that if anything below throws, the
/// column stays exactly as it was (shrinking a PODArray does not throw).
offsets.reserve(offsets.size() + (num_read_rows - rows_offset));

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.

SerializationNumber<UInt64>::deserializeBinaryBulk is partial-read tolerant here: on a short size stream it can append fewer than rows_offset + limit sizes without throwing. If it stops before rows_offset, num_read_rows - rows_offset wraps, so this hardening path turns a corrupted seeked read into a giant offsets.reserve(...) / out-of-bounds appendStringSizesToColumnStringOffsets(...) path instead of a parse error. Please guard num_read_rows < rows_offset before the subtraction, and add a regression test that truncates the size stream with a non-zero rows_offset.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 8024485. num_read_rows < rows_offset is now reported as INCORRECT_DATA ("Unexpected end of the size stream ... read {} sizes, while at least {} were expected") right after num_read_rows is determined, so it covers both the freshly read stream and the substreams-cache branch — a short read stored in the cache would have hit the same wraparound from another column. The regression test drives SerializationString(WITH_SIZE_STREAM) directly with a single-size stream and rows_offset = 2 (the wire path always passes rows_offset = 0, so only a direct call can reach this) and asserts the error code.

Worth noting: this underflow was already present in the original WITH_SIZE_STREAM disk-read code before this PR — the same subtraction has been there since 25.10 — so this catch fixes a latent bug on the MergeTree read path too, not only the new transport.

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.

The 80244851e9e guard is not on the current head. In src/DataTypes/Serializations/SerializationString.cpp:839-857, the code still computes num_read_rows = size_column->size() - prev_size, then immediately uses num_read_rows - rows_offset and indexes sizes_begin + rows_offset without first checking num_read_rows < rows_offset. A truncated size stream with a seeked read can still underflow exactly as in the original report.

The bulk number deserialization tolerates a short stream and can append fewer
than `rows_offset + limit` sizes without throwing. When it stops before
`rows_offset` (a corrupted seeked read), `num_read_rows - rows_offset` wrapped
around, turning the truncation into a giant `offsets.reserve` and
out-of-bounds size reads instead of a parse error. Report `INCORRECT_DATA`
before the subtraction; the check covers both the freshly read stream and the
substreams-cache branch. The regression test drives the serialization directly
with a single-size stream and `rows_offset = 2`.
Comment thread src/Formats/NativeWriter.cpp Resolved
Comment thread src/Formats/BuffersWriter.cpp Resolved
…rites

The context-wide `client_protocol_version` (a reserved HTTP parameter since
2023) reaches every `NativeWriter` in the request, so a server-side
`INSERT INTO FUNCTION file/s3/url(..., 'Native'|'Buffers')` over HTTP with a
raised version writes at that revision, while table-function reads always
parse at revision `0`. The spec claimed files stay at revision `0` on both
sides; describe the real asymmetry instead (write side raisable, read side
fixed at `0`, so such a file does not round-trip), in `NativeFormat.md` and
`Buffers.md`.
Comment thread src/Formats/NativeWriter.cpp Resolved
The flattened `Dynamic`/`JSON` representation
(`output_format_native_use_flattened_dynamic_and_json_serialization = 1`)
serializes its subtypes with `getDefaultSerialization`, so a flattened
`String` alternative keeps the per-value layout even at revision 54487. Only
the default (non-flattened) `Dynamic`/`JSON` path carries `String` subcolumns
in the size-stream layout. Note this in the spec next to the existing
`LowCardinality`-dictionary carve-out so third-party decoders do not expect
the size-stream layout there.
The flattened `Dynamic`/`JSON` representation
(`output_format_native_use_flattened_dynamic_and_json_serialization = 1`)
serialized its subtypes with `getDefaultSerialization`, so a flattened
`String` alternative stayed on the per-value layout at revision 54487 while
the non-flattened path (and the spec) used the size stream. Third-party
decoders following the spec would lose sync on flattened String data.

`SerializationDynamic` already carries `serialization_info_settings` and uses
it on the non-flattened path; thread it through the flattened subtype
serializations too (write prefix/suffix/data, read prefix/data — the index
columns keep the default serialization). Flattened mode is Native/Buffers
transport only and never persisted, so this changes no on-disk format. Revert
the spec carve-out added for flattened; only the `LowCardinality` dictionary
remains an exception. A flattened `Dynamic` round-trip test at the new
revision covers write/read symmetry.
The previous commit added `client_protocol_version` to every async-insert
batching key, but the version only changes how raw bytes are reparsed on
flush. That happens only for `Parsed` entries in a revision-sensitive format
(`Native`/`Buffers`). `Preprocessed` entries are already-materialized Blocks
(the native TCP path) and are never reparsed, and other parsers (CSV,
`JSONEachRow`, ...) ignore the version — so keying on it there split
otherwise-identical batches for no reason, e.g. two TCP clients on revisions
54486 and 54487, or parsed inserts that merely carried different
`client_protocol_version` values.

Fold the version into the key only for `Parsed` + `Native`/`Buffers`
(case-insensitive: a lowercase `FORMAT native` at a raised revision must still
key on it, otherwise the flush would reparse raised bytes at revision 0). The
key test now covers all four cases.
…stream

# Conflicts:
#	src/Core/ProtocolDefines.h

@Avogar Avogar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the work! I cleaned up the code a bit, hope that's ok. I removed input/output format settings that enable separate string size stream in input/output format, because of 3 points:

  1. I want to keep this PR only about change in Native protocol
  2. I am not sure these settings are any useful actually
  3. I didn't like the interaction of NativeWriter/Reader with these settings and I don't know if we can do better.

So, in future if we are sure these settings are actually useful, we can add them in a separate PR.

…t layout

WithSizeStreamFaithfulRoundTripIsConsistent deserialized the offsets layout
(position_independent_encoding = false) with rows_offset > 0, but that layout is
only ever read as a whole fresh block, so the seeked read tripped a chassert.
Run the seek on the position-independent (per-row sizes) layout, which supports
it, matching the real MergeTree read path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Avogar and others added 2 commits August 13, 2026 18:12
Master took 54489 for `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`
(`391f7499f1a`) and bumped `DBMS_TCP_PROTOCOL_VERSION` to it. This branch had claimed 54489
for the size-stream `String` layout, and because both sides changed `DBMS_TCP_PROTOCOL_VERSION`
to the same value the merge did not conflict, leaving one revision standing for two unrelated
features.

A master-head server then announces 54489 while still writing per-value `String` columns, and
a client from this branch reads them as the offsets layout: the first `String` of every
`ProfileEvents` block (`host_name`, a 12-character container id) is decoded as `UInt64`
offsets, which the monotonicity check reports as

    String offsets stream is not monotonically increasing (at index 0, value 7306590359078908428)

That failed all 6 shards of the performance comparison on both architectures, where the client
from this build talks to the reference master-head server on port 9001:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110320&sha=eba06e69233e23bc748683753c3788a8504d6037&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%203%2F6%29
ClickHouse#110320

Also document master's 54489 in the protocol revision table, which had no row for it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing acbdd040f with master 3436fefff (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 701.97 MiB 698.95 MiB -3.02 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

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

Job report

Avogar and others added 4 commits August 14, 2026 15:28
…e-stream

Master took 54490 for `DBMS_MIN_REVISION_WITH_HTTP_HANDLER_IN_CLIENT_INFO` (`133ec91134e`),
so the size-stream `String` layout moves to 54491 along with `DBMS_TCP_PROTOCOL_VERSION`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`ColumnBLOB.h` no longer uses anything from `Core/ProtocolDefines.h`, and the reflowed
declarations in `NativeReader`/`NativeWriter` changed no signature. With these reverted,
`ColumnBLOB.h` and both headers are untouched by this branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e-stream

Master took 54491 for `DBMS_MIN_REVISION_WITH_QUANTILE_DETERMINISTIC_SKIP_DEGREE`, so the
size-stream `String` layout moves to 54492 along with `DBMS_TCP_PROTOCOL_VERSION`. Third
collision in as many days: the revision this branch claims is only safe at the moment it merges.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@Avogar
Avogar added this pull request to the merge queue Aug 19, 2026
Merged via the queue into ClickHouse:master with commit c804a78 Aug 19, 2026
179 of 181 checks passed
@vahid-sohrabloo
vahid-sohrabloo deleted the native-string-size-stream branch August 19, 2026 14:33
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 22, 2026
…rotocol

Since ClickHouse#110320 the native protocol (revision 54492+) sends a String column as
an offsets stream plus the characters. For a range starting at offset > 0 the
network branch of SerializationString::serializeBinaryBulkWithSizeStream wrote
the column's absolute offsets but the characters from offsets[offset - 1],
while the reader and the protocol spec count the offsets from the first
written row.

SerializationSparse always writes the values column from index 1, and in
Sparse(Nullable(String)) the NULL default row at index 0 can keep a non-empty
nested string (toString(nullIf(i, 0)) keeps '0' under the NULL). So every
offset was too large by that length: the receiver split the characters at
wrong positions and read into the next stream, returning wrong strings,
sometimes followed by UNKNOWN_PACKET_FROM_SERVER, in clickhouse-client and in
remote/cluster/Distributed reads.

Rebase the offsets by offsets[offset - 1] in the writer. A zero base keeps the
existing bulk write, so all other traffic is byte-identical. The fixed stream
is the documented layout, which every 54492+ reader already decodes.

The test pins optimize_read_in_order = 1: with a full sort the column is
materialized before it is sent and the bug does not show. It also pins
serialization_info_version = 'with_types', without which a Nullable column is
never stored sparse.

Closes ClickHouse#126854

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

can be tested Allows running workflows for external contributors manual approve Manual approve required to run CI 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.

Native protocol: send String columns with a size stream

4 participants