Skip to content

Add the ResetSession packet to the native protocol - #123914

Open
alex-clickhouse wants to merge 9 commits into
ClickHouse:masterfrom
alex-clickhouse:reset-session-packet
Open

alex-clickhouse wants to merge 9 commits into
ClickHouse:masterfrom
alex-clickhouse:reset-session-packet

Conversation

@alex-clickhouse

@alex-clickhouse alex-clickhouse commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #105962

This adds the ResetSession packet (type 15) to the native TCP protocol. The packet returns the session of a connection to its state right after authentication, without a new connection. A client connection pool can send it when a connection comes back to the pool, so that the next user does not get the settings, temporary tables or current database of the previous user.

This PR replaces the SQL statement RESET SESSION from #105962. In review, tavplubix asked for a packet of the native protocol instead of a SQL query, so that TCPHandler makes a new context and the other components do not change.

How it works

  • Session::resetSessionContext makes a new session context with the same code that login uses (createSessionContextForUser and applySettingsFromAuthServer, now shared by both). The new context gets the authenticated user, the external roles, the grants and expiry of the authentication method, and the settings from an external authentication server. The client info of the connection is kept.
  • The old context is destroyed. With it go the settings changed by SET, the current roles and database, temporary tables, query parameters, scalars and in-memory backups.
  • TCPHandler sets the database from the handshake on the new context before it replaces the old one. If the handshake had no database, the session uses the default database of the user, read again from access control.
  • If anything fails, the old context stays and the server sends Exception. The connection stays open, except for USER_EXPIRED. If the database from the handshake was dropped, the reset fails with UNKNOWN_DATABASE, the same as a new connection with that handshake.
  • The reset is rejected with INVALID_TRANSACTION inside a transaction. No query runs, so the transaction is not touched, and the client can still COMMIT or ROLLBACK.
  • The reset is rejected with ACCESS_DENIED while the session runs as another user after EXECUTE AS. See EXECUTE AS and other one-way changes.
  • On success the server refreshes its connection settings (idle_connection_timeout and the others) from the new context and replies with EndOfStream.
  • The packet is valid only between queries. During a query, while the server reads the query data or runs the query, the server cancels the query, replies with UNEXPECTED_PACKET_FROM_CLIENT and closes the connection.

EXECUTE AS and other one-way changes

A session can give up rights in a way that its SQL cannot undo:

  • After EXECUTE AS target (the form without a subquery), the session runs as target. To go back, target needs IMPERSONATE on the original user. Without it, the server returns ACCESS_DENIED.
  • After SET readonly = 1 (or 2), SET readonly = 0 fails with READONLY.
  • After SET allow_ddl = 0, SET allow_ddl = 1 fails.

A proxy can use this to run less trusted SQL on its own connection. In the review of #105962, ringerc found that the SQL statement RESET SESSION undid EXECUTE AS (comment). The less trusted SQL could send RESET SESSION itself, so EXECUTE AS was no longer one-way. The same applied to readonly and allow_ddl.

This PR closes this gap with two rules:

  1. SQL cannot send the packet. Only the client that owns the connection can send ResetSession. The SQL that runs in the session cannot undo EXECUTE AS, readonly or allow_ddl with it.
  2. The reset does not change the user. A reset rebuilds the session context for the existing authenticated connection, retaining its authentication grants, expiry, external roles and external authentication response. It does not authenticate again. If the session runs as another user after EXECUTE AS, the server rejects the reset with ACCESS_DENIED and the session does not change. The client must open a new connection, and for that it needs the credentials. After EXECUTE AS back to the authenticated user, the reset works again. SQL Server has the same rule: its connection pool reset fails with error 18059 when the session runs as an impersonated principal.

readonly and allow_ddl get the values from the profile of the user, the same as all other settings, because a new login of the same user also gets these values. The server does not keep a list of one-way settings: each new setting would have to be added to such a list, and it is easy to forget. The user check is one condition, and it does not depend on what the session changed.

A proxy that forwards the packets of a less trusted client on its own connection must not forward ResetSession. This is a check of one packet type, not a match on SQL text.

05326_reset_session_packet_user tests these rules: the reset is rejected after EXECUTE AS and the session stays usable, the reset works again after EXECUTE AS back to the authenticated user, and readonly gets the value from the profile.

Version gate

The packet has the protocol version 54495 (DBMS_MIN_PROTOCOL_VERSION_WITH_RESET_SESSION). It is gated on the server's version from the server Hello, not on the client's version. The server accepts the packet from a client with any version, because neither the request nor the reply has a field that depends on the version.

A gate on the client's version would force a client to declare 54495. With that declaration, the server switches on every feature up to 54495 for the connection, which includes sparse columns (54465), replicated columns (54482) and the new String layout (54492). For example, the native client in clickhouse-cs declares 54460, and it would have to implement all of these before it could clean its pooled connections. The client TablesStatusRequest already uses the same pattern: ConnectionEstablisher sends it only if server_revision is high enough.

An older server closes the connection when it receives an unknown packet, so a client must check the server's version first. The spec in docs/resources/develop-contribute/native-protocol/protocol.mdx describes this.

Benchmark

On review, tavplubix asked how much this saves. We measured the clickhouse-cs native client against ClickHouse 26.7 in Docker, with network delay added by tc netem. The reset was simulated with SELECT 1 on an open connection. The other option was to close the connection and open a new one (TCP, TLS, Hello). Median time for one cleanup:

