On Tue, 1 Dec 2026 at 08:26, Michael Paquier <[email protected]> wrote:
That's a new thing.

Agreed, and to be clear I don't want to block this thread on the later
patches I'm proposing. 0001 is a serious improvement on its own already,
and it's a prerequisite for the later ones.

Err, 0005, that controls with a GUC for how long a backend should stay
around to flush its information, feels like an unstable knob to me.
Let's assume that we do 0004, why would there be any need for 0005,
then?

0001 fixes the case where a client is waiting for a response and then
    gets a FATAL
0004 fixes the case where a client was idle and then wants to send
    something but in the meantime got a FATAL
0005 fixes the case where a client is actively sending something and
    during that send a FATAL happens. I added a test now to the patch
    to show such a case: TLS handshake on a busy client where the
    client cert is rejected by the server. Another example would be a
    somewhat short COPY IN stream that the client keeps writing to
    while a FATAL occurs.

The 0005 solution is indeed finicky, and I dislike it quite a lot. If
this is the only way to solve it, I'm not even sure if the solution is
worth it. But I don't really see another way. The Windows behaviour is
simply terrible: it's prone to these race conditions by design.

Perhaps it would be better for Jacob to comment here.  I was under
the impression that there was little need for more than 0003 in terms
of the tests, at least.

The (fairly simple) tests in 0004 fail consistently without the code
change in 0004.
From f0b0cfa98d95214de68985671108618fce9cc692 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Thu, 8 Oct 2026 20:10:21 +0000
Subject: [PATCH v3 1/5] Reapply "graceful shutdown" changes for Windows.

This reverts commit 29992a6a509b256efc4ac560a1586b51a64b2637.

a8458f508a7 closed the race that lost FD_CLOSE events, which was the
reason for the revert, so try again.
---
 src/backend/libpq/pqcomm.c | 29 ++++++++++++++++++++++-------
 1 file changed, 22 insertions(+), 7 deletions(-)

diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index 3704d121003..c0445f64546 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -377,15 +377,30 @@ socket_close(int code, Datum arg)
 		secure_close(MyProcPort);
 
 		/*
-		 * Formerly we did an explicit close() here, but it seems better to
-		 * leave the socket open until the process dies.  This allows clients
-		 * to perform a "synchronous close" if they care --- wait till the
-		 * transport layer reports connection closure, and you can be sure the
-		 * backend has exited.
+		 * On most platforms, we leave the socket open until the process dies.
+		 * This allows clients to perform a "synchronous close" if they care
+		 * --- wait till the transport layer reports connection closure, and
+		 * you can be sure the backend has exited.  Saves a kernel call, too.
 		 *
-		 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
-		 * though.
+		 * However, that does not work on Windows: if the kernel closes the
+		 * socket it will invoke an "abortive shutdown" that discards any data
+		 * not yet sent to the client.  (This is a flat-out violation of the
+		 * TCP RFCs, but count on Microsoft not to care about that.)  To get
+		 * the spec-compliant "graceful shutdown" behavior, we must invoke
+		 * closesocket() explicitly.  When using OpenSSL, it seems that clean
+		 * shutdown also requires an explicit shutdown() call.
+		 *
+		 * This code runs late enough during process shutdown that we should
+		 * have finished all externally-visible shutdown activities, so that
+		 * in principle it's good enough to act as a synchronous close on
+		 * Windows too.  But it's a lot more fragile than the other way.
 		 */
+#ifdef WIN32
+		shutdown(MyProcPort->sock, SD_SEND);
+		closesocket(MyProcPort->sock);
+#endif
+
+		/* In any case, set sock to PGINVALID_SOCKET to prevent further I/O */
 		MyProcPort->sock = PGINVALID_SOCKET;
 	}
 }
-- 
2.56.1

From 231a69aa88e40dad8b8bb9a791d72751af377fb4 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Thu, 8 Oct 2026 20:10:21 +0000
Subject: [PATCH v3 2/5] Revert "Skip isolation tests that terminate other
 backends on Windows"

