Skip to content

Commit 93f26c3

Browse files
committed
Cancel the query again when psycopg closed the connection mid-cancel
Since psycopg 3.3.9 a second Ctrl-C during its cancel closes the connection (psycopg #1435) instead of leaving it busy. recover_from_interrupt() saw a closed connection and did nothing, so the query kept running on the server until it next sent data to the client. The cancel key libpq gives at connect time (PQgetCancel) still reaches the backend after the connection is closed: pgcli saves it on every connect and sends it once in that case, in a thread bounded to 2 s with Ctrl-C ignored. Checked end to end through a link with 150 ms of latency: two Ctrl-C 0.15 s or 0.4 s apart leave no pg_sleep running, with psycopg 3.3.8 and 3.3.9.
1 parent 5531b5a commit 93f26c3

4 files changed

Lines changed: 114 additions & 5 deletions

File tree

‎changelog.rst‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ Bug fixes:
2626
cancels again and reads the reply, and if the server does not answer within
2727
5 seconds, or yet another Ctrl-C arrives, it cancels (ignoring Ctrl-C for
2828
the at most 2 seconds that takes, so the query never outlives the session)
29-
and closes the connection so the next statement reconnects.
29+
and closes the connection so the next statement reconnects. Since psycopg
30+
3.3.9 the second Ctrl-C makes psycopg close the connection itself, which
31+
left the query running on the server; pgcli then cancels it with the key
32+
libpq gave when connecting, which still reaches the backend.
3033

3134
Internal:
3235
---------

‎pgcli/main.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1464,7 +1464,23 @@ def _recover_from_interrupt(self):
14641464
except KeyboardInterrupt:
14651465
self.pgexecute.abandon_connection()
14661466
outcome = "closed"
1467-
if outcome == "closed":
1467+
if outcome == "recancelled":
1468+
self.logger.debug("psycopg closed the connection mid-cancel; cancel sent again")
1469+
click.secho(
1470+
"The connection was closed while the query was being cancelled; the cancel has been sent "
1471+
"again. The next statement reconnects.",
1472+
err=True,
1473+
fg="red",
1474+
)
1475+
elif outcome == "lost":
1476+
self.logger.debug("psycopg closed the connection mid-cancel; the cancel could not be sent")
1477+
click.secho(
1478+
"The connection was closed while the query was being cancelled, and the query may still be "
1479+
"running on the server. The next statement reconnects.",
1480+
err=True,
1481+
fg="red",
1482+
)
1483+
elif outcome == "closed":
14681484
self.logger.debug("Connection closed after an interrupted query")
14691485
click.secho(
14701486
"The connection was still busy after the cancel and has been closed. If the cancel did not "

‎pgcli/pgexecute.py‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
import select
55
import signal
6+
import threading
67
import time
78
import traceback
89
from collections import namedtuple
@@ -76,6 +77,15 @@ def _sigint_ignored():
7677
signal.signal(signal.SIGINT, previous if previous is not None else signal.default_int_handler)
7778

7879

80+
def _cancel_handle_of(conn):
81+
"""libpq's cancel key for ``conn``'s backend, or None if it has none."""
82+
try:
83+
return conn.pgconn.get_cancel()
84+
except Exception as e:
85+
_logger.debug("No cancel key for the connection: %r", e)
86+
return None
87+
88+
7989
class ProtocolSafeCursor(psycopg.Cursor):
8090
"""This class wraps and suppresses Protocol Errors with pgbouncer database.
8191
See https://github.com/dbcli/pgcli/pull/1097.
@@ -192,6 +202,8 @@ def __init__(
192202
self._conn_params = {}
193203
self._is_virtual_database = None
194204
self.conn = None
205+
# libpq's cancel key for self.conn's backend; see send_saved_cancel().
206+
self._cancel_handle = None
195207
self.dbname = None
196208
self.user = None
197209
self.password = None
@@ -258,6 +270,8 @@ def connect(
258270
self.conn.close()
259271
self.conn = conn
260272
self.conn.autocommit = True
273+
# Taken while the connection is open: psycopg may close it mid-cancel.
274+
self._cancel_handle = _cancel_handle_of(conn)
261275

262276
if self.notify_callback is not None:
263277
self.conn.add_notify_handler(self.notify_callback)
@@ -481,10 +495,22 @@ def recover_from_interrupt(self, timeout=5.0):
481495
Returns "idle" when the connection was not busy, "drained" once the
482496
query is cancelled and its reply read, or "closed" when the server did
483497
not answer within ``timeout`` and the connection had to be given up,
484-
so that the next statement reconnects.
498+
so that the next statement reconnects. When psycopg already closed the
499+
connection, returns "recancelled" once the cancel saved at connect
500+
time went out, or "lost" if it could not be sent.
485501
"""
486502
conn = self.conn
487-
if conn is None or conn.closed or conn.info.transaction_status != psycopg.pq.TransactionStatus.ACTIVE:
503+
if conn is None:
504+
return "idle"
505+
if conn.closed:
506+
# psycopg >= 3.3.9 closes the connection itself when a second
507+
# Ctrl-C interrupts its cancel (psycopg #1435). The connection can
508+
# no longer cancel anything, and the server only notices the
509+
# client is gone when it next sends data.
510+
if self._cancel_handle is None:
511+
return "idle"
512+
return "recancelled" if self.send_saved_cancel() else "lost"
513+
if conn.info.transaction_status != psycopg.pq.TransactionStatus.ACTIVE:
488514
return "idle"
489515
try:
490516
# cancel_safe() is psycopg >= 3.2; cancel() blocks but works on 3.0.
@@ -509,7 +535,10 @@ def abandon_connection(self, timeout=2.0):
509535
``timeout`` seconds the cancel takes, so it always goes out.
510536
"""
511537
conn = self.conn
512-
if conn is None or conn.closed:
538+
if conn is None:
539+
return
540+
if conn.closed:
541+
self.send_saved_cancel(timeout)
513542
return
514543
try:
515544
if conn.info.transaction_status == psycopg.pq.TransactionStatus.ACTIVE:
@@ -524,6 +553,33 @@ def abandon_connection(self, timeout=2.0):
524553
finally:
525554
conn.close()
526555

556+
def send_saved_cancel(self, timeout=2.0):
557+
"""Cancel the backend's query with the key saved at connect time.
558+
559+
It still works once the connection is closed. Ctrl-C is ignored while
560+
it is sent, for at most ``timeout`` seconds; the key is used only once,
561+
since the backend goes away with the closed connection. Returns True
562+
if the cancel request went out.
563+
"""
564+
handle, self._cancel_handle = self._cancel_handle, None
565+
if handle is None:
566+
return False
567+
sent = threading.Event()
568+
569+
def send():
570+
try:
571+
handle.cancel()
572+
sent.set()
573+
except Exception as e:
574+
_logger.debug("Cancel with the saved key failed: %r", e)
575+
576+
# In a thread because libpq's cancel blocks with no timeout of its own.
577+
thread = threading.Thread(target=send, name="pgcli-cancel", daemon=True)
578+
with _sigint_ignored():
579+
thread.start()
580+
thread.join(timeout)
581+
return sent.is_set()
582+
527583
def _drain_results(self, timeout):
528584
"""Read and discard the reply of the query in flight.
529585

‎tests/test_cancel_recovery.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,40 @@ def _still_running(connection, pid):
6767
return True
6868

6969

70+
def _leave_query_running_and_closed(executor):
71+
"""Put the connection where psycopg >= 3.3.9 leaves it after a second Ctrl-C.
72+
73+
psycopg now closes the connection when its cancel is interrupted (psycopg
74+
#1435), so it is no longer busy but cannot cancel anything either, and the
75+
server keeps running the query until it next sends the client data.
76+
"""
77+
executor.conn.pgconn.send_query(b"select pg_sleep(30)")
78+
executor.conn.pgconn.finish()
79+
raise KeyboardInterrupt
80+
81+
82+
@dbtest
83+
def test_query_is_cancelled_when_psycopg_closed_the_connection(executor, connection):
84+
cli = PGCli(pgexecute=executor)
85+
cli.auto_retry_closed_connection = True
86+
pid = executor.conn.info.backend_pid
87+
88+
with patch.object(cli, "_evaluate_command", side_effect=lambda text: _leave_query_running_and_closed(executor)):
89+
cli.execute_command("select pg_sleep(30)")
90+
91+
assert not _still_running(connection, pid)
92+
cli.execute_command("select 1")
93+
output, query = cli._evaluate_command("select 40 + 2 as answer")
94+
assert query.successful
95+
96+
97+
@dbtest
98+
def test_saved_cancel_key_is_used_once(executor):
99+
executor.conn.pgconn.finish()
100+
assert executor.send_saved_cancel()
101+
assert not executor.send_saved_cancel()
102+
103+
70104
@dbtest
71105
def test_another_ctrl_c_during_the_recovery_closes_the_connection(executor, connection):
72106
cli = PGCli(pgexecute=executor)

0 commit comments

Comments
 (0)