Skip to content

Do not deserialize unexpected packets in TCPHandler - #119368

Merged
alexey-milovidov merged 30 commits into
masterfrom
no-deserialize-unexpected-packets
Oct 14, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
no-deserialize-unexpected-packets

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 10, 2026 •

Copy link
Copy Markdown
Member

TCPHandler used to read the whole payload of a packet that cannot appear at the current point of the protocol, and only then throw UNEXPECTED_PACKET_FROM_CLIENT. For a Data or Scalar packet that meant running NativeReader over untrusted bytes: resolving arbitrary type names through DataTypeFactory and deserializing values, including aggregate function states. That is a large amount of code exposed to a peer that has not necessarily authenticated — in interserver mode the cluster secret is only verified while reading the query packet, so a Data packet arriving where a query is expected reaches the deserializer first.

Verified against a server built before this change: a Data packet sent instead of a query gets as far as AggregateFunctionFactory::getImpl.

5. src/AggregateFunctions/AggregateFunctionFactory.cpp:378: DB::AggregateFunctionFactory::getImpl(...)
7. src/DataTypes/DataTypeAggregateFunction.cpp:336: DB::create(...)
10. src/DataTypes/DataTypeFactory.cpp:149: DB::DataTypeFactory::getImpl<false>(String const&) const
11. src/Formats/NativeReader.cpp:203: DB::NativeReader::read()
12. src/Server/TCPHandler.cpp:2907: DB::TCPHandler::processUnexpectedData()
13. src/Server/TCPHandler.cpp:1209: DB::TCPHandler::receivePacketsExpectQuery(...)

Nothing was gained by it, since the connection is closed right after the exception. This rejects such a packet immediately instead, the way the obsolete IgnoredPartUUIDs packet is already rejected.

processUnexpectedData, processUnexpectedQuery, processUnexpectedHello and processUnexpectedTablesStatusRequest are replaced by a single throwUnexpectedPacket, which keeps the existing messages. The skip parsers also duplicated the real readers and drifted from them: processUnexpectedQuery never read the interserver externally granted roles field added in revision 54472, so on any modern connection it desynchronized and then blocked on the rest of the packet instead of reporting the error.

The one place where a data packet of a doomed query is still deserialized is the drain in skipData: a client that keeps streaming data for a query that has already failed. There the block is read only to find where the packet ends, so that the connection survives; that path is post-authentication and no different from an ordinary INSERT. It moves to skipDataPacket, which takes the compression flag from the query state instead of the last_block_in member — the two always held the same value there, because skipData runs only after processQuery has completed, so LastBlockInputParameters is gone.

The new test 05175_unexpected_packet_no_deserialization sends only the packet type and nothing else, so a server that reads the payload waits for the missing bytes until the receive timeout. Against a pre-change build every one of its six scenarios blocks; with this change the server answers at once. The last scenario keeps the drain covered: a client that streams data for an insert that has already failed still gets its exception, and the connection survives to answer a subsequent Ping.

Related: #68800

Changelog category (leave one):

  • Improvement

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

A packet that cannot appear at the current point of the native protocol is now rejected without deserializing its payload. Previously the server deserialized the body of an unexpected Data packet — including arbitrary data types and aggregate function states — only to throw UNEXPECTED_PACKET_FROM_CLIENT and close the connection.


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

Version info

  • Merged into: 26.10.1.2410-master (included in 26.10 and later)
  • Backported to: 26.9.20.12, 26.8.29.7, 26.7.35.2, 26.3.53.5

`TCPHandler` used to read the whole payload of a packet that cannot appear at
the current point of the protocol, and only then throw
`UNEXPECTED_PACKET_FROM_CLIENT`. For a `Data` or `Scalar` packet that meant
running `NativeReader` over untrusted bytes: resolving arbitrary type names
through `DataTypeFactory` and deserializing values, including aggregate
function states. That is a large amount of code exposed to a peer that has not
necessarily authenticated - in interserver mode the cluster secret is only
verified while reading the query packet, so a `Data` packet arriving where a
query is expected reaches the deserializer first. Verified against a server
built before this change: a `Data` packet sent instead of a query gets as far
as `AggregateFunctionFactory::getImpl` from `TCPHandler::processUnexpectedData`.