This reverts commit e0f633ca6bc6a2ace3e6c0e79157c3bf0edddfbe.
---
 contrib/test_decoding/Makefile                |  8 +--
 contrib/test_decoding/meson.build             | 44 +++++++---------
 src/test/modules/injection_points/Makefile    |  7 +--
 src/test/modules/injection_points/meson.build | 50 ++++++++-----------
 4 files changed, 41 insertions(+), 68 deletions(-)

diff --git a/contrib/test_decoding/Makefile b/contrib/test_decoding/Makefile
index 45d859b72d7..c94bf860aa0 100644
--- a/contrib/test_decoding/Makefile
+++ b/contrib/test_decoding/Makefile
@@ -7,15 +7,9 @@ REGRESS = ddl xact rewrite toast permissions decoding_in_xact \
 	decoding_into_rel binary prepared replorigin time messages \
 	repack spill slot truncate stream stats twophase twophase_stream \
 	rowtypes_alter
-
-# slot_creation_error terminates another backend, whose FATAL message can be
-# lost on Windows, making the test unstable there.
-# See https://postgr.es/m/[email protected]
-SLOT_CREATION_TST = $(if $(filter win32,$(PORTNAME)),,slot_creation_error)
-
 ISOLATION = mxact delayed_startup ondisk_startup concurrent_ddl_dml \
 	oldest_xmin snapshot_transfer subxact_without_top concurrent_stream \
-	twophase_snapshot $(SLOT_CREATION_TST) catalog_change_snapshot \
+	twophase_snapshot slot_creation_error catalog_change_snapshot \
 	skip_snapshot_restore invalidation_distribution parallel_session_origin \
 	tuplecid_restart tuplecid_nested
 
diff --git a/contrib/test_decoding/meson.build b/contrib/test_decoding/meson.build
index aa57ff02c23..3117a629307 100644
--- a/contrib/test_decoding/meson.build
+++ b/contrib/test_decoding/meson.build
@@ -16,31 +16,6 @@ test_decoding = shared_module('test_decoding',
 )
 contrib_targets += test_decoding
 
