On Thu, 8 Oct 2026 at 22:33, Zsolt Parragi <[email protected]> wrote:
On Windows, when a backend exits without closing its socket, the
kernel does an abortive close, which resets the connection, and the
client can lose unread data, including the FATAL message of a
terminated backend.
Hi Zsolt and others,
I ran into this with my patch to stop libpq from appending "server
closed the connection unexpectedly" after a FATAL [1]: its postgres_fdw
test needed a Windows-only expected output because the FATAL got lost.
The graceful close is important (it's what fixes Greg's failures), but
it isn't enough to fix the problem I ran into. If the client sends
anything after the backend is gone, the server's OS (Windows or Linux)
answers with an RST and Winsock discards the unread FATAL. That's the
normal case for a FATAL on an idle connection (bug #15598 [2]), and
Alexander Lakhin hit it in 2023 too [3]. So attached is a
fix/workaround for that as well: libpq reads any pending network data
into its own buffer before sending a new query.
Attached v2, which also addresses Jacob's and Michael's concerns:
0001: Zsolt's graceful shutdown reapply, unchanged
0002: Zsolt's isolation test skip revert, rebased
0003: fixup of 0001's comment, addressing Jacob's review
0004: libpq on Windows reads pending input before sending a query on an
idle connection, plus tests
0005: POC for a server-side lingering close, which would make these
lost FATAL errors even more unlikely
P.S. A review of [1] would definitely be appreciated
[1]
https://www.postgresql.org/message-id/flat/DJ60NPKYB9L9.3I3SS9I2MBL00%40jeltef.nl#3ffda50a235a05d2f3af73dbc18be18b
[2]
https://www.postgresql.org/message-id/15598-e3fec9d8c5184936%40postgresql.org
[3]
https://www.postgresql.org/message-id/32d112ee-0b6f-d4ab-441b-e2bba66a1d83%40gmail.com
From 4149096b7fadefbb520c35868527c530adc3000c Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Thu, 8 Oct 2026 20:10:21 +0000
Subject: [PATCH v2 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 0783408a61418ad5df480541337b5cce42bd7c98 Mon Sep 17 00:00:00 2001
From: Zsolt Parragi <[email protected]>
Date: Thu, 8 Oct 2026 20:10:21 +0000
Subject: [PATCH v2 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 2bbde948858af5ccc4235dd39002e86acecf60d7 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
Date: Thu, 26 Nov 2026 13:59:54 +0100
Subject: [PATCH v2 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 99feadabcfea04a2f0bbc82fe8606eeb11f1ee47 Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
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
From ce42ddedafa6e95355ff7817b019c5e18c18669e Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <[email protected]>
Date: Thu, 26 Nov 2026 14:27:33 +0100
Subject: [PATCH v2 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 +
4 files changed, 94 insertions(+), 7 deletions(-)
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
--
2.56.1