Skip to content

Reconnect PostgreSQL after the server drops the connection - #236

Merged
tina4stack merged 1 commit into
v3from
fix/postgres-reconnect-dead-connection
Oct 19, 2026
Merged

tina4stack merged 1 commit into
v3from
fix/postgres-reconnect-dead-connection

Conversation

@M1gael

@M1gael M1gael commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator

After the PostgreSQL server drops a connection (failover, idle-session reap, pg_terminate_backend), the adapter keeps the dead psycopg2 connection and every later query fails with connection already closed until the process is restarted. This was seen in production on 3.13.52 after a database failover.

Change (tina4_python/database/postgres.py)

  • connect() stores its arguments.
  • When a statement fails and psycopg2 has marked the connection closed, the adapter opens a new connection from those arguments.
  • The failed statement is retried once, only when no explicit transaction was open and the connection held no uncommitted work. Otherwise the error reaches the caller and the next statement runs on the new connection.
  • Same approach as the Firebird adapter's dead-connection handling.

Not carried over: session state set with SET after connecting (connect options are).

Tests: tests/test_postgres_reconnect_after_drop.py runs against a live PostgreSQL, with the drop done by a real pg_terminate_backend. 5 of its 6 tests fail on v3 and all pass with this change. The existing PostgreSQL tests give the same results before and after.

A failover, an idle-session reap or pg_terminate_backend closes the
connection under a running app. The adapter kept the dead psycopg2
connection, so every later query raised "connection already closed"
until the process was restarted.

The adapter now keeps its connect arguments and, when psycopg2 has
marked the connection closed, opens a new one. The statement that hit
the dropped link is retried once, but only when no explicit transaction
was open and no uncommitted work was pending. Otherwise the caller sees
the error and the next statement runs on the new connection. This
mirrors the Firebird adapter's dead-connection handling.

Session state set with SET after connecting does not carry over to the
new connection; connect options do.

Signed-off-by: Michael <michael@codeinfinity.co.za>
@M1gael

M1gael commented Oct 15, 2026

Copy link
Copy Markdown
Collaborator Author

I have read the Tina4 Contributor Licence Agreement and I agree to it.

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.

3 participants