Skip to content

Cherry pick #119368 to 26.8: Do not deserialize unexpected packets in TCPHandler - #125883

Merged
robot-clickhouse-ci-2 merged 32 commits into
backport/26.8/119368from
cherrypick/26.8/119368
Oct 15, 2026
Merged

robot-clickhouse-ci-2 merged 32 commits into
backport/26.8/119368from
cherrypick/26.8/119368

Conversation

@robot-clickhouse

Copy link
Copy Markdown
Member

Original pull-request #119368

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

alexey-milovidov and others added 30 commits September 10, 2026 23:56
`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.
`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]>
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]>
`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]>
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]>
`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]>
`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]>
…tocol violations` table

List `TablesStatusRequest` as a valid `READY`-state exchange, and describe the
client packets that are legal after `Query` (query input as `Data` / `Scalar` /
`QueryPlan`, `Ping` while the input is read, `Cancel`, read-task answers),
so the top-level state table no longer contradicts the violations table.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A lone `0x80` sent during an `INSERT`, followed by a half-close, leaves the
server at the end of the input in the middle of the packet type `VarUInt`.
The new scenario asserts that the server closes the connection promptly
instead of draining from there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ations` table

Once the query's input has ended, client packets are read by
`receivePacketsExpectCancel`, which closes the connection with
`UNKNOWN_PACKET_FROM_CLIENT` and no `Exception` for anything other than
`Cancel` (and the obsolete `IgnoredPartUUIDs`). Document that as its own row
instead of claiming a late `QueryPlan` gets `UNEXPECTED_PACKET_FROM_CLIENT`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore the end-of-data marker

The `Query phase` sequence listed only external tables before the empty
`Data` marker, while `RemoteQueryExecutor::sendQuery` sends the scalars,
then the optional `QueryPlan`, then the external tables, and the server
rejects a `QueryPlan` that arrives after the marker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Server/TCPHandler.cpp
…rain

With `run_query_in_background`, `skipData` runs after `EndOfStream` has
already been sent. An exception there - such as an out-of-place `QueryPlan`,
now rejected while draining - reached the normal exception path and put an
`Exception` packet on the wire after `EndOfStream`. Close the connection
without sending anything instead, as the failed-query drain already does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…state

Describe the `READY` row by the packets that are allowed there, and document
that a violation during the drain of a detached query closes the connection
without an `Exception` after `EndOfStream`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… the query input

`receivePacketsExpectData` ends the client input on any empty block, and
`Scalar` packets go through the same `processData` path as `Data`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ueryPlan` and `IgnoredPartUUIDs`

The `READY` state-table row now says that any packet other than the
allowed ones is a violation and names `QueryPlan` (13) among the examples.
The `Protocol violations` table gets a separate row for `IgnoredPartUUIDs`
after the query input has ended: `processObsoleteIgnoredPartUUIDs` throws
`UNEXPECTED_PACKET_FROM_CLIENT`, so the server sends `Exception` `101`
before closing, unlike the silent close for other packets in that state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…packets

Do not deserialize unexpected packets in TCPHandler
@robot-clickhouse robot-clickhouse added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request labels Oct 14, 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
robot-clickhouse-ci-2 merged commit d2da2f9 into backport/26.8/119368 Oct 15, 2026
1 check passed
@robot-clickhouse-ci-2
robot-clickhouse-ci-2 deleted the cherrypick/26.8/119368 branch October 15, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants