From 99feadabcfea04a2f0bbc82fe8606eeb11f1ee47 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Mon, 5 Oct 2026 22:03:19 +0200
Subject: [PATCH v2 4/5] libpq: On Windows, read pending input before sending a
 new query

When a backend sends a FATAL error it closes the connection, which means
the server's OS answers any new data it receives with an RST. Annoyingly
Winsock discards all unread data when it receives an RST... So on
Windows the client often only reports "server closed the connection
unexpectedly" instead of the actual error, as reported in bug #15598[1].

This fixes that for idle connections receiving a FATAL, by first moving
any data that was received while idle into libpq's buffer before sending
a query on the connection. This isn't a complete fix, since a race is
still possible: e.g. a FATAL arriving just after the pending data was
read into libpq's buffer. There's no way to avoid such races completely
though, and this does help in a common case.

[1]: https://www.postgresql.org/message-id/15598-e3fec9d8c5184936%40postgresql.org
---
 src/bin/psql/t/001_basic.pl      | 36 ++++++++++++
 src/interfaces/libpq/fe-exec.c   | 33 +++++++++++
 src/test/ssl/meson.build         |  1 +
 src/test/ssl/t/005_idle_fatal.pl | 97 ++++++++++++++++++++++++++++++++
 4 files changed, 167 insertions(+)
 create mode 100644 src/test/ssl/t/005_idle_fatal.pl

diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index 028df33ce8a..0f6c5d3c052 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -151,6 +151,42 @@ psql:<stdin>:2: server closed the connection unexpectedly
 psql:<stdin>:2: error: connection to server was lost/,
 	'server crash: error message');
 
+# Terminate the backend of an idle psql session from another session, then
+# send a query.  The FATAL message is already waiting in the client's socket
+# buffer when psql sends that query.  On Windows, the reset the dead peer
+# answers our send with used to make the OS discard that buffered message, so
+# the server's own error never reached the user.
+my $idle_timeout = IPC::Run::timer($PostgreSQL::Test::Utils::timeout_default);
+my ($idle_stdin, $idle_stdout, $idle_stderr) = ('', '', '');
+my $idle_psql = IPC::Run::start(
+	[
+		'psql', '--no-psqlrc', '--quiet', '--no-align', '--tuples-only',
+		'--file' => '-',
+		'--dbname' => $node->connstr('postgres')
+	],
+	'<' => \$idle_stdin,
+	'>' => \$idle_stdout,
+	'2>' => \$idle_stderr,
+	$idle_timeout);
+
+$idle_stdin .= "SELECT pg_backend_pid();\n";
+pump_until($idle_psql, $idle_timeout, \$idle_stdout,
+	qr/[[:digit:]]+[\r\n]$/m);
+my $idle_pid = $idle_stdout;
+chomp $idle_pid;
+
+$node->safe_psql('postgres',
+	"SELECT pg_terminate_backend($idle_pid, 180000)");
+
+$idle_stdin .= "SELECT 1;\n";
+pump_until($idle_psql, $idle_timeout, \$idle_stderr,
+	qr/connection to server was lost/);
+$idle_psql->finish;
+like(
+	$idle_stderr,
+	qr/FATAL:  terminating connection due to administrator command/,
+	'FATAL while idle: server message reported');
+
 # test \errverbose
 #
 # (This is not in the regular regression tests because the output
