Skip to content

Implement Backend Query Cancellation and Backend Termination for PostgreSQL#5137

Merged
renecannao merged 8 commits intov3.0from
v3.0_pgsql_query_cancel_terminate_issue_5136
Oct 14, 2025
Merged

Implement Backend Query Cancellation and Backend Termination for PostgreSQL#5137
renecannao merged 8 commits intov3.0from
v3.0_pgsql_query_cancel_terminate_issue_5136

Conversation

@rahim-kanji
Copy link
Collaborator

Closes #5136

Add support for PostgreSQL query cancellation and backend termination
features to allow clients to cancel long-running queries and terminate
connections through the standard PostgreSQL protocol.

Features implemented:
- Intercept pg_backend_pid() queries and return ProxySQL session thread ID
- Intercept pg_terminate_backend() to terminate client connections asynchronously
- Intercept pg_cancel_backend() to cancel queries on backend connections
- Support Cancel Request protocol via separate connection with PID and secret key validation
- Return BackendKeyData message on successful authentication with session thread ID and unique cancel secret key

This enables clients to use standard PostgreSQL cancellation mechanisms
(pg_cancel_backend, pg_terminate_backend, and Cancel Request protocol)
while ProxySQL maintains proper session isolation and maps client requests
to appropriate backend connections.
@gemini-code-assist
Copy link

Summary of Changes

Hello @rahim-kanji, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances ProxySQL's PostgreSQL support by introducing robust mechanisms for backend query cancellation and connection termination. It addresses a long-standing issue by allowing users to interrupt long-running queries or forcibly close unresponsive connections, improving operational control and stability. The changes involve deep integration with PostgreSQL's native protocols, refactoring internal session management, and extending the admin interface to support these new capabilities.

Highlights

  • PostgreSQL Backend Kill Mechanism: Introduced a new, unified backend kill mechanism capable of both cancelling queries and terminating connections for PostgreSQL. This replaces the previous PgSQL_CancelQueryArgs with a more versatile PgSQL_Backend_Kill_Args structure and PgSQL_backend_kill_thread function.
  • Query Cancellation Support: Implemented support for PostgreSQL's native query cancellation protocol. Clients can now send a PG_PKT_CANCEL startup packet with a backend PID and a secret key to cancel a running query. Additionally, SELECT pg_cancel_backend(<pid>) queries are intercepted and handled internally.
  • Connection Termination Support: Added functionality to terminate PostgreSQL backend connections. This includes handling KILL PGSQL CONNECTION <id> commands from the admin interface and intercepting SELECT pg_terminate_backend(<pid>) queries. Connections can also be terminated when they are destroyed from the pool if configured.
  • Secure Cancellation with Secret Keys: Integrated a cancel_secret_key into PostgreSQL sessions. This randomly generated key is sent to the client during the welcome phase and is required for authenticating native query cancellation requests, enhancing security.
  • Internal pg_backend_pid() Handling: ProxySQL now intercepts and responds to SELECT pg_backend_pid() queries internally, returning the session's thread ID without forwarding the query to the backend.
  • Refactored Session Interruption Logic: The internal kill queue mechanism (kq) has been refactored into PgSQL_Session_Interrupt_Queue_t and PgSQL_Session_Interrupt_t, allowing for more granular and secure handling of session and query interruption requests using both usernames and secret keys.
  • Improved Query Timeout and Cancellation Handling: Enhanced the main session handler to explicitly check for cancel_query flags alongside query timeouts and general session kills, ensuring prompt processing of cancellation requests and providing more descriptive warning messages.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a significant and valuable feature: the ability to cancel running queries and terminate backend connections for PostgreSQL. The implementation is comprehensive, touching multiple parts of the codebase to handle signaling, authentication of requests, and execution of the cancellation/termination. The refactoring of argument-passing structures and the use of modern C++ features like std::unique_ptr are commendable improvements.

My review focuses on a critical security vulnerability in the fallback key generation mechanism and a suggestion to improve code maintainability by reducing duplication. Addressing these points will further strengthen the implementation.

Centralize escaping/formatting of connection parameters (key='value').
Replace duplicate escape/append/free sequences in connect_start and PgSQL_backend_kill_thread.
@sonarqubecloud
Copy link

sonarqubecloud bot commented Oct 2, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
1 Security Hotspot

See analysis details on SonarQube Cloud

@renecannao renecannao merged commit c5a0a00 into v3.0 Oct 14, 2025
147 of 155 checks passed
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.

Implement Backend Query Cancellation and Backend Termination for PostgreSQL

2 participants