Nothing was gained by it, since the connection is closed right after the
exception. Reject such a packet immediately instead, the way the obsolete
`IgnoredPartUUIDs` packet is already rejected.

`processUnexpectedData`, `processUnexpectedQuery`, `processUnexpectedHello` and
`processUnexpectedTablesStatusRequest` are replaced by a single
`throwUnexpectedPacket`, which keeps the existing messages. The skip parsers
also duplicated the real readers and drifted from them:
`processUnexpectedQuery` never read the interserver externally granted roles
field added in revision 54472, so on any modern connection it desynchronized
and then blocked on the rest of the packet instead of reporting the error.

The one place where a data packet of a doomed query is still deserialized is
the drain in `skipData`: a client that keeps streaming data for a query that
has already failed. There the block is read only to find where the packet ends,
so that the connection survives; that path is post-authentication and no
different from an ordinary `INSERT`. It moves to `skipDataPacket`, which takes
the compression flag from the query state instead of the `last_block_in`
member - the two always held the same value there, because `skipData` runs only
after `processQuery` has completed, so `LastBlockInputParameters` is gone.
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d94f9b9]

Summary: ✅


AI Review

Summary

PR #119368 rejects unexpected native-protocol packets before deserializing their bodies and closes connections after incomplete packet reads. It preserves connection reuse when a failed INSERT can safely drain its remaining input, prevents an Exception after a detached query's EndOfStream, and documents the protocol behavior. Reviewed head: d94f9b98cf8814d537b803749388b948ee2a0d27. All prior findings are addressed in the current code; no new actionable findings remain. The focused 05175_unexpected_packet_no_deserialization test passes in the current Fast test report. Validation relied on source inspection and CI results; no local server tests were run.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Sep 10, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
@alexey-milovidov alexey-milovidov added the pr-must-backport Pull request should be backported intentionally. Use this label with great care! label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit d94f9b98cf8814d537b803749388b948ee2a0d27 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@Avogar Avogar self-assigned this Sep 11, 2026
`UNEXPECTED_PACKET_FROM_CLIENT` is now thrown without reading the payload of
the packet, which leaves the input positioned in the middle of it. The
post-exception drain in `runImpl` ran anyway and parsed those bytes as a packet
stream of its own, so the deserialization that the rejection avoids happened a
moment later: a leading `13` reaches `receiveQueryPlan` and
`QueryPlan::deserialize`, a `2` or a `7` reaches `NativeReader`. It also blocked
until `receive_timeout` waiting for the rest of a packet the client never sent,
all to preserve a connection that is closed right afterwards for this very
error code. The drain is skipped now.

`processObsoleteIgnoredPartUUIDs` threw `UNSUPPORTED_METHOD`, which does not
close the connection, so an `IgnoredPartUUIDs` packet arriving mid-query left
the connection alive with a desynchronized stream. It throws
`UNEXPECTED_PACKET_FROM_CLIENT` now, keeping its message about the removed
setting.

An out-of-place `QueryPlan` packet is rejected before `QueryPlan::deserialize`
rather than after it. Deserializing only to find the end of the packet remains
on the drain of a query that has already failed, which is post-authentication.

Every scenario of `05175_unexpected_packet_no_deserialization` now keeps the
socket open and requires the server to close it. The exception is sent before
the drain would run, so reading it proves nothing by itself; blocking in that
wait is what a server which drains the leftover input does. New scenarios for
a mid-insert `QueryPlan` and `IgnoredPartUUIDs` packet, and one that appends a
`QueryPlan` type byte after a rejected `Query`, cover the changes above.

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

Avogar commented Sep 11, 2026

Copy link
Copy Markdown
Member

Pushed 5da0ecd: the review finding, plus two adjacent cases in the same spirit.