diff --git a/src/interfaces/libpq/fe-exec.c b/src/interfaces/libpq/fe-exec.c
index 294690648bd..b3b6c70a2e2 100644
--- a/src/interfaces/libpq/fe-exec.c
+++ b/src/interfaces/libpq/fe-exec.c
@@ -1747,6 +1747,39 @@ PQsendQueryStart(PGconn *conn, bool newQuery)
 	}
 	else
 	{
+#ifdef WIN32
+
+		/*
+		 * The server may have sent us something while we were idle, most
+		 * importantly a FATAL error just before it closed the connection
+		 * (e.g. due to idle_in_transaction_session_timeout or
+		 * pg_terminate_backend()).  If so, sending our query will make the
+		 * server's OS answer with an RST, and when Winsock receives an RST it
+		 * discards any data we have not read yet.  So pull whatever is
+		 * available into our own buffer before sending.  We don't parse it
+		 * here: it gets processed along with this command's results, just as
+		 * it would be on other platforms where the data survives the RST.
+		 *
+		 * This only helps if the server closed its socket gracefully.  If it
+		 * didn't, as with servers older than PostgreSQL 20, Windows sends the
+		 * RST as soon as the backend exits, and the data is already gone
+		 * before we get here.
+		 *
+		 * We only do this when the connection is idle and not in pipeline
+		 * mode, which is the case where a FATAL from the server is most
+		 * likely to be sitting unread: if results are pending, the
+		 * application will normally be reading them anyway.  Doing it on
+		 * every send instead would cost an extra recv() call per flush, which
+		 * pipeline mode and COPY are particularly sensitive to.  It would
+		 * also remove TCP backpressure, letting unread result data pile up in
+		 * our input buffer without bound.  On an idle connection the only
+		 * thing that can be waiting is a few asynchronous messages, and this
+		 * command's result processing will consume those right away.
+		 */
+		if (conn->asyncStatus == PGASYNC_IDLE && pqReadData(conn) < 0)
+			return false;
+#endif
+
 		/*
 		 * This command's results will come in immediately. Initialize async
 		 * result-accumulation state
diff --git a/src/test/ssl/meson.build b/src/test/ssl/meson.build
index d7e7ce23433..190448ec3b6 100644
--- a/src/test/ssl/meson.build
+++ b/src/test/ssl/meson.build
@@ -14,6 +14,7 @@ tests += {
       't/002_scram.pl',
       't/003_sslinfo.pl',
       't/004_sni.pl',
+      't/005_idle_fatal.pl',
     ],
   },
 }
diff --git a/src/test/ssl/t/005_idle_fatal.pl b/src/test/ssl/t/005_idle_fatal.pl
new file mode 100644
index 00000000000..a0118e16b95
--- /dev/null
+++ b/src/test/ssl/t/005_idle_fatal.pl
@@ -0,0 +1,97 @@
+
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that a FATAL error sent to an idle SSL connection reaches the client.
+#
+# On Windows, the client's TCP stack discards unread data when it receives a
+# reset, so this depends on the backend closing its socket gracefully and on
+# libpq reading pending input before sending its next query.  Doing that
+# through TLS adds the close_notify exchange to the mix, so test it
+# separately for each protocol version, as TLS 1.3 handles closure
+# differently than TLS 1.2.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+use FindBin;
+use lib $FindBin::RealBin;
+
+use SSL::Server;
+
+if ($ENV{with_ssl} ne 'openssl')
+{
+	plan skip_all => 'OpenSSL not supported by this build';
+}
+if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bssl\b/)
+{
+	plan skip_all =>
+	  'Potentially unsafe test SSL not enabled in PG_TEST_EXTRA';
+}
+
+my $ssl_server = SSL::Server->new();
+
+my $SERVERHOSTADDR = '127.0.0.1';
+my $SERVERHOSTCIDR = '127.0.0.1/32';
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+
+# PGHOST is enforced here to set up the node, subsequent connections
+# will use a dedicated connection string.
+$ENV{PGHOST} = $node->host;
+$ENV{PGPORT} = $node->port;
+$node->start;
+
+$ssl_server->configure_test_server_for_ssl($node, $SERVERHOSTADDR,
+	$SERVERHOSTCIDR, 'trust');
+$ssl_server->switch_server_cert($node, certfile => 'server-cn-only');
+
+# The pg_hba.conf set up above only allows SSL connections over TCP, so the
+# session terminating the idle backend has to use SSL as well.
+my $connstr =
+	"sslkey=invalid sslcert=invalid sslrootcert=ssl/root+server_ca.crt "
+  . "sslcrl=invalid sslcrldir=invalid sslmode=require dbname=trustdb "
+  . "hostaddr=$SERVERHOSTADDR host=localhost user=ssltestuser";
+
+foreach my $version ('TLSv1.2', 'TLSv1.3')
+{
+	my $version_connstr = "$connstr ssl_min_protocol_version=$version "
+	  . "ssl_max_protocol_version=$version";
+
+	my $timeout = IPC::Run::timer($PostgreSQL::Test::Utils::timeout_default);
+	my ($stdin, $stdout, $stderr) = ('', '', '');
+	my $psql = IPC::Run::start(
+		[
+			'psql', '--no-psqlrc', '--quiet', '--no-align', '--tuples-only',
+			'--file' => '-',
+			'--dbname' => $version_connstr
+		],
+		'<' => \$stdin,
+		'>' => \$stdout,
+		'2>' => \$stderr,
+		$timeout);
+
+	$stdin .=
+	  "SELECT pid || ' ' || version FROM pg_stat_ssl WHERE pid = pg_backend_pid();\n";
+	pump_until($psql, $timeout, \$stdout, qr/^\d+ TLS\S+[\r\n]/m);
+	my ($pid, $used_version) = split ' ', $stdout;
+	is($used_version, $version, "$version: connection uses $version");
+
+	$node->safe_psql(
+		'trustdb',
+		"SELECT pg_terminate_backend($pid, 180000)",
+		connstr => $connstr);
+
+	$stdin .= "SELECT 1;\n";
+	pump_until($psql, $timeout, \$stderr, qr/connection to server was lost/);
+	$psql->finish;
+	like(
+		$stderr,
+		qr/FATAL:  terminating connection due to administrator command/,
+		"$version: FATAL while idle is reported");
+}
+
+done_testing();
-- 
2.56.1

