Skip to content

Add RESET SESSION statement - #105962

Closed
alex-clickhouse wants to merge 48 commits into
ClickHouse:masterfrom
alex-clickhouse:reset-session
Closed

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

Conversation

@alex-clickhouse

@alex-clickhouse alex-clickhouse commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

What

RESET SESSION restores a session to the state it had immediately after authentication, without dropping the connection. After the reset:

  • Settings, profile, roles, and the current database are re-derived from access control (so admin edits to the user's profile take effect immediately).
  • Settings supplied at authentication time by an external auth server (e.g. LDAP, HTTP authentication) are replayed.
  • Temporary tables, query parameters, scalars, and in-memory backups (BACKUP ... TO Memory(name)) created during the session are dropped.
  • User identity is restored to the authenticated user — an in-session EXECUTE AS impersonation does not survive the reset.
  • Client info and the handshake-negotiated output format (MySQLWire, PostgreSQLWire) are preserved.
  • Active transactions are not silently rolled back. RESET SESSION is rejected with INVALID_TRANSACTION if the session is inside a transaction; pool implementations must COMMIT or ROLLBACK first.

Database fallback: only the native TCP handler captures the connection-start database. The other interfaces where the reset runs (HTTP, gRPC, Arrow Flight, clickhouse-local) fall back to the user's DEFAULT DATABASE, then to the server's global default. The first existing candidate wins, so an admin-dropped connection-start database is handled gracefully. (RESET SESSION is a no-op over MySQL and PostgreSQL — see below — so the fallback does not apply there.)

Client-side: clickhouse-client clears its parallel state on RESET SESSION so it doesn't re-send stale settings / query parameters on the next query, and probes the server with SELECT currentDatabase() to sync its local default database to whatever the server actually landed on (so a later reconnect doesn't request a database the server fell back away from).

Scope / known gaps (intentional)