The finding. Rejecting a packet without reading its payload leaves the input mid-packet, and the post-exception drain in runImpl ran anyway — parsing those bytes as a packet stream of its own, so the deserialization this PR avoids happened a moment later (a leading 13 reaches receiveQueryPlan and QueryPlan::deserialize, a 2 or a 7 reaches NativeReader), and blocking until receive_timeout for the rest of a packet the client never sent, all to preserve a connection that is closed right afterwards for this very error code. skipData is now skipped for UNEXPECTED_PACKET_FROM_CLIENT, and only for it: with USER_EXPIRED or TCP_CONNECTION_LIMIT_REACHED the stream is still framed correctly, and closing with the client's in-flight data unread would make the kernel send RST, which can cost the client the exception it was about to read. The pre-query rejections were never affected, because runImpl returns early when there is no query state — receivePacketsExpectData was the only path.

Adjacent cases. processObsoleteIgnoredPartUUIDs stopped reading its payload in 2553c8f but throws UNSUPPORTED_METHOD, which does not close the connection, so mid-query it left the connection alive with a desynchronized stream; it now throws UNEXPECTED_PACKET_FROM_CLIENT and keeps its message about the removed setting. An out-of-place QueryPlan packet is now rejected before QueryPlan::deserialize rather than after it, leaving the deserialize-to-find-the-end only on the drain.

Test. It closed the socket as soon as it read the exception, but the exception is sent before the drain would run, so it passed either way. Every scenario now keeps the socket open and requires the server to close it, which is what a server that drains the leftover input fails. Added scenarios for a mid-insert QueryPlan and IgnoredPartUUIDs packet, and one that appends a QueryPlan type byte after a rejected Query to show that leftover bytes are not parsed. Passes locally in 3.2 s; I have not yet confirmed it fails against a pre-change build.

Comment thread src/Server/TCPHandler.cpp Resolved
alexey-milovidov and others added 2 commits September 14, 2026 01:32
Conflict in `TCPHandler::receivePacketsExpectQuery`: master (34f0104) reports a pre-authentication
interserver `Data` packet as `AUTHENTICATION_FAILED`; that check is kept in front of the PR's
`throwUnexpectedPacket`, which replaces the payload-reading `processUnexpectedData` /
`processUnexpectedHello`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Review asked for the protocol contract to be spelled out in
`docs/reference/interfaces/specs/NativeProtocol.mdx` rather than left to be
re-derived from `TCPHandler.cpp`. Adds a `Protocol violations` section to the
connection lifecycle: which client packets are violations in `READY` and while
the server reads a query's input, that the server rejects them as soon as it has
read the packet-type code and never reads the body, that before a query it closes
without an `Exception` packet while mid-query it sends `UNEXPECTED_PACKET_FROM_CLIENT`
(code 101) first, and that the leftover bytes are not parsed as further packets.
Contrasts that with a failed `INSERT`, where the remaining `Data` packets are
drained and the connection survives. Marks `IgnoredPartUUIDs` as obsolete in the
packet type reference and extends the `READY` state row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@mintlify

mintlify Bot commented Sep 14, 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 Oct 13, 2026, 9:03 PM

Comment thread src/Server/TCPHandler.cpp Resolved
`skipData` was gated on the exception code, but what makes skipping safe is
positional: the input has to sit at a packet boundary. The two agree only for a
rejected packet, whose body is never read. An exception escaping a body read
leaves that body half-consumed, carries an unrelated code, and was skipped
anyway, so the remaining bytes of the failed packet were parsed as packets of
their own. An `INSERT` whose `Data` packet names a column type that does not
exist is enough to reach it: `NativeReader` resolves the type right after
reading its name, so it throws with the rest of the packet unread, and the
drain then takes the client's payload for a packet stream - deserializing
whatever it finds there and blocking until `receive_timeout` for a packet that
was never sent.

`QueryState::packet_body_partially_read` now marks the window in which bytes of
a body have been consumed, across `processData`, `skipDataPacket`, both
`QueryPlan::deserialize` paths and the three parallel-replicas and
cluster-function response reads. Plain assignments rather than a scope guard:
leaving the flag set when the read throws is exactly the wanted signal. The
marks cover the reads alone - wrapping all of `processData` would also cover
the external-table pipeline push that follows it, where a `Cancel` would then
close an otherwise healthy connection.

The flag skips the drain and, more importantly, closes the connection.
Skipping alone would only move the problem: the connection would be kept and
the next query would read the rest of the abandoned body as its first packet.