Added RTT Reset (SELECT 1, TLS) Reconnect, plain Reconnect, TLS
0 ms 1.26 ms 0.51 ms 2.49 ms
1 ms 1.89 ms 2.43 ms 5.70 ms
5 ms 6.97 ms 10.7 ms 22.3 ms
20 ms 21.1 ms 40.7 ms 65.6 ms
50 ms 51.5 ms 101.6 ms 153.5 ms

The purpose is to avoid additional connection-establishment round trips and reduce socket churn for applications that frequently reuse pooled connections. ResetSession takes one round trip on the existing connection. In this benchmark setup, a plain reconnect takes two round trips and a TLS reconnect takes three. Keeping the socket open also avoids repeatedly creating and closing sockets and reduces pressure on ephemeral ports and TIME_WAIT under heavy connection turnover.

The measurements above use SELECT 1 as a latency proxy; they are not measurements of the actual reset implementation.

Regression coverage

The executable stateless tests cover session cleanup, transaction rejection without aborting the transaction, current access-control defaults, one-way EXECUTE AS, authentication-scoped grants, restrictive settings, quota consumption, and state preservation when database validation fails. Integration tests cover authentication expiry, session limits, all four chunked/unframed combinations with an older client revision, and external-authentication profile replay and failure handling.

Limits

  • A pool must wait for EndOfStream before treating a connection as clean. On Exception, the previous session state can remain; discard the connection if cleanup cannot be completed.
  • The server does not send its settings again after a reset. A client that applies the server settings from the Hello (apply_settings_from_server) keeps the values from login.
  • Only the native TCP protocol has the packet. HTTP clients can start a new session with a new session_id.

Changelog category (leave one):

  • New Feature

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

The native protocol has a new client packet ResetSession. It returns the session of a connection to its state right after authentication: settings, roles, current database, temporary tables and query parameters. Client connection pools can use it to clean a connection without a new connection. A session that runs as another user after EXECUTE AS cannot be reset. A client can use the packet when the server's protocol version is 54495 or more, whatever its own version is.

🤖 Generated with Claude Code


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

The `ResetSession` client packet (type 15) returns the session of a native
connection to its state right after authentication, without a new connection.
`Session::resetSessionContext` makes a new session context with the same code
as login, and `TCPHandler` sets the database from the handshake on it before it
replaces the old context. If anything fails, the old context stays and the
server replies with `Exception`; on success it replies with `EndOfStream`.

The packet has the protocol version 54493. A client checks it against the
server's version from the Hello packet, and the server accepts the packet from
a client with any version, so a client does not need support for all earlier
protocol versions to use it.

Related: ClickHouse#105962

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f92df54]

Summary: ✅


AI Review

Summary

Adds the native TCP ResetSession packet to rebuild a pooled connection's session while retaining its authentication limits. Reviewed PR head f92df544e2902624346186e6a78fab80dc569fa4, the full diff, surrounding implementation, and all prior discussion. No actionable findings remain; the previous query-phase rejection issue is fixed.

Current-head fast-test results pass four reset regressions; the transaction test is skipped there. The transaction and other reset regressions passed in the earlier PR commit's targeted stateless run, and authentication, session-limit, and framing cases passed in its integration run. Those full jobs are still pending on the reviewed head.

Final Verdict

Status: ✅ Approve. No code changes requested; pending CI should complete before merge.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Oct 4, 2026
@alex-clickhouse alex-clickhouse added the can be tested Allows running workflows for external contributors label Oct 5, 2026
Comment thread src/Server/TCPHandler.cpp Resolved
While the server runs a query, it reads client packets in
`receivePacketsExpectCancel`. There, packet 15 went to the default branch,
`UNKNOWN_PACKET_FROM_CLIENT`, and the server closed the connection without an
`Exception`. The packet has no body, so the input is in sync: raise
`UNEXPECTED_PACKET_FROM_CLIENT`, as during the read of the query data, so the
client gets the error before the server closes the connection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f92df544e with master 3f1c2fc7b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

328 translation units recompiled, 3165 s compile time in total, 326 of them have a recent master baseline.

Job report

A reset is a new login of the authenticated user without its credentials.
After `EXECUTE AS`, a reset gave back the rights that `EXECUTE AS` dropped,
so `EXECUTE AS` was no longer one-way for the client of the connection.
The server now rejects the reset with `ACCESS_DENIED` in this case. The
session does not change and the connection stays open; the client must
open a new connection. After `EXECUTE AS` back to the authenticated user,
the reset works again.

Settings that the session cannot change back itself (`readonly`,
`allow_ddl`) get the values from the profile, as at a new login. SQL cannot
send the packet, so they stay one-way for the SQL that runs in the session.
The spec and `05326_reset_session_packet_user` describe and test both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI enables `table_engines_require_grant`, so `CREATE TEMPORARY TABLE`
alone does not permit the restricted users to create `Memory` tables.
Add `TABLE ENGINE ON Memory` to the atomicity and HTTP authentication
profile tests so they reach their session-preservation assertions.

Reproduced both failures locally with CI access-control improvements
enabled, then verified the stateless test through `clickhouse-test` and
the HTTP profile test body through the disposable-server adapter. The
local binary is the earlier PR build; full integration CI remains needed.

CI: https://github.com/ClickHouse/ClickHouse/actions/runs/38709305532/job/116337142579#step:4:34008
@alex-clickhouse
alex-clickhouse marked this pull request as ready for review October 15, 2026 14:56
@mintlify

mintlify Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit f92df54.

Approve preview

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant