Repository navigation
Add size-stream String serialization to the Native protocol - #110320
Conversation
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.
|
Workflow [PR], commit [acbdd04] Summary: ❌
AI ReviewSummaryThis PR switches PR Metadata
The native TCP protocol now sends Findings❌ Blockers
Final Verdict❌ Changes requested. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 298/301 (99.00%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (8 of 43)
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_officialFlagged queries (2 of 22)
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
|
…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.
|
About the What was new from this PR: when the client reads the broken stream with the size-stream layout, 8 garbage bytes become a Fixed in 96b6eb3: |
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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`.
…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`.
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
left a comment
There was a problem hiding this comment.
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:
- I want to keep this PR only about change in Native protocol
- I am not sure these settings are any useful actually
- 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]>
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
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 units2967 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. |
…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]>
…-string-size-stream
c804a78
…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]>
Closes: #110126
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
The native protocol now sends
Stringcolumns as a separate stream of cumulative byte offsets (the same layoutArrayuses 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 readStringcolumns 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 theNativeandBuffersformats through the new settingsoutput_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
Stringcolumn is written asnum_rowscumulativeUInt64little-endian offsets (offsetiis the end of valueiin the data blob; size of valueiisoffset[i] - offset[i-1]) followed by all the data, starting at protocol revisionDBMS_MIN_REVISION_WITH_STRING_WITH_SIZE_STREAM_SERIALIZATION(54489). This is the same wire shapeArrayuses for its offsets, so the reader preallocates the exact size and copies the data in one go. The layout applies toStringnested insideArray/Nullable/Map/Tuple/Variant/Dynamic/JSON; the dictionary of aLowCardinalitycolumn keeps the per-value layout (it is always written with the default nested serialization). On disk the MergeTreeWITH_SIZE_STREAMformat is unchanged (per-row sizes, position-independent).The
NativeandBuffersformats keep the portable per-value layout by default. Setoutput_format_native_write_string_with_size_stream = 1to write the offsets layout andinput_format_native_read_string_with_size_stream = 1to read it; both peers must agree.Measured with a Go client (chconn) against this branch,
SELECT s FROM bench_stringswith 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 theStringdecode loop. Details and client-side decode benchmarks are in the linked issue.Notes:
WITH_SIZE_STREAMversion builds, selecting it bySerializationInfoSettings::enableAllSupportedSerializations; over the wire the offsets are written/read as-is (SerializationNumber<Offset>), on disk the same tree writes position-independent sizes.NativeFormat.mdandBuffers.mdare updated in the same change (revision gate table,Stringtype section with both layouts,LowCardinalityexception, the new format settings).Workflow [PR]
Sync PR [sync-upstream/pr/110320]