An out-of-place `QueryPlan` packet is now rejected while draining too. The
drain consumes what a failed query's input still owes and a stray plan is not
part of that, so `skipping_data` no longer waives the check. That leaves the
global-context fallback in `receiveQueryPlan` unreachable, and it goes away.

`05175_unexpected_packet_no_deserialization` gains the two matching scenarios
and keeps `dataAfterFailedInsertScenario` as their counterweight: a failure
after a complete packet must still drain the rest and keep the connection.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`queryPlanDuringDrainScenario` waited for an exception that could not arrive
yet, so the fast test timed out in it. Two things have to line up for a
rejected row to fail an insert while the client is still sending, which is
what leaves the server draining the rest of the row stream. `max_threads = 1`
keeps the insert pipeline single-threaded, so the error surfaces from the
`push` of the offending block instead of at the end through
`PushingAsyncPipelineExecutor`. `max_block_size = 1` is what sets the squashing
threshold for a table that does not prefer large blocks, as `Memory` does not,
so `min_insert_block_size_rows` has no effect there.

`dataAfterFailedInsertScenario` never reached the drain either, for the same
reason plus one of its own: it sent the end-of-data terminator before the
insert failed, so `read_all_data` was already true and `skipData` was never
entered - `skipDataPacket` had no coverage at all. It now fails on its first
block and finishes its row stream afterwards, which is the sequence that
exercises the drain and shows the connection surviving it.

Verified against a server without this pull request: both new scenarios block
until the receive timeout there, while the rewritten
`dataAfterFailedInsertScenario` passes, so it holds as their counterweight.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
The drain consumed an out-of-place `QueryPlan` packet by deserializing it to
find where it ends. That runs the query-plan deserializer on a peer's bytes,
which is what the `process_query_plan_packet` server setting exists to
prevent - and the setting does not stop it, because it is off by default and a
query rejected for that reason fails after `processQuery` has finished, so the
drain runs and takes the plan packet the client still owes.

Rejecting it instead costs the reuse of a connection whose query is already
lost, and the client has its exception either way. In exchange the drain is
left deserializing nothing but `Data` blocks, which is what the protocol spec
already describes.

Also closes the case the review raised: with nothing recording that a plan had
been consumed, the drain accepted a second and every further `QueryPlan` for
the same query, since the guard only looked at `plan_and_sets`, which the skip
path never set. Tracking "already consumed" would not have been enough on its
own - after a rejection for the setting being off no plan has been consumed, so
the first one would still have been deserialized.

Not covered by a functional test. The state needed to reach it - a
`stage = QueryPlan` query that fails before its plan arrives - requires
`process_query_plan_packet` to be off, and `tests/config` turns it on for
stateless tests, where the server then waits for the plan instead of failing.
Reaching it with the setting on through a failure after a complete packet does
not work either: the connection is already closed by the time the plan packet
would be read.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
`packet_body_partially_read` was set inside the body reads, but the packet type
is a varuint and is read before all of them, so a client could leave the input
mid-packet where nothing marked it: send `0x80` during an `INSERT` and the type
read consumes that byte and waits for a continuation that never comes. The
resulting `SOCKET_TIMEOUT` neither cancels the buffer nor closes the
connection, so the drain ran from inside the type and the connection was then
kept, with the next query free to read the rest of that varuint as its first
packet.

The flag is now positional - `at_packet_boundary`, cleared before the type is
read and set again only once the whole packet is consumed. Clearing it before
the read rather than after is the point: a throw inside `readVarUInt` has to
leave it cleared. This covers partial types and partial bodies with one
concept, so the two are no longer tracked separately.

All five readers that take a packet type while a query state exists are
covered: the data loop, the cancellation poll, and the three parallel-replicas
and cluster-function response readers. The no-body arms mark the boundary as
soon as the type is read, `Cancel` before calling `processCancel`, which throws
by design and whose `QUERY_WAS_CANCELLED_BY_CLIENT` must keep the connection.
`processData` still marks it after the block read and before the pipeline push,
so a `Cancel` arriving during that push cannot close a healthy connection.