-test_decoding_isolation = [
-  'mxact',
-  'delayed_startup',
-  'ondisk_startup',
-  'catalog_change_snapshot',
-  'concurrent_ddl_dml',
-  'oldest_xmin',
-  'snapshot_transfer',
-  'subxact_without_top',
-  'concurrent_stream',
-  'twophase_snapshot',
-  'skip_snapshot_restore',
-  'invalidation_distribution',
-  'parallel_session_origin',
-  'tuplecid_nested',
-  'tuplecid_restart',
-]
-
-# slot_creation_error terminates another backend, whose FATAL message can be
-# lost on Windows, making the test unstable there.
-# See https://postgr.es/m/[email protected]
-if host_system != 'windows'
-  test_decoding_isolation += 'slot_creation_error'
-endif
-
 tests += {
   'name': 'test_decoding',
   'sd': meson.current_source_dir(),
@@ -77,7 +52,24 @@ tests += {
     'runningcheck': false,
   },
   'isolation': {
-    'specs': test_decoding_isolation,
+    'specs': [
+      'mxact',
+      'delayed_startup',
+      'ondisk_startup',
+      'catalog_change_snapshot',
+      'concurrent_ddl_dml',
+      'oldest_xmin',
+      'snapshot_transfer',
+      'subxact_without_top',
+      'concurrent_stream',
+      'twophase_snapshot',
+      'slot_creation_error',
+      'skip_snapshot_restore',
+      'invalidation_distribution',
+      'parallel_session_origin',
+      'tuplecid_nested',
+      'tuplecid_restart',
+    ],
     'regress_args': [
       '--temp-config', files('logical.conf'),
     ],
diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile
index a7a16d5016a..6a8d426233f 100644
--- a/src/test/modules/injection_points/Makefile
+++ b/src/test/modules/injection_points/Makefile
@@ -14,11 +14,6 @@ EXTRA_INSTALL = contrib/test_decoding
 REGRESS = injection_points hashagg portal_bind reindex_conc vacuum
 REGRESS_OPTS = --dlpath=$(top_builddir)/src/test/regress
 
-# wait_cleanup terminates another backend, whose FATAL message can be lost
-# on Windows, making the test unstable there.
-# See https://postgr.es/m/[email protected]
-WAIT_CLEANUP_TST = $(if $(filter win32,$(PORTNAME)),,wait_cleanup)
-
 ISOLATION = basic \
 	    inplace \
 	    reindex_concurrently_deferred \
@@ -34,7 +29,7 @@ ISOLATION = basic \
 	    ri_fastpath_reindex \
 	    ri_fastpath_snapshot \
 	    syscache-update-pruned \
-	    $(WAIT_CLEANUP_TST) \
+	    wait_cleanup \
 	    heap_lock_update \
 	    on_conflict_probe_window \
 	    multixact-aborted-updater
diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build
index cf9cb219548..324c715b37f 100644
--- a/src/test/modules/injection_points/meson.build
+++ b/src/test/modules/injection_points/meson.build
@@ -26,34 +26,6 @@ test_install_data += files(
   'injection_points--1.0.sql',
 )
 
-injection_points_isolation = [
-  'basic',
-  'inplace',
-  'reindex_concurrently_deferred',
-  'reindex_concurrently_toast',
-  'repack',
-  'repack_commit_race',
-  'repack_decode',
-  'repack_dropped',
-  'repack_missingval',
-  'repack_temporal',
-  'repack_temporal_multirange',
-  'repack_toast',
-  'ri_fastpath_reindex',
-  'ri_fastpath_snapshot',
-  'syscache-update-pruned',
-  'heap_lock_update',
-  'on_conflict_probe_window',
-  'multixact-aborted-updater',
-]
-
-# wait_cleanup terminates another backend, whose FATAL message can be lost
-# on Windows, making the test unstable there.
-# See https://postgr.es/m/[email protected]
-if host_system != 'windows'
-  injection_points_isolation += 'wait_cleanup'
-endif
-
 tests += {
   'name': 'injection_points',
   'sd': meson.current_source_dir(),
@@ -71,7 +43,27 @@ tests += {
     'runningcheck': false,
   },
   'isolation': {
-    'specs': injection_points_isolation,
+    'specs': [
+      'basic',
+      'inplace',
+      'reindex_concurrently_deferred',
+      'reindex_concurrently_toast',
+      'repack',
+      'repack_commit_race',
+      'repack_decode',
+      'repack_dropped',
+      'repack_missingval',
+      'repack_temporal',
+      'repack_temporal_multirange',
+      'repack_toast',
+      'ri_fastpath_reindex',
+      'ri_fastpath_snapshot',
+      'syscache-update-pruned',
+      'wait_cleanup',
+      'heap_lock_update',
+      'on_conflict_probe_window',
+      'multixact-aborted-updater',
+    ],
     'runningcheck': false, # see syscache-update-pruned
     # Some tests wait for all snapshots, so avoid parallel execution
     'runningcheck-parallel': false,
-- 
2.56.1

From 4f8cd555a39f37295db092ace161dbd2e9720118 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
Date: Thu, 26 Nov 2026 13:59:54 +0100
Subject: [PATCH v3 3/5] fixup! Reapply "graceful shutdown" changes for
 Windows.

Rewrite the socket_close() comment to address Jacob Champion's
review[1]: describe what Windows actually does instead of calling it an
RFC violation, and don't claim to know why OpenSSL needs shutdown().

[1]: https://www.postgresql.org/message-id/CAOYmi%2BnPVLfTO%3DwhNPdyQ420GCjMg5f_BHMwTR3QeBYHWaXW%3Dw%40mail.gmail.com
---
 src/backend/libpq/pqcomm.c | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)

diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index c0445f64546..87de7ac1a1c 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -382,13 +382,24 @@ socket_close(int code, Datum arg)
 		 * --- wait till the transport layer reports connection closure, and
 		 * you can be sure the backend has exited.  Saves a kernel call, too.
 		 *
-		 * However, that does not work on Windows: if the kernel closes the
-		 * socket it will invoke an "abortive shutdown" that discards any data
-		 * not yet sent to the client.  (This is a flat-out violation of the
-		 * TCP RFCs, but count on Microsoft not to care about that.)  To get
-		 * the spec-compliant "graceful shutdown" behavior, we must invoke
-		 * closesocket() explicitly.  When using OpenSSL, it seems that clean
-		 * shutdown also requires an explicit shutdown() call.
+		 * However, that does not work on Windows: if the kernel closes a
+		 * socket that is still open at process exit, it does an "abortive
+		 * shutdown", sending an RST instead of a FIN.  Any data not yet sent
+		 * is discarded, and when the RST reaches the client, Winsock also
+		 * discards whatever the client has not read yet.  Either way, the
+		 * client is likely to lose the error message explaining why we're
+		 * exiting, and reports that the server closed the connection
+		 * unexpectedly instead.  Calling closesocket() explicitly gives a
+		 * graceful shutdown.  The shutdown() call was added because, with
+		 * OpenSSL, closesocket() alone was observed to still lose messages
+		 * occasionally; why exactly was never determined.
+		 *
+		 * Even with a graceful shutdown, if the client sends anything after
+		 * we're gone, such as its next query, our side answers with an RST,
+		 * and the client can still lose the data we sent.  The client can
+		 * reduce that risk by reading any pending input before sending, but
+		 * it can't rule it out: our data might not have arrived yet when it
+		 * sends.
 		 *
 		 * This code runs late enough during process shutdown that we should
 		 * have finished all externally-visible shutdown activities, so that
-- 
2.56.1

From 92e92673e5332492b48fb5cd0b6e4cf18d2e3ca8 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
Date: Mon, 5 Oct 2026 22:03:19 +0200
Subject: [PATCH v3 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

From 8f985a90460dae162c9bd8823fe58551df121119 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
Date: Thu, 26 Nov 2026 14:27:33 +0100
Subject: [PATCH v3 5/5] POC: Add client_connection_linger_timeout to avoid
 lost errors at close

When a backend closes the connection while the client is still sending,
for instance a startup packet sent right after a TLS 1.3 handshake that
the server is about to reject, the server's OS answers that data with
an RST. On Windows the client's OS then discards everything the client
hasn't read yet, including the error explaining why the connection was
closed.

With this setting the backend sends a FIN, and then keeps reading and
discarding client data until the client closes its side or the timeout
expires, before closing the socket. Data the client sends in that
window no longer causes an RST. It's disabled by default, because it
can delay backend exit by up to the timeout when the client keeps the
connection open.
---
 src/backend/libpq/pqcomm.c                    | 87 +++++++++++++++++--
 src/backend/utils/misc/guc_parameters.dat     | 10 +++
 src/backend/utils/misc/postgresql.conf.sample |  3 +
 src/include/libpq/libpq.h                     |  1 +
 src/test/ssl/.gitignore                       |  3 +
 src/test/ssl/Makefile                         | 12 ++-
 src/test/ssl/meson.build                      | 21 +++++
 src/test/ssl/ssl_slow_connect.c               | 63 ++++++++++++++
 src/test/ssl/t/006_linger.pl                  | 83 ++++++++++++++++++
 9 files changed, 274 insertions(+), 9 deletions(-)
 create mode 100644 src/test/ssl/ssl_slow_connect.c
 create mode 100644 src/test/ssl/t/006_linger.pl

diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index 87de7ac1a1c..ab69ad3b65c 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -78,6 +78,7 @@
 #include "storage/latch.h"
 #include "utils/guc_hooks.h"
 #include "utils/memutils.h"
+#include "utils/timestamp.h"
 
 /*
  * Cope with the various platform-specific ways to spell TCP keepalive socket
@@ -103,6 +104,7 @@
  */
 int			Unix_socket_permissions;
 char	   *Unix_socket_group;
+int			client_connection_linger_timeout = 0;
 
 /* Where the Unix socket files are (list of palloc'd strings) */
 static List *sock_paths = NIL;
@@ -136,6 +138,7 @@ static bool PqCommReadingMsg;	/* in the middle of reading a message */
 /* Internal functions */
 static void socket_comm_reset(void);
 static void socket_close(int code, Datum arg);
+static void socket_linger(pgsocket sock);
 static void socket_set_nonblocking(bool nonblocking);
 static int	socket_flush(void);
 static int	socket_flush_if_writable(void);
@@ -394,20 +397,26 @@ socket_close(int code, Datum arg)
 		 * OpenSSL, closesocket() alone was observed to still lose messages
 		 * occasionally; why exactly was never determined.
 		 *
-		 * Even with a graceful shutdown, if the client sends anything after
-		 * we're gone, such as its next query, our side answers with an RST,
-		 * and the client can still lose the data we sent.  The client can
-		 * reduce that risk by reading any pending input before sending, but
-		 * it can't rule it out: our data might not have arrived yet when it
-		 * sends.
+		 * Even with a graceful shutdown, and on any platform, if the client
+		 * sends anything after we're gone, our side answers with an RST, and
+		 * a client on Windows can still lose the data we sent.  Lingering
+		 * (see socket_linger) avoids that for data the client sends shortly
+		 * after we close, such as during connection setup.  For later sends,
+		 * like an idle client's next query, only the client can reduce the
+		 * risk, by reading any pending input before sending.
 		 *
 		 * This code runs late enough during process shutdown that we should
 		 * have finished all externally-visible shutdown activities, so that
 		 * in principle it's good enough to act as a synchronous close on
 		 * Windows too.  But it's a lot more fragile than the other way.
 		 */
+		if (client_connection_linger_timeout > 0)
+			socket_linger(MyProcPort->sock);
+
 #ifdef WIN32
-		shutdown(MyProcPort->sock, SD_SEND);
+		/* If lingering is enabled, socket_linger() already called shutdown() */
+		if (client_connection_linger_timeout == 0)
+			shutdown(MyProcPort->sock, SD_SEND);
 		closesocket(MyProcPort->sock);
 #endif
 
@@ -416,6 +425,70 @@ socket_close(int code, Datum arg)
 	}
 }
 
+/*
+ * Send a FIN, then read and discard client data until the client closes its
+ * side too or client_connection_linger_timeout expires.
+ *
+ * Data arriving after we've closed the socket makes our OS answer with an
+ * RST, and some client OSes (notably Windows) then discard data the client
+ * hasn't read yet, such as our final error message.  This happens on any
+ * server OS, which is why this isn't Windows-specific.
+ *
+ * This runs very late during process exit, so use plain select() and recv().
+ */
+static void
+socket_linger(pgsocket sock)
+{
+	TimestampTz deadline;
+	char		buf[1024];
+
+#ifdef WIN32
+	shutdown(sock, SD_SEND);
+#else
+	shutdown(sock, SHUT_WR);
+#endif
+
+	deadline = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
+										   client_connection_linger_timeout);
+	for (;;)
+	{
+		long		timeout_ms;
+		fd_set		rfds;
+		struct timeval tv;
+		int			rc;
+		ssize_t		nread;
+
+		timeout_ms = TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
+													 deadline);
+		if (timeout_ms <= 0)
+			break;
+
+		FD_ZERO(&rfds);
+		FD_SET(sock, &rfds);
+		tv.tv_sec = timeout_ms / 1000;
+		tv.tv_usec = (timeout_ms % 1000) * 1000;
+		rc = select((int) sock + 1, &rfds, NULL, NULL, &tv);
+		if (rc < 0)
+		{
+			if (errno == EINTR)
+				continue;
+			break;
+		}
+		if (rc == 0)
+			break;
+
+		nread = recv(sock, buf, sizeof(buf), 0);
+		if (nread == 0)
+			break;				/* client closed its side as well */
+		if (nread < 0)
+		{
+			if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
+				continue;
+			break;
+		}
+	}
+}
+
 
 
 /* --------------------------------
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..e3a3a721a38 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -449,6 +449,16 @@
   check_hook => 'check_client_connection_check_interval',
 },
 
+{ name => 'client_connection_linger_timeout', type => 'int', context => 'PGC_SIGHUP', group => 'CONN_AUTH_TCP',
+  short_desc => 'Sets how long to keep reading from the client after closing the connection.',
+  long_desc => 'This avoids the client losing the final error message, if it sends data while the connection is being closed. 0 disables lingering.',
+  flags => 'GUC_UNIT_MS',
+  variable => 'client_connection_linger_timeout',
+  boot_val => '0',
+  min => '0',
+  max => 'INT_MAX',
+},
+
 { name => 'client_encoding', type => 'string', context => 'PGC_USERSET', group => 'CLIENT_CONN_LOCALE',
   short_desc => 'Sets the client\'s character set encoding.',
   flags => 'GUC_IS_NAME | GUC_REPORT',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06c..336654fb821 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -92,6 +92,9 @@
 #client_connection_check_interval = 0   # time between checks for client
                                         # disconnection while running queries;
                                         # 0 for never
+#client_connection_linger_timeout = 0   # time to keep reading from the client
+                                        # after closing the connection;
+                                        # 0 to not linger
 
 # - Authentication -
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index d15073a0a93..96124100b5d 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -62,6 +62,7 @@ extern const PGDLLIMPORT PQcommMethods *PqCommMethods;
  * prototypes for functions in pqcomm.c
  */
 extern PGDLLIMPORT WaitEventSet *FeBeWaitSet;
