From 04a3e8c116c80daf0ebb917029e7433177313be6 Mon Sep 17 00:00:00 2001
From: Sehrope Sarkuni <sehrope@jackdb.com>
Date: Sat, 23 May 2026 09:59:45 -0400
Subject: [PATCH 3/6] libpq: expose connect deadline on PGconn

Mirror the per-host connect_timeout deadline (end_time) tracked locally
in pqConnectDBComplete() onto the PGconn struct as connect_deadline.
Initialized to -1 (no deadline) by pqMakeEmptyPGconn(), set whenever the
local end_time is computed for a new host attempt, and reset to -1 on
each new connection attempt.

This exposes no new behavior on its own, but lets code reached during
connection establishment, such as authentication paths, consult the
deadline of the in-flight attempt.
---
 src/interfaces/libpq/fe-connect.c | 8 ++++++++
 src/interfaces/libpq/libpq-int.h  | 8 ++++++++
 2 files changed, 16 insertions(+)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 4272d386e64..b766013971e 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -2807,6 +2807,12 @@ pqConnectDBComplete(PGconn *conn)
 	if (conn == NULL || conn->status == CONNECTION_BAD)
 		return 0;
 
+	/*
+	 * Clear any stale deadline from a previous invocation before deciding
+	 * whether this attempt installs one.
+	 */
+	conn->connect_deadline = -1;
+
 	/*
 	 * Set up a time limit, if connect_timeout is greater than zero.
 	 */
@@ -2836,6 +2842,7 @@ pqConnectDBComplete(PGconn *conn)
 			 conn->whichaddr != last_whichaddr))
 		{
 			end_time = PQgetCurrentTimeUSec() + (pg_usec_time_t) timeout * 1000000;
+			conn->connect_deadline = end_time;
 			last_whichhost = conn->whichhost;
 			last_whichaddr = conn->whichaddr;
 		}
@@ -5042,6 +5049,7 @@ pqMakeEmptyPGconn(void)
 	conn->show_context = PQSHOW_CONTEXT_ERRORS;
 	conn->sock = PGINVALID_SOCKET;
 	conn->altsock = PGINVALID_SOCKET;
+	conn->connect_deadline = -1;
 	conn->Pfdebug = NULL;
 
 	/*
diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h
index 461b39620c3..0f8696e032d 100644
--- a/src/interfaces/libpq/libpq-int.h
+++ b/src/interfaces/libpq/libpq-int.h
@@ -484,6 +484,14 @@ struct pg_conn
 	int			whichhost;		/* host we're currently trying/connected to */
 	pg_conn_host *connhost;		/* details about each named host */
 	char	   *connip;			/* IP address for current network connection */
+	/*
+	 * Deadline for the in-progress connection attempt against the current
+	 * host, in PQgetCurrentTimeUSec() units; -1 if no connect_timeout is in
+	 * effect.  This mirrors the local end_time tracked in
+	 * pqConnectDBComplete() so that code paths invoked during connection
+	 * establishment (e.g. authentication) can consult the deadline.
+	 */
+	pg_usec_time_t connect_deadline;
 
 	/*
 	 * The pending command queue as a singly-linked list.  Head is the command
-- 
2.43.0