RESET SESSION is a no-op over the MySQL and PostgreSQL wire protocols and leaves the session unchanged. Those handlers keep state outside the server-side session context that a context reset would not account for: the PostgreSQL emulation exposes the pg_* compatibility views as session-scoped temporary tables (a reset would clear them without re-creating them, breaking driver metadata queries), and the MySQL handler keeps the handshake database and prepared statements there. Rather than half-reset, the statement skips these two interfaces entirely; to reset a pooled MySQL/PostgreSQL connection, drop and reopen it (or use the protocol's own DISCARD ALL / DEALLOCATE).

On the interfaces where it does run (native TCP, HTTP, gRPC, Arrow Flight, clickhouse-local), RESET SESSION resets the server-side session context but deliberately does not touch protocol-local state a handler keeps outside it — notably Arrow Flight prepared-statement handles, which survive the reset. All of these gaps are documented on the statement page.

Why
Suppose you have a ClickHouse language client (e.g. in C#) that talks to the server over the native TCP protocol and maintains an internal connection pool.

A user borrows a connection, runs SET TIME ZONE 'Europe/Amsterdam';, CREATE TEMPORARY TABLE foo ..., and some other work, then returns the connection to the pool. The connection is now 'dirty' — it has modified state compared to a fresh one. The next borrower is surprised to get a connection with a changed timezone, leftover temporary tables, etc.

RESET SESSION lets the pool clean up connection state on return, allowing safe and predictable reuse without dropping the connection or parsing the user's queries to decide whether the connection is dirty.

Testing

Stateless: settings + params + temp tables, roles (custom user), HTTP transport, clickhouse-local (incl. database restoration over the local override), profile changes + exact connection-start DB restoration, profile constraint behavior across reset, client-side command-line settings snapshot/restore, --inline-insert-data startup-setting snapshot, dropped connection-start database fallback, user with no DEFAULT DATABASE fallback to the global default, in-transaction rejection, implicit_transaction = 1 exemption, BACKUP ... TO Memory(name) cleared by reset, EXECUTE AS impersonation undone by reset. Integration: gRPC without session_id is a graceful no-op; RESET SESSION is a no-op over the MySQL and PostgreSQL protocols (session state preserved, pg_* views still resolve); RESET SESSION re-applies external HTTP authenticator settings (including a profile returned by the auth server).

Changelog category (leave one):

  • New Feature

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

You can now restore a session to its post-authentication state without dropping the connection by running RESET SESSION. This clears settings modified by SET, query parameters, temporary tables, and in-memory backups, and restores the current database and roles to the user's defaults. It resets the server-side session context and is a no-op over the MySQL and PostgreSQL wire protocols; on other interfaces, protocol-local state such as Arrow Flight prepared statements is not affected.

Introduces a SQL statement that restores a TCP session to the state it
was in immediately after authentication, without dropping the
connection or re-authenticating. The statement re-derives profiles,
roles, the default database, and settings from access control;
re-applies any settings supplied by the authentication server; and
drops all temporary tables, query parameters, and scalars created
during the session. The authenticated user identity, the connection's
client info, and the handshake-time output format (`MySQLWire`,
`PostgreSQLWire`) are preserved.

Native TCP, MySQL, and PostgreSQL handlers also remember the database
the connection was opened with so the reset restores it (rather than
the user's profile default). HTTP and gRPC fall back to the profile
default, documented in the statement page.

The client side (`ClientBase`) also clears its parallel state on
`RESET SESSION` so the next query doesn't re-send the stale settings
and query parameters the server has just dropped.

Includes six stateless tests covering: settings + params + temp tables
(SQL), roles (custom user via .sh), HTTP transport, clickhouse-local,
profile changes + exact connection-start DB restoration, and profile
constraint behavior across reset.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alex-clickhouse
alex-clickhouse requested a review from Copilot May 27, 2026 14:55
@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f062c9c]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Column identifier A is already registered (STID: 4697-4326) FAIL cidb
Stateless tests (arm_asan_ubsan, azure, sequential) FAIL
Server died FAIL cidb
03714_queries_escaping_3 UNKNOWN cidb
03710_parallel_alter_comment_rename_selects UNKNOWN cidb, issue
Unknown error FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_s3_aws_sdk_has_slightly_unreliable_behaviour/test.py::test_dataloss FAIL cidb

AI Review

Summary

This PR adds RESET SESSION across parsing, interpretation, session reset state, client-side synchronization, documentation, and focused regression coverage. The core reset implementation has addressed the earlier session-baseline issues, but one current authorization invariant still does not hold: a readonly HTTP GET can run the mutating reset against a named session.

PR Metadata
  • Changelog category: New Feature is appropriate.
  • Changelog entry: required, but the current text overstates protocol coverage. The code and docs now make RESET SESSION a full no-op over the MySQL and PostgreSQL wire protocols, while the entry only says protocol-local state such as prepared statements is unaffected.
  • Suggested replacement:
You can now restore a ClickHouse session to its post-authentication state without dropping the connection by running `RESET SESSION` on interfaces where the statement has a session context to reset. It clears settings changed by `SET`, query parameters, temporary tables, and in-memory backups, and restores the current database and roles to the authenticated user's defaults. Over the `MySQL` and `PostgreSQL` wire protocols the statement is currently a no-op; protocol-local state such as Arrow Flight prepared statements is not reset.
Findings

⚠️ Majors

  • [src/Interpreters/InterpreterResetSessionQuery.cpp:35] [dismissed by author -- https://github.com/Add RESET SESSION statement #105962#discussion_r3333350697] RESET SESSION mutates session state even when the query context is readonly. HTTPHandler sets readonly = 2 for non-POST requests, but InterpreterResetSessionQuery::execute never checks readonly before calling Context::resetToUserDefaults. With a named HTTP session, GET ?query=RESET%20SESSION&session_id=s can clear settings, query parameters, temporary tables, and in-memory backups despite GET being constrained to readonly queries. Please reject RESET SESSION when readonly is nonzero before mutating the session context, or otherwise require POST for this statement.
Tests
  • ⚠️ Add a focused HTTP named-session regression for GET ?query=RESET SESSION&session_id=...: it should return READONLY, and state dirtied before the request should still be present afterwards.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: enforce the readonly/POST invariant for RESET SESSION, add the HTTP GET regression, and update the changelog entry to mention the MySQL/PostgreSQL no-op behavior.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 27, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR introduces a new RESET SESSION statement that restores server (and client) session state to the post-authentication baseline without reconnecting.

Changes:

  • Added parser, AST, interpreter registration, and execution path for RESET SESSION.
  • Implemented Context::resetToUserDefaults() to re-derive roles/profiles/settings and clear session-scoped state.
  • Added end-to-end tests (TCP, HTTP, clickhouse-local) plus documentation and fuzz dictionary coverage.

Reviewed changes

Copilot reviewed 32 out of 32 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04028_reset_session.sql SQL-level smoke coverage for RESET SESSION semantics.
tests/queries/0_stateless/04028_reset_session.reference Expected output for the SQL smoke test.
tests/queries/0_stateless/04029_reset_session_user_state.sh Validates roles/default role restoration across reset.
tests/queries/0_stateless/04029_reset_session_user_state.reference Expected output for role restoration test.
tests/queries/0_stateless/04030_reset_session_http.sh Exercises HTTP session_id state reset (params, temp tables).
tests/queries/0_stateless/04030_reset_session_http.reference Expected output for HTTP test.
tests/queries/0_stateless/04031_reset_session_local.sh Smoke test that clickhouse-local reset doesn’t crash and clears state.
tests/queries/0_stateless/04031_reset_session_local.reference Expected output for local test.
tests/queries/0_stateless/04032_reset_session_profile_and_db.sh Ensures profile/database are restored exactly after reset in a single TCP session.
tests/queries/0_stateless/04032_reset_session_profile_and_db.reference Expected output for profile/db restoration test.
tests/queries/0_stateless/04033_reset_session_constraints.sh Verifies constraints survive reset and pick up mid-session profile tightening.
tests/queries/0_stateless/04033_reset_session_constraints.reference Expected output for constraints test.
tests/fuzz/all.dict Adds RESET SESSION to fuzzing dictionary.
src/Server/TCPHandler.cpp Captures “session-start database” for native TCP sessions.
src/Server/MySQLHandler.cpp Captures “session-start database” for MySQL wire sessions.
src/Server/PostgreSQLHandler.cpp Captures “session-start database” for PostgreSQL wire sessions.
src/Parsers/CommonParsers.h Introduces RESET SESSION keyword token.
src/Parsers/IAST.h Adds QueryKind::ResetSession.
src/Parsers/ASTResetSessionQuery.h Adds AST node for RESET SESSION.
src/Parsers/ParserResetSessionQuery.h Declares parser for RESET SESSION.
src/Parsers/ParserResetSessionQuery.cpp Implements parser for RESET SESSION.
src/Parsers/ParserQuery.cpp Integrates RESET SESSION into top-level query parsing.
src/Interpreters/InterpreterResetSessionQuery.h Declares interpreter for RESET SESSION.
src/Interpreters/InterpreterResetSessionQuery.cpp Implements interpreter and factory registration.
src/Interpreters/registerInterpreters.cpp Registers InterpreterResetSessionQuery.
src/Interpreters/InterpreterFactory.cpp Routes ASTResetSessionQuery to the correct interpreter.
src/Interpreters/Session.cpp Persists auth-server settings on the session context for replay on reset.
src/Interpreters/Context.h Adds state and APIs needed for reset (auth settings + session-start DB + reset method).
src/Interpreters/Context.cpp Implements resetToUserDefaults() and related helpers.
src/Client/ClientBase.h Tracks “database at connect” for client-side mirroring of reset behavior.
src/Client/ClientBase.cpp Mirrors server-side reset in the client (clearing params/settings + restoring DB).
docs/en/sql-reference/statements/reset-session.md Adds user-facing documentation for RESET SESSION.

Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Interpreters/Context.h Resolved
- ClientBase: snapshot the client-side effective settings at `initClientContext`
  and restore that snapshot on `RESET SESSION` instead of compiled-in
  defaults. Without this, a client invoked with command-line overrides like
  `--max_threads 4` would lose them after `RESET SESSION` even though the
  user expects them to be part of the "connection baseline" (analogous to
  the existing `default_database_at_connect` snapshot). Added test
  `04034_reset_session_cmdline_settings`.
- `Context::resetToUserDefaults`: tighten the fallback in the
  `target_database` existence check to swallow only `UNKNOWN_DATABASE`
  rather than every `Exception`. Catalog internal errors and permission
  failures now propagate instead of being masked.
- `Context.h`: doc comment on `resetToUserDefaults` mentioned "formats"
  in the cleared-collections list, but the implementation doesn't clear
  format state (and the user-facing docs say handshake-negotiated formats
  are *preserved*). Fixed to match the implementation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alex-clickhouse alex-clickhouse added the can be tested Allows running workflows for external contributors label May 27, 2026
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
The .cpp / .h source files and the .sql / .reference test data files
got committed with mode 0755 by mistake. Strip the executable bit; the
.sh test runner scripts keep it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…aults

Two issues raised on PR ClickHouse#105962:

1. Database fallback chain was broken. The code wrote
       database_at_session_start.value_or(user_default_database)
   so when `database_at_session_start` held a now-dropped database
   the `assertDatabaseExists` catch path cleared `target_database` to
   empty instead of trying the user's profile default. Concrete case:
   connect with `--database A`, user default is `B`, drop `A`, then
   `RESET SESSION` lands on empty rather than `B`. Replaced with an
   explicit chain (`connection-start → profile-default → empty`),
   probing each candidate against the catalog.

2. Settings pre-compute didn't match the real post-auth pipeline.
   Login (`Session::makeSessionContext`) effectively does
   `createCopy(global_context).settings`, then layers profile changes
   through `setCurrentProfilesWithLock` (which runs quirks + sanity
   clamp + chains constraints onto the existing constraint set), then
   layers auth-server settings through `applySettingsChanges` (which
   runs quirks again). Reset was instead starting from a fresh
   `Settings{}` and applying profile + auth deltas as a single
   `applyChanges` call — no quirks, no sanity clamp, and no inheritance
   from the global baseline. Settings not explicitly present in the
   deltas would silently drift after `RESET SESSION`.

   New pipeline matches the login path step-for-step:
     - start from `getGlobalContext()->getSettingsCopy()`
     - apply profile changes, run quirks, run server-level sanity clamp
     - chain constraints onto the global context's existing constraint
       set, matching what `setCurrentProfilesWithLock` does
     - check auth-server settings against constraints, apply, run quirks

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
Fast test failures
==================

`04028_reset_session.sql` and `04033_reset_session_constraints.sh`
emitted server-side error logs for their expected `serverError` queries
into the per-test client_logs_file, triggering the runner's "having
stderror" failure. Match the workaround used by `00002_system_numbers`
and `01109_exchange_tables`: `SET send_logs_level = 'fatal'` for the
batches that contain `serverError` queries. `RESET SESSION` resets that
back to the baseline, so we re-`SET` it after each reset that precedes
another `serverError` query.

Also in 04028 the temp-table checks now query `system.tables` for the
session's hidden temporary database instead of triggering
`UNKNOWN_TABLE` — same invariant, no error log to suppress.

Post-auth re-derivation: post-application sanity clamp
======================================================

Login applies auth-server settings via `applySettingChangeWithLock`,
which runs the server sanity clamp per setting. The reset path applies
them via the lighter `Settings::applyChanges`, which doesn't. Run a
single sanity-clamp pass on the new settings after the auth-server
changes and quirks to land on the same final state.

Client-side: startup `--param_*` survives reset
================================================

`RESET SESSION` was clearing the client's `query_parameters` to empty,
which dropped startup `--param_*` values along with in-session
`SET param_*` changes. Snapshot the startup parameter map in
`initClientContext` and restore from it on reset (analogous to
`default_database_at_connect` and `settings_at_connect`).

Test: dropped connection-start database falls back to user default
==================================================================

`04035_reset_session_dropped_start_db.sh` covers the scenario the
reviewer flagged: connect with `--database A`, user's profile default
is `B`, drop `A` from inside the session, `RESET SESSION`, assert
`currentDatabase() = B`. The existing 04028 case drops a `USE`-d
database, not the captured connection-start one, so it never exercises
this fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Interpreters/Context.cpp Resolved
alex-clickhouse and others added 2 commits May 27, 2026 22:39
The style check at `ci/jobs/scripts/check_style/various_checks.sh:25-54`
requires any file that queries `system.tables` (and a handful of other
tables with a `database` column) to filter on `database = currentDatabase()`,
`$CLICKHOUSE_DATABASE`, or a literal database name.

`is_temporary` alone doesn't satisfy the check. Temporary tables live in
`_temporary_and_external_tables`, so use that as the literal filter —
which both satisfies the lint and makes the query slightly more precise.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…TCP-cache refresh

Docs: `reset-session.md`
=======================
Add the missing `sidebar_position` and `slug` frontmatter fields and
the `{#anchor}` suffix on every `H2` heading so the generated sidebar
slot and stable section anchors are well-formed. Model on neighboring
statement pages (use, set, set-role).

Database fallback: match `setUser` semantics
============================================
`Context::setUser` leaves `current_database` inherited from the global
context when the user has no `DEFAULT DATABASE`, so for HTTP, gRPC, and
`clickhouse-local` users without a profile default a fresh session
typically lands in `default` rather than empty. `resetToUserDefaults`
was clearing to empty in this case, which both broke the
no-op-on-already-clean-session contract and produced an unusable
session state. Add the global-context current database as the third
step in the fallback chain (before empty), and add a test for the
no-profile-default case.

Active-transaction guard
========================
Reject `RESET SESSION` when `merge_tree_transaction` is set on the
session context. Silently rolling back would discard work without
warning, and pretending to reset while leaving the transaction in
place would let a pooled connection inherit the previous snapshot and
uncommitted writes. The user can `COMMIT` or `ROLLBACK` explicitly and
then reset.

TCPHandler cached connection settings
=====================================
`TCPHandler` caches `idle_connection_timeout`, `poll_interval`,
`send_timeout`, `receive_timeout` etc. from the per-query context on
each query. If a session did `SET idle_connection_timeout = 1` then
`RESET SESSION`, the handler would still wait for the next packet
with the stale `idle_connection_timeout = 1` because the cache isn't
refreshed after query execution. Re-extract from the session context
right after `executeQuery` returns if the parsed query was a
`RESET SESSION`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Interpreters/Session.cpp Resolved
alex-clickhouse and others added 3 commits May 28, 2026 09:11
`${CLICKHOUSE_CLIENT}` already carries `--database=${CLICKHOUSE_DATABASE}`
from `shell_config.sh`. Adding a second `--database "${DB_A}"` makes
the client error with `option '--database' cannot be specified more
than once`. Use the `sed`-rewrite pattern that
`01160_table_dependencies.sh` uses to point the existing flag at the
new database.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replace the post-`executeQuery` `ASTResetSessionQuery` sniff in `TCPHandler`
with a generic callback API on `Context`. Protocol handlers register a
closure at handshake time; `Context::resetToUserDefaults` fires them after
applying the reset.

`TCPHandler` reuses the callback to re-`extractConnectionSettingsFromContext`
(`idle_connection_timeout`, `send_timeout`, `receive_timeout`, `poll_interval`,
etc.), which previously needed the AST sniff and forced every reset path to
think about the TCP cache. `MySQLHandler` now clears `prepared_statements`
and refreshes the Poco socket's send / receive timeouts. `PostgreSQLHandler`
resets `prepared_statements_manager` to a fresh instance so names registered
via `PREPARE` are dropped along with the rest of the session.

Also apply `settings_from_auth_server` on the newly-created branch of the
named-session path in `Session::makeSessionContext`, matching the unnamed
path. Otherwise a fresh named session would have settings that
`RESET SESSION` later replays, breaking idempotency on a clean session.

`InterpreterResetSessionQuery::supportsTransactions` now returns `true` so
`executeQuery`'s `throw_on_unsupported_query_inside_transaction` gate lets
us through to `Context::resetToUserDefaults`, which is where the actual
in-transaction rejection lives.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The previous shape captured a `session_context` `shared_ptr` inside each
registered closure to reach `Settings` after reset. The callback list lives
on `Context`, so a `shared_ptr` to that same `Context` kept inside the
closures it owns would pin the `Context` forever — a reference cycle.

Pass the session `Context` by reference into each callback instead. Callers
read `Settings` directly off the argument. `extractConnectionSettingsFromContext`
in `TCPHandler` now takes `const Context &` (it only ever needed
`getSettingsRef`); existing callers dereference their `ContextPtr` at the
boundary.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
…exemption

Two issues spotted on the callback rollout in the latest AI review round
(ClickHouse#105962):

- `Context::resetToUserDefaults` swallowed callback exceptions. A handler
  that failed to drop its protocol-local state (e.g. clearing prepared
  statements) would still leave `RESET SESSION` looking successful, and a
  pool that takes that as a signal to hand the connection out as "clean"
  would silently re-leak the same state. Run every callback regardless,
  but capture the first exception and rethrow it after the loop.

- `executeQuery` wraps non-`ASTTransactionControl` queries in an implicit
  transaction when `implicit_transaction = 1` is set. With `RESET SESSION`
  going through that path, the in-transaction guard inside
  `resetToUserDefaults` would immediately reject the reset — and worse,
  prevent `RESET SESSION` from ever clearing the very `implicit_transaction`
  setting that caused the wedge. Exempt `ASTResetSessionQuery` from the
  implicit-transaction wrapping (alongside the existing `ASTTransactionControl`
  exemption) and pin the behaviour with `04039_reset_session_implicit_transaction`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
alex-clickhouse and others added 2 commits May 29, 2026 20:07
… MySQL

Three review findings:

- `Context::resetToUserDefaults` was not fail-close: the fallible auth-server
  replay (e.g. a `profile` that was dropped after login) ran only after the
  user, roles, settings and profiles had already been swapped, leaving a
  half-reset session on failure. Reorder so the replay — the only step that can
  throw — runs right after the settings/profile swap, before any other live
  mutation, and roll settings/profiles back on failure. The replay does not
  depend on the restored user/roles, so the reorder is safe.

- `Session::makeSessionContext` published a freshly-created named session in the
  storage via `acquireSession` before initializing it. A throw during
  initialization (`setUser`, or the auth-server replay) left a half-built
  session whose `tryGetUser` succeeds, so a later request reusing the same
  `session_id` skipped applying the auth settings. Guard the initialization and
  remove a newly-created session from the storage on failure, and move the
  `RESET SESSION` auth snapshot into the same guarded block so the session is
  fully prepared before it is published.

- Make `RESET SESSION` a no-op over the MySQL wire protocol as well, matching
  PostgreSQL: the MySQL handler keeps protocol-local state (handshake database,
  prepared statements) outside the session context, so a session-context reset
  would move the connection off its post-handshake baseline. Added a MySQL
  no-op integration test and updated the docs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`Settings` has no move assignment, so `*settings = std::move(...)` is a copy
and `performance-move-const-arg` rejects it under -warnings-as-errors. Assign
directly, matching the existing `*settings = settings_` idiom in this file.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/Context.cpp Resolved
alex-clickhouse and others added 2 commits June 1, 2026 12:08
…sionQuery

The register function is only forward-declared in registerInterpreters.cpp, so
when InterpreterResetSessionQuery.cpp is compiled outside the unity build its
definition has no visible prototype and -Wmissing-prototypes fails under
-Werror. Repeat the forward declaration in this translation unit.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…l roles

`Context::resetToUserDefaults` re-applied the externally-granted roles
(LDAP / interserver) on the session context and set `need_recalculate_access`,
but the next query context is built with `Context::createCopy`, whose copy
constructor copies `access` and `current_roles` but not `external_roles`. With
the session left needing recalculation, the query context recomputed its access
from the copied state and dropped the restored external roles, so a session that
authenticated with them could still lose those privileges after `RESET SESSION`.

Bake the access into the session context at the end of the reset (calling
`getAccess`, as `Session::makeSessionContext` does after `setUser`), so the
cached access — which includes the external roles — is what query-context copies
inherit. A focused regression would need interserver/LDAP role mapping across a
cluster to populate `external_roles`, so none is added here.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alex-clickhouse and others added 4 commits June 1, 2026 13:11
`cppcoreguidelines-init-variables` (run with -warnings-as-errors in the ARM
tidy build) flags `is_session_context` and `inside_transaction` as declared
without an initializer. They are always assigned inside the shared-lock block
before use, but initialize them to `false` to satisfy the check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The dropped-database block created a hardcoded global database
`reset_session_db_to_drop` and dropped it with a bare `DROP DATABASE`. The
flaky check runs the test many times concurrently against one server, so
parallel copies collided: `CREATE DATABASE` failed with
`DATABASE_ALREADY_EXISTS` and the bare `DROP DATABASE` failed with
`UNKNOWN_DATABASE`. Use the per-test-unique `{CLICKHOUSE_DATABASE_1:Identifier}`
name so concurrent runs don't share a database. The `RESET SESSION` behaviour
under test is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lel-replicas

The test opens a transaction and does `INSERT ... VALUES` then an in-transaction
`SELECT count()`. Under the AsyncInsert CI profile the insert fails with
`NOT_IMPLEMENTED: Async inserts inside transactions are not supported`; under the
ParallelReplicas profile the in-transaction count reads inconsistently (observed
3 instead of 1). Transactions don't compose with either mode, so add
`no-async-insert` and `no-parallel-replicas`, matching existing transaction
tests (e.g. 04059/04060 use `no-parallel-replicas`).

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105962&sha=132d14c51bef6e76fb77e81f911880df13975f06&name_0=PR

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The coverage report flagged `ASTResetSessionQuery::formatImpl` (and the trivial
`getID`/`clone`) as uncovered. Add `SELECT formatQuery('RESET SESSION')` so the
statement round-trips through the parser and AST formatter, exercising that path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 300/335 (89.55%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 11 line(s) · Uncovered code

Full report · Diff report

@alex-clickhouse
alex-clickhouse marked this pull request as ready for review June 2, 2026 13:53
@alex-clickhouse
alex-clickhouse requested review from azat and kssenii June 2, 2026 13:53
@alex-clickhouse

Copy link
Copy Markdown
Contributor Author

@ClickHouse/integrations ptal

@tavplubix tavplubix left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it should be implemented as a special packet/flag in the native protocol, not as a SQL query, so the TCPHandler would simply reset the whole context without changing other components

@tavplubix

Copy link
Copy Markdown
Member

Also, could you please provide more details about the usecase? I understand that it's a useful optimization to avoid re-establishing TCP connections, but I'm wondering how useful it is on real workloads: for example, do you have some benchmarks demonstaring the performance improvements?

@abashkeev abashkeev added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 4, 2026
@ringerc

ringerc commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

@groeneai In a session where session-level privileges have been dropped via EXECUTE AS ... without a SQL statement, does RESET SESSION restore the session to the original user from before EXECUTE AS ?

If so, this is a likely security hole. It should raise the same error that other attempts to escape EXECUTE AS raise instead.

In my opinion such sessions should not be resettable.

If it's protocol-level only that's probably less bad, because we assume the client in control of the protocol is trusted, and they're just running less-trusted SQL. I'm still not convinced it's safe though and it needs some careful thought at least.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Yes. On this PR's head (f062c9c), RESET SESSION after a session-form EXECUTE AS target returns the session to the authenticated user, and no privilege is checked: InterpreterResetSessionQuery::execute calls resetToUserDefaults(), which restores the user pinned at login (authenticated_user_id). The PR's own test 04041_reset_session_execute_as asserts exactly this and passed in this PR's CI: target has no grants, yet after RESET SESSION currentUser() is the authenticated user again. The direct way back, EXECUTE AS <authenticated user> run as target, fails on master with Code: 497 (ACCESS_DENIED, no IMPERSONATE).

It is not protocol-level. RESET SESSION is an ordinary SQL statement, so the less-trusted SQL can send it on every interface where it runs (it is a no-op only over MySQL and PostgreSQL).

The restore exists so that a pooled connection does not silently stay impersonated (the test's comment says so). Refusing the reset while impersonating, with the same IMPERSONATE check on the authenticated user, keeps that property: the pool gets an error and reconnects, as it already has to over MySQL and PostgreSQL.

@ringerc

ringerc commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

@alex-clickhouse I think this has a design/security issue with EXECUTE AS per my comment here #105962 (comment)

Allowing SQL-level RESET SESSION to restore privileges dropped by EXECUTE AS defeats the defense that EXECUTE AS has against using another EXECUTE AS to re-gain dropped privileges. It means that EXECUTE AS longer serves as a one-way permission dropping latch that makes it safe to use a session to run less-trusted SQL.

If this is merged, a proxy/supervisor has to watch the SQL passed through on the ClickHouse session and try to filter out RESET SESSION by text-matching it. Which is very weak, as attackers can no doubt find plenty of ways to obfuscate it.

(This is the same big security gap PostgreSQL has when trying to use SET ROLE or SET SESSION AUTHORIZATION to drop privileges - it's easily escaped with a RESET ROLE. RESET SESSION AUTHORIZATION or DISCARD ALL.)

@alex-clickhouse

Copy link
Copy Markdown
Contributor Author

This PR is closed. #123914 replaces it with a different approach: a ResetSession packet of the native protocol instead of the SQL statement RESET SESSION, as tavplubix asked.

The issues from this review are solved there:

  • EXECUTE AS (comment): SQL cannot send the packet, so the SQL that runs in a session cannot use it to undo EXECUTE AS. Also, the server rejects the reset with ACCESS_DENIED while the session runs as a user other than the authenticated user. The session does not change, and the client must open a new connection, which needs the credentials. SQL Server has the same rule (error 18059). SET readonly and SET allow_ddl = 0 are also one-way for SQL, because SQL cannot send the packet. A reset gives them the values from the profile, the same values that a new login of the user gets.
  • Benchmark: the description of Add the ResetSession packet to the native protocol #123914 has the numbers. The reset takes one round trip, a plain reconnect takes two and a TLS reconnect takes three.
  • Earlier review points about the SQL statement (readonly over HTTP GET, the MySQL and PostgreSQL interfaces, a partly reset session after an error): these do not apply. Only the native TCP protocol has the packet. The server makes the new context before it replaces the old one, so after an error the session does not change.

The section "EXECUTE AS and other one-way changes" in the description of #123914 has the details.

@ringerc

ringerc commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Thanks @alex-clickhouse for considering that concern. Much appreciated.

(As a side-note) re round-trips, have you seen the work I started off on PostgreSQL's libpq regarding protocol-pipelining? It can make a huge difference for apps. Worth looking into whether something similar is possible in CH?

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-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants