From 99422cbe06332a8526865daf79ecba6ba95c97e0 Mon Sep 17 00:00:00 2001
From: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Date: Fri, 20 Nov 2026 19:37:05 +0900
Subject: [PATCH 1/3] Allow BackgroundPsql::quit to wait for backend exit

Waiting for psql to exit does not guarantee that its backend has
finished exit processing. Tests that depend on session-exit cleanup
need to wait for the backend as well.

Save the backend PID in wait_connect() and add an optional wait
argument to quit(). When requested, wait for the saved PID to exit
after psql finishes, without issuing additional queries or discarding
session output.
---
 .../perl/PostgreSQL/Test/BackgroundPsql.pm    | 35 ++++++++++++++++---
 1 file changed, 31 insertions(+), 4 deletions(-)

diff --git a/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm b/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
index d7797225451..e5ea9481253 100644
--- a/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
+++ b/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
@@ -61,6 +61,7 @@ use Config;
 use IPC::Run;
 use PostgreSQL::Test::Utils qw(pump_until);
 use Test::More;
+use Time::HiRes qw(usleep);
 
 =pod
 
@@ -91,6 +92,7 @@ sub new
 		'stderr' => '',
 		'query_timer_restart' => undef,
 		'query_cnt' => 1,
+		'backend_pid' => undef,
 	};
 	my $run;
 
@@ -141,6 +143,7 @@ sub new
 
 Returns once psql has started up and is ready to consume input. This is called
 automatically for clients unless requested otherwise in the constructor.
+The backend PID is saved for use by C<quit>.
 
 =cut
 
@@ -173,24 +176,46 @@ sub wait_connect
 	$self->{stderr} = '';
 
 	die "psql startup timed out" if $self->{timeout}->is_expired;
+
+	# Remember the backend PID so quit() can wait for it to exit.
+	my $output = $self->query_safe("SELECT pg_backend_pid()");
+	$output =~ /^([1-9][0-9]*)\r?$/m
+	  or croak "could not determine backend PID: $output";
+	$self->{backend_pid} = $1;
 }
 
 =pod
 
-=item $session->quit
+=item $session->quit()
 
 Close the session and clean up resources. Each test run must be closed with
-C<quit>.
+C<quit>. Also wait for the saved backend PID to exit if C<$wait> is true.
 
 =cut
 
 sub quit
 {
-	my ($self) = @_;
+	my ($self, $wait) = @_;
 
 	$self->{stdin} .= "\\q\n";
 
-	return $self->{run}->finish;
+	my $ret = $self->{run}->finish;
+
+	if ($wait && defined($self->{backend_pid}))
+	{
+		my $pid = $self->{backend_pid};
+		my $max_attempts = 10 * $PostgreSQL::Test::Utils::timeout_default;
+		my $attempts = 0;
+
+		while (kill(0, $pid))
+		{
+			croak "timed out waiting for backend $pid to exit"
+			  if $attempts++ >= $max_attempts;
+			usleep(100_000);
+		}
+	}
+
+	return $ret;
 }
 
 =pod
@@ -205,6 +230,8 @@ sub reconnect_and_clear
 {
 	my ($self) = @_;
 
+	$self->{backend_pid} = undef;
+
 	# If psql isn't dead already, tell it to quit as \q, when already dead,
 	# causes IPC::Run to unhelpfully error out with "ack Broken pipe:".
 	$self->{run}->pump_nb();
-- 
2.52.0