+extern PGDLLIMPORT int client_connection_linger_timeout;
 
 #define FeBeWaitSetSocketPos 0
 #define FeBeWaitSetLatchPos 1
diff --git a/src/test/ssl/.gitignore b/src/test/ssl/.gitignore
index e07b677a7dc..9be3bdc6add 100644
--- a/src/test/ssl/.gitignore
+++ b/src/test/ssl/.gitignore
@@ -1,2 +1,5 @@
 # Generated by regression tests
 /tmp_check/
+
+# Test program
+/ssl_slow_connect
diff --git a/src/test/ssl/Makefile b/src/test/ssl/Makefile
index aa062945fb9..2048dfe05c1 100644
--- a/src/test/ssl/Makefile
+++ b/src/test/ssl/Makefile
@@ -17,6 +17,13 @@ include $(top_builddir)/src/Makefile.global
 
 export OPENSSL with_ssl
 
+override CPPFLAGS := -I$(libpq_srcdir) $(CPPFLAGS)
+
+all: ssl_slow_connect$(X)
+
+ssl_slow_connect$(X): ssl_slow_connect.o | submake-libpq submake-libpgport
+	$(CC) $(CFLAGS) $^ $(libpq_pgport) $(LDFLAGS) $(LDFLAGS_EX) $(LIBS) -o $@
+
 # The sslfiles targets are separated into their own file due to interactions
 # with settings in Makefile.global.
 .PHONY: sslfiles sslfiles-clean
