Repository navigation
Do not deserialize unexpected packets in TCPHandler - #119368
Conversation
`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.
|
Workflow [PR], commit [d94f9b9] Summary: ✅
AI ReviewSummaryPR #119368 rejects unexpected native-protocol packets before deserializing their bodies and closes connections after incomplete packet reads. It preserves connection reuse when a failed Final VerdictStatus: ✅ Approve. |
Build profile diff (arm_release)Commit See the job log for details. |
`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]>
|
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 Adjacent cases. 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 |
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
`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]>
…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]>
Backport #119368 to 26.9: Do not deserialize unexpected packets in TCPHandler
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]>
Cherry pick #119368 to 26.3: Do not deserialize unexpected packets in TCPHandler
Cherry pick #119368 to 26.7: Do not deserialize unexpected packets in TCPHandler
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]>
Cherry pick #119368 to 26.8: Do not deserialize unexpected packets in TCPHandler
Backport #119368 to 26.8: Do not deserialize unexpected packets in TCPHandler
Backport #119368 to 26.3: Do not deserialize unexpected packets in TCPHandler
Backport #119368 to 26.7: Do not deserialize unexpected packets in TCPHandler
TCPHandlerused to read the whole payload of a packet that cannot appear at the current point of the protocol, and only then throwUNEXPECTED_PACKET_FROM_CLIENT. For aDataorScalarpacket that meant runningNativeReaderover untrusted bytes: resolving arbitrary type names throughDataTypeFactoryand 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 aDatapacket arriving where a query is expected reaches the deserializer first.Verified against a server built before this change: a
Datapacket sent instead of a query gets as far asAggregateFunctionFactory::getImpl.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
IgnoredPartUUIDspacket is already rejected.processUnexpectedData,processUnexpectedQuery,processUnexpectedHelloandprocessUnexpectedTablesStatusRequestare replaced by a singlethrowUnexpectedPacket, which keeps the existing messages. The skip parsers also duplicated the real readers and drifted from them:processUnexpectedQuerynever 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 ordinaryINSERT. It moves toskipDataPacket, which takes the compression flag from the query state instead of thelast_block_inmember — the two always held the same value there, becauseskipDataruns only afterprocessQueryhas completed, soLastBlockInputParametersis gone.The new test
05175_unexpected_packet_no_deserializationsends 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 subsequentPing.Related: #68800
Changelog category (leave one):
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
Datapacket — including arbitrary data types and aggregate function states — only to throwUNEXPECTED_PACKET_FROM_CLIENTand close the connection.Workflow [PR]
Sync PR [sync-upstream/pr/119368]
Version info
26.10.1.2410-master(included in26.10and later)26.9.20.12,26.8.29.7,26.7.35.2,26.3.53.5