Not covered by a functional test. Reaching it needs the type read to throw
while the connection stays open, which means a real socket timeout; closing the
write side instead gives EOF, and then the drain hits EOF too and closes either
way. `receive_timeout` in the query settings did not shorten the wait in
practice, so a test would sit on the default 300 seconds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Server/TCPHandler.cpp Resolved
`read_all_data` only became `false` at the very end of `processQuery`, long
after the `Query` packet itself had been consumed. A failure in between -
resolving the query context, checking settings constraints - therefore left
`runImpl` believing the query's input had all been read: no drain ran, and
since the input was still aligned the connection was preserved. The data
packets that always follow a `Query` were then stranded, for the next query on
that connection to read as its first packet, where it is rejected as an
unexpected `Data` packet.

The flag is now cleared as soon as the `Query` packet has been read, which is
the point from which that data is owed. A well-behaved client sends the
end-of-external-tables block immediately after its query, so the drain finds
its terminator at once; the exception reaches the client before the drain
either way.

Also narrows the `Protocol violations` table in the spec: it promised an
`Exception` with code `101` for a violating packet mid-query, but one arriving
while the server is discarding the input of a query that has already failed is
rejected silently - the drain's own exception is swallowed and the connection
just closes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits October 13, 2026 20:26
…ing-state rows of the protocol-violations table

After the query input has ended, distributed execution still accepts
`ReadTaskResponse`, `MergeTreeReadTaskResponse` and
`MergeTreeAllRangesAnnouncementResponse` while the matching request is
outstanding (`receiveClusterFunctionReadTaskResponse`,
`receivePartitionMergeTreeReadTaskResponse`,
`receiveAllRangesAnnouncementResponse`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit f26191d Oct 14, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the no-deserialize-unexpected-packets branch October 14, 2026 21:30
@robot-ch-test-poll robot-ch-test-poll added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 14, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 14, 2026
Backport #119368 to 26.9: Do not deserialize unexpected packets in TCPHandler
alexey-milovidov added a commit that referenced this pull request Oct 15, 2026
Resolve the conflicts by re-applying the change of
#119368 onto the 26.3 version
of `TCPHandler`, which differs from master around it:

- 26.3 has no detached-query (`run_query_in_background`) path and no
  `receiveAllRangesAnnouncementResponse`, so those parts are dropped.
- 26.3 still supports `IgnoredPartUUIDs` before a query; the out-of-place one
  during the data phase is now rejected with `throwUnexpectedPacket` without
  reading its payload, like the other unexpected packets, so
  `processUnexpectedIgnoredPartUUIDs` is removed as well. The test expects the
  generic message for it accordingly.
- `QueryPlan::deserialize` and `NativeReader` keep their 26.3 signatures.
- The native protocol docs page does not exist on 26.3 and is dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-1 added a commit that referenced this pull request Oct 15, 2026
Cherry pick #119368 to 26.3: Do not deserialize unexpected packets in TCPHandler
robot-ch-test-poll2 added a commit that referenced this pull request Oct 15, 2026
Cherry pick #119368 to 26.7: Do not deserialize unexpected packets in TCPHandler
alexey-milovidov added a commit that referenced this pull request Oct 15, 2026
Resolve the conflict in `TCPHandler::runImpl`: 26.8 does not have the
`out->sync` before draining a detached query's input (a separate master
change), so keep the 26.8 code and only wrap `skipData` in the
`try`/`catch` added by #119368.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 15, 2026
Cherry pick #119368 to 26.8: Do not deserialize unexpected packets in TCPHandler
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 15, 2026
Backport #119368 to 26.8: Do not deserialize unexpected packets in TCPHandler
alexey-milovidov added a commit that referenced this pull request Oct 15, 2026
Backport #119368 to 26.3: Do not deserialize unexpected packets in TCPHandler
PedroTadim added a commit that referenced this pull request Oct 19, 2026
Backport #119368 to 26.7: Do not deserialize unexpected packets in TCPHandler

This branch was successfully deployed

1 active deployment
staging - docs — d94f9b98 Deployed Oct 13, 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-improvement Pull request with some product improvements 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.

6 participants