@@ -24,12 +31,13 @@ sslfiles sslfiles-clean:
 	$(MAKE) -f $(srcdir)/sslfiles.mk $@
 
 clean distclean:
+	rm -f ssl_slow_connect$(X) ssl_slow_connect.o
 	rm -rf tmp_check
 	$(MAKE) -f $(srcdir)/sslfiles.mk $@
 
 # Doesn't depend on sslfiles because we don't rebuild them by default
-check:
+check: all
 	$(prove_check)
 
-installcheck:
+installcheck: all
 	$(prove_installcheck)
diff --git a/src/test/ssl/meson.build b/src/test/ssl/meson.build
index 190448ec3b6..c37318e7ac4 100644
--- a/src/test/ssl/meson.build
+++ b/src/test/ssl/meson.build
@@ -1,5 +1,24 @@
 # Copyright (c) 2022-2026, PostgreSQL Global Development Group
 
+ssl_slow_connect_sources = files(
+  'ssl_slow_connect.c',
+)
+
+if host_system == 'windows'
+  ssl_slow_connect_sources += rc_bin_gen.process(win32ver_rc, extra_args: [
+    '--NAME', 'ssl_slow_connect',
+    '--FILEDESC', 'ssl_slow_connect - test client that connects slowly',])
+endif
+
+ssl_slow_connect = executable('ssl_slow_connect',
+  ssl_slow_connect_sources,
+  dependencies: [frontend_code, libpq],
+  kwargs: default_bin_args + {
+    'install': false,
+  },
+)
+testprep_targets += ssl_slow_connect
+
 tests += {
   'name': 'ssl',
   'sd': meson.current_source_dir(),
@@ -9,12 +28,14 @@ tests += {
       'with_ssl': ssl_library,
       'OPENSSL': openssl.found() ? openssl.full_path() : '',
     },
+    'deps': [ssl_slow_connect],
     'tests': [
       't/001_ssltests.pl',
       't/002_scram.pl',
       't/003_sslinfo.pl',
       't/004_sni.pl',
       't/005_idle_fatal.pl',
+      't/006_linger.pl',
     ],
   },
 }
diff --git a/src/test/ssl/ssl_slow_connect.c b/src/test/ssl/ssl_slow_connect.c
new file mode 100644
index 00000000000..6231c6ff635
--- /dev/null
+++ b/src/test/ssl/ssl_slow_connect.c
@@ -0,0 +1,63 @@
+/*-------------------------------------------------------------------------
+ *
+ * ssl_slow_connect.c
+ *		Test client that connects asynchronously, sleeping before each call
+ *		to PQconnectPoll().
+ *
+ * This imitates an application with a busy event loop: the steps of
+ * connection establishment get spread out in time, most importantly the
+ * end of the TLS handshake and the sending of the startup packet.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * IDENTIFICATION
+ *		src/test/ssl/ssl_slow_connect.c
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres_fe.h"
+
+#include "libpq-fe.h"
+
+int
+main(int argc, char *argv[])
+{
+	PGconn	   *conn;
+	long		delay_us;
+
+	if (argc != 3)
+	{
+		fprintf(stderr, "usage: %s DELAY_MS CONNINFO\n", argv[0]);
+		return 2;
+	}
+	delay_us = atol(argv[1]) * 1000L;
+
+	conn = PQconnectStart(argv[2]);
+	if (conn == NULL)
+	{
+		fprintf(stderr, "out of memory\n");
+		return 2;
+	}
+
+	while (PQstatus(conn) != CONNECTION_BAD)
+	{
+		PostgresPollingStatusType res;
+
+		pg_usleep(delay_us);
+		res = PQconnectPoll(conn);
+		if (res == PGRES_POLLING_OK)
+		{
+			printf("connected\n");
+			PQfinish(conn);
+			return 0;
+		}
+		if (res == PGRES_POLLING_FAILED)
+			break;
+	}
+
+	fprintf(stderr, "%s", PQerrorMessage(conn));
+	PQfinish(conn);
+	return 1;
+}
diff --git a/src/test/ssl/t/006_linger.pl b/src/test/ssl/t/006_linger.pl
new file mode 100644
index 00000000000..bbbfb2a15d9
--- /dev/null
+++ b/src/test/ssl/t/006_linger.pl
@@ -0,0 +1,83 @@
+
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that libpq reports the reason when the server rejects a client
+# certificate over TLS 1.3.
+#
+# With TLS 1.3 the client considers the handshake complete before the server
+# has verified the client certificate, so libpq sends its startup packet
+# without having heard from the server.  The server meanwhile rejects the
+# certificate, sends an alert and closes the connection.  If the startup
+# packet arrives after that, the server's OS answers it with a reset, and a
+# Windows client then loses the alert it hasn't read yet.
+# client_connection_linger_timeout makes the backend read and discard the
+# startup packet instead.
+#
+# psql sends its startup packet so quickly that it reaches the server before
+# the backend is done rejecting the certificate, in which case the alert isn't
+# lost.  So this uses a client that takes its time between the steps of
+# connection establishment, like an application with a busy event loop would.
+
+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;
+$node->append_conf('postgresql.conf',
+	"client_connection_linger_timeout = '30s'");
+
+# 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');
+
+my $connstr =
+	"sslrootcert=ssl/root+server_ca.crt sslcrl=invalid sslcrldir=invalid "
+  . "sslmode=require dbname=certdb user=ssltestuser "
+  . "hostaddr=$SERVERHOSTADDR host=localhost "
+  . "ssl_min_protocol_version=TLSv1.3 ssl_max_protocol_version=TLSv1.3 "
+  . "sslcert=ssl/client-revoked.crt "
+  . $ssl_server->sslkey('client-revoked.key');
+
+foreach my $i (1 .. 3)
+{
+	my ($stdout, $stderr) = ('', '');
+	IPC::Run::run(
+		[ 'ssl_slow_connect', '50', $connstr ],
+		'>' => \$stdout,
+		'2>' => \$stderr);
+	like(
+		$stderr,
+		qr!SSL error: (ssl[a-z0-9/]*|tls) alert certificate revoked!,
+		"revoked client cert over TLS 1.3, attempt $i");
+}
+
+done_testing();
-- 
2.56.1

Reply via email to