Skip to content

Client connection reuse and server-side query cancellation#152

Open
joe-clickhouse wants to merge 2 commits intomainfrom
joe/client-reuse-improvements
Open

Client connection reuse and server-side query cancellation#152
joe-clickhouse wants to merge 2 commits intomainfrom
joe/client-reuse-improvements

Conversation

@joe-clickhouse
Copy link
Collaborator

@joe-clickhouse joe-clickhouse commented Mar 25, 2026

Summary

The goal of this PR is to harden the MCP server for heavy, sustained usage by reusing client connections, adding real server-side query cancellation, and preventing worker thread pool exhaustion from zombie queries.

  • Connection reuse: Cache clickhouse_connect clients by config key instead of creating a new client on every tool call. Eliminates hundreds of ms of overhead per call that a significant contributor to intermittent timeouts under sustained use.
  • Server-side query cancellation: Assign a query_id to every query and issue KILL QUERY on timeout instead of the no-op future.cancel(). Timed-out queries no longer continue running as zombies consuming worker threads and ClickHouse server resources.
  • Timeout alignment: Auto-cap send_receive_timeout to query_timeout + 5, unless explicitly overridden so worker threads unblock shortly after the MCP timeout fires, preventing thread pool exhaustion.
  • Stale client eviction: Evict cached clients on connection errors and on failed liveness pings after idle. Read-only metadata calls like list_databases and list_tables retry once with a fresh client. run_query evicts but does not retry because writes could duplicate.
  • Config resolution fix: Resolve session config overrides on the request thread where FastMCP ContextVar is available before dispatching to the worker thread, fixing a latent bug where PR Client config override support via MCP Context Session states #115 overrides were silently missed inside the executor.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant