From 50662c1d37e70c1b357ecebab261275e286ca49a Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horiguchi.kyotaro@lab.ntt.co.jp>
Date: Tue, 16 Oct 2018 21:31:22 +0900
Subject: [PATCH 3/3] Remote GUC setting feature and non-xact GUC config.

This adds two features at once. (will be split later).

One is non-transactional GUC setting feature. This allows setting GUC
variable set by the action GUC_ACTION_NONXACT(the name requires
condieration) survive beyond rollback. It is required by remote guc
setting to work sanely. Without the feature a remote-set value within
a trasction will disappear involved in rollback. The only local
interface for the NONXACT action is set_config(name, value,
is_local=false, is_nonxact = true).

The second is remote guc setting feature. It uses ProcSignal to notify
the target server.
---
 doc/src/sgml/config.sgml             |   4 +
 doc/src/sgml/func.sgml               |  30 ++
 src/backend/catalog/system_views.sql |   7 +-
 src/backend/postmaster/pgstat.c      |   3 +
 src/backend/storage/ipc/ipci.c       |   2 +
 src/backend/storage/ipc/procsignal.c |   4 +
 src/backend/tcop/postgres.c          |  10 +
 src/backend/utils/misc/README        |  26 +-
 src/backend/utils/misc/guc.c         | 619 +++++++++++++++++++++++++++++++++--
 src/include/catalog/pg_proc.dat      |  10 +-
 src/include/pgstat.h                 |   3 +-
 src/include/storage/procsignal.h     |   3 +
 src/include/utils/guc.h              |  13 +-
 src/include/utils/guc_tables.h       |   5 +-
 src/test/regress/expected/guc.out    | 223 +++++++++++++
 src/test/regress/expected/rules.out  |  26 +-
 src/test/regress/sql/guc.sql         |  88 +++++
 17 files changed, 1027 insertions(+), 49 deletions(-)

diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml
index b8a91d954d..029642cddb 100644
--- a/doc/src/sgml/config.sgml
+++ b/doc/src/sgml/config.sgml
@@ -281,6 +281,10 @@ UPDATE pg_settings SET setting = reset_val WHERE name = 'configuration_parameter
      </listitem>
     </itemizedlist>
 
+    <para>
+     Also values on other sessions can be set using the SQL
+     function <function>pg_set_backend_setting</function>.
+    </para>
    </sect2>
 
    <sect2>
diff --git a/doc/src/sgml/func.sgml b/doc/src/sgml/func.sgml
index 09c77db045..f3e4c8f592 100644
--- a/doc/src/sgml/func.sgml
+++ b/doc/src/sgml/func.sgml
@@ -18694,6 +18694,20 @@ SELECT collation for ('foo' COLLATE "de_DE");
        <entry><type>text</type></entry>
        <entry>set parameter and return new value</entry>
       </row>
+      <row>
+       <entry>
+        <indexterm>
+         <primary>pg_set_backend_setting</primary>
+        </indexterm>
+        <literal><function>pg_set_backend_config(
+            				<parameter>process_id</parameter>,
+                            <parameter>setting_name</parameter>,
+                            <parameter>new_value</parameter>)
+							</function></literal>
+       </entry>
+       <entry><type>bool</type></entry>
+       <entry>set parameter on another session</entry>
+      </row>
      </tbody>
     </tgroup>
    </table>
@@ -18748,6 +18762,22 @@ SELECT set_config('log_statement_stats', 'off', false);
 ------------
  off
 (1 row)
+</programlisting>
+   </para>
+
+   <para>
+    <function>pg_set_backend_config</function> sets the parameter
+    <parameter>setting_name</parameter> to
+    <parameter>new_value</parameter> on the other session with PID
+    <parameter>process_id</parameter>. The setting is always session-local and
+    returns true if succeeded.  An example:
+<programlisting>
+SELECT pg_set_backend_config(2134, 'work_mem', '16MB');
+
+pg_set_backend_config
+------------
+ t
+(1 row)
 </programlisting>
    </para>
 
diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index 4f7e12463e..642b7e28d4 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -474,7 +474,7 @@ CREATE VIEW pg_settings AS
 CREATE RULE pg_settings_u AS
     ON UPDATE TO pg_settings
     WHERE new.name = old.name DO
-    SELECT set_config(old.name, new.setting, 'f');
+    SELECT set_config(old.name, new.setting, 'f', 'f');
 
 CREATE RULE pg_settings_n AS
     ON UPDATE TO pg_settings
@@ -1048,6 +1048,11 @@ CREATE OR REPLACE FUNCTION
   RETURNS boolean STRICT VOLATILE LANGUAGE INTERNAL AS 'pg_promote'
   PARALLEL SAFE;
 
+CREATE OR REPLACE FUNCTION set_config (
+		setting_name text, new_value text, is_local boolean, is_nonxact boolean DEFAULT false)
+		RETURNS text STRICT VOLATILE LANGUAGE internal AS 'set_config_by_name'
+		PARALLEL UNSAFE;
+
 -- legacy definition for compatibility with 9.3
 CREATE OR REPLACE FUNCTION
   json_populate_record(base anyelement, from_json json, use_json_as_text boolean DEFAULT false)
diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c
index fc50f10cbb..a1e21f2696 100644
--- a/src/backend/postmaster/pgstat.c
+++ b/src/backend/postmaster/pgstat.c
@@ -3707,6 +3707,9 @@ pgstat_get_wait_ipc(WaitEventIPC w)
 		case WAIT_EVENT_SYNC_REP:
 			event_name = "SyncRep";
 			break;
+		case WAIT_EVENT_REMOTE_GUC:
+			event_name = "RemoteGUC";
+			break;
 			/* no default case, so that compiler will warn */
 	}
 
diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c
index 0c86a581c0..03d526d12d 100644
--- a/src/backend/storage/ipc/ipci.c
+++ b/src/backend/storage/ipc/ipci.c
@@ -150,6 +150,7 @@ CreateSharedMemoryAndSemaphores(bool makePrivate, int port)
 		size = add_size(size, SyncScanShmemSize());
 		size = add_size(size, AsyncShmemSize());
 		size = add_size(size, BackendRandomShmemSize());
+		size = add_size(size, GucShmemSize());
 #ifdef EXEC_BACKEND
 		size = add_size(size, ShmemBackendArraySize());
 #endif
@@ -270,6 +271,7 @@ CreateSharedMemoryAndSemaphores(bool makePrivate, int port)
 	SyncScanShmemInit();
 	AsyncShmemInit();
 	BackendRandomShmemInit();
+	GucShmemInit();
 
 #ifdef EXEC_BACKEND
 
diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c
index b0dd7d1b37..b897c36bae 100644
--- a/src/backend/storage/ipc/procsignal.c
+++ b/src/backend/storage/ipc/procsignal.c
@@ -27,6 +27,7 @@
 #include "storage/shmem.h"
 #include "storage/sinval.h"
 #include "tcop/tcopprot.h"
+#include "utils/guc.h"
 
 
 /*
@@ -292,6 +293,9 @@ procsignal_sigusr1_handler(SIGNAL_ARGS)
 	if (CheckProcSignal(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN))
 		RecoveryConflictInterrupt(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN);
 
+	if (CheckProcSignal(PROCSIG_REMOTE_GUC))
+		HandleRemoteGucSetInterrupt();
+
 	SetLatch(MyLatch);
 
 	latch_sigusr1_handler();
diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index f2573fecbd..a891935528 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -3152,6 +3152,10 @@ ProcessInterrupts(void)
 
 	if (ParallelMessagePending)
 		HandleParallelMessages();
+
+	/* We don't want chage GUC variables while running a query */
+	if (RemoteGucChangePending && DoingCommandRead)
+		HandleGucRemoteChanges();
 }
 
 
@@ -4188,6 +4192,12 @@ PostgresMain(int argc, char *argv[],
 			send_ready_for_query = false;
 		}
 
+		/*
+		 * (2.5) Process some pending works.
+		 */
+		if (RemoteGucChangePending)
+			HandleGucRemoteChanges();
+
 		/*
 		 * (2) Allow asynchronous signals to be executed immediately if they
 		 * come in while we are waiting for client input. (This must be
diff --git a/src/backend/utils/misc/README b/src/backend/utils/misc/README
index 6e294386f7..42ae6c1a8f 100644
--- a/src/backend/utils/misc/README
+++ b/src/backend/utils/misc/README
@@ -169,10 +169,14 @@ Entry to a function with a SET option:
 Plain SET command:
 
 	If no stack entry of current level:
-		Push new stack entry w/prior value and state SET
+		Push new stack entry w/prior value and state SET or
+		push new stack entry w/o value and state NONXACT.
 	else if stack entry's state is SAVE, SET, or LOCAL:
 		change stack state to SET, don't change saved value
 		(here we are forgetting effects of prior set action)
+	else if stack entry's state is NONXACT:
+		change stack state to NONXACT_SET, set the current value to
+		prior.
 	else (entry must have state SET+LOCAL):
 		discard its masked value, change state to SET
 		(here we are forgetting effects of prior SET and SET LOCAL)
@@ -185,13 +189,20 @@ SET LOCAL command:
 	else if stack entry's state is SAVE or LOCAL or SET+LOCAL:
 		no change to stack entry
 		(in SAVE case, SET LOCAL will be forgotten at func exit)
+	else if stack entry's state is NONXACT:
+		set current value to both prior and masked slots. set state
+		NONXACT+LOCAL.
 	else (entry must have state SET):
 		put current active into its masked slot, set state SET+LOCAL
 	Now set new value.
 
+Setting by NONXACT action (no command exists):
+	Always blow away existing stack then create a new NONXACT entry.	
+
 Transaction or subtransaction abort:
 
-	Pop stack entries, restoring prior value, until top < subxact depth
+	Pop stack entries, restoring prior value unless the stack entry's
+	state is NONXACT, until top < subxact depth
 
 Transaction or subtransaction commit (incl. successful function exit):
 
@@ -199,9 +210,9 @@ Transaction or subtransaction commit (incl. successful function exit):
 
 		if entry's state is SAVE:
 			pop, restoring prior value
-		else if level is 1 and entry's state is SET+LOCAL:
+		else if level is 1 and entry's state is SET+LOCAL or NONXACT+LOCAL:
 			pop, restoring *masked* value
-		else if level is 1 and entry's state is SET:
+		else if level is 1 and entry's state is SET or NONXACT+SET:
 			pop, discarding old value
 		else if level is 1 and entry's state is LOCAL:
 			pop, restoring prior value
@@ -210,9 +221,9 @@ Transaction or subtransaction commit (incl. successful function exit):
 		else
 			merge entries of level N-1 and N as specified below
 
-The merged entry will have level N-1 and prior = older prior, so easiest
-to keep older entry and free newer.  There are 12 possibilities since
-we already handled level N state = SAVE:
+The merged entry will have level N-1 and prior = older prior, so
+easiest to keep older entry and free newer.  Disregarding to NONXACT,
+here are 12 possibilities since we already handled level N state = SAVE:
 
 N-1		N
 
@@ -232,6 +243,7 @@ SET+LOCAL	SET		discard top prior and second masked, state SET
 SET+LOCAL	LOCAL		discard top prior, no change to stack entry
 SET+LOCAL	SET+LOCAL	discard top prior, copy masked, state S+L
 
+(TODO: states involving NONXACT)
 
 RESET is executed like a SET, but using the reset_val as the desired new
 value.  (We do not provide a RESET LOCAL command, but SET LOCAL TO DEFAULT
diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c
index ba0e65f6fb..15c6e2889d 100644
--- a/src/backend/utils/misc/guc.c
+++ b/src/backend/utils/misc/guc.c
@@ -216,6 +216,37 @@ static ConfigVariable *ProcessConfigFileInternal(GucContext context,
 						  bool applySettings, int elevel);
 
 
+/* Enum and struct to command GUC setting to another backend */
+typedef enum
+{
+	REMGUC_VACANT,
+	REMGUC_REQUEST,
+	REMGUC_INPROCESS,
+	REMGUC_DONE,
+	REMGUC_CANCELING,
+	REMGUC_CANCELED,
+} remote_guc_status;
+
+#define GUC_REMOTE_MAX_VALUE_LEN  1024		/* an arbitrary value */
+#define GUC_REMOTE_CANCEL_TIMEOUT 5000		/* in milliseconds */
+
+typedef struct
+{
+	remote_guc_status	 state;
+	char name[NAMEDATALEN];
+	char value[GUC_REMOTE_MAX_VALUE_LEN];
+	int	 sourcepid;
+	int	 targetpid;
+	Oid	 userid;
+	bool success;
+	volatile Latch *sender_latch;
+	LWLock	lock;
+} GucRemoteSetting;
+
+static GucRemoteSetting *remote_setting;
+
+volatile bool RemoteGucChangePending = false;
+
 /*
  * Options for enum values defined in this module.
  *
@@ -3137,7 +3168,7 @@ static struct config_int ConfigureNamesInt[] =
 		},
 		&pgstat_track_syscache_usage_interval,
 		0, 0, INT_MAX / 2,
-		NULL, NULL, NULL
+		NULL, &pgstat_track_syscache_assign_hook, NULL
 	},
 
 	{
@@ -4695,7 +4726,6 @@ discard_stack_value(struct config_generic *gconf, config_var_value *val)
 	set_extra_field(gconf, &(val->extra), NULL);
 }
 
-
 /*
  * Fetch the sorted array pointer (exported for help_config.c's use ONLY)
  */
@@ -5487,6 +5517,22 @@ push_old_value(struct config_generic *gconf, GucAction action)
 
 	/* Do we already have a stack entry of the current nest level? */
 	stack = gconf->stack;
+
+	/* NONXACT action make existing stack useles */
+	if (action == GUC_ACTION_NONXACT)
+	{
+		while (stack)
+		{
+			GucStack *prev = stack->prev;
+
+			discard_stack_value(gconf, &stack->prior);
+			discard_stack_value(gconf, &stack->masked);
+			pfree(stack);
+			stack = prev;
+		}
+		stack = gconf->stack = NULL;
+	}
+
 	if (stack && stack->nest_level >= GUCNestLevel)
 	{
 		/* Yes, so adjust its state if necessary */
@@ -5494,28 +5540,63 @@ push_old_value(struct config_generic *gconf, GucAction action)
 		switch (action)
 		{
 			case GUC_ACTION_SET:
-				/* SET overrides any prior action at same nest level */
-				if (stack->state == GUC_SET_LOCAL)
+				if (stack->state == GUC_NONXACT)
 				{
-					/* must discard old masked value */
-					discard_stack_value(gconf, &stack->masked);
+					/* NONXACT rollbacks to the current value */
+					stack->scontext = gconf->scontext;
+					set_stack_value(gconf, &stack->prior);
+					stack->state = GUC_NONXACT_SET;
 				}
-				stack->state = GUC_SET;
+				else 
+				{
+					/* SET overrides other prior actions at same nest level */
+					if (stack->state == GUC_SET_LOCAL)
+					{
+						/* must discard old masked value */
+						discard_stack_value(gconf, &stack->masked);
+					}
+					stack->state = GUC_SET;
+				}
+
 				break;
+
 			case GUC_ACTION_LOCAL:
 				if (stack->state == GUC_SET)
 				{
-					/* SET followed by SET LOCAL, remember SET's value */
+					/* SET followed by SET LOCAL, remember it's value */
 					stack->masked_scontext = gconf->scontext;
 					set_stack_value(gconf, &stack->masked);
 					stack->state = GUC_SET_LOCAL;
 				}
+				else if (stack->state == GUC_NONXACT)
+				{
+					/*
+					 * NONXACT followed by SET LOCAL, both prior and masked
+					 * are set to the current value
+					 */
+					stack->scontext = gconf->scontext;
+					set_stack_value(gconf, &stack->prior);
+					stack->masked_scontext = stack->scontext;
+					stack->masked = stack->prior;
+					stack->state = GUC_NONXACT_LOCAL;
+				}
+				else if (stack->state == GUC_NONXACT_SET)
+				{
+					/* NONXACT_SET followed by SET LOCAL, set masked */
+					stack->masked_scontext = gconf->scontext;
+					set_stack_value(gconf, &stack->masked);
+					stack->state = GUC_NONXACT_LOCAL;
+				}
 				/* in all other cases, no change to stack entry */
 				break;
 			case GUC_ACTION_SAVE:
 				/* Could only have a prior SAVE of same variable */
 				Assert(stack->state == GUC_SAVE);
 				break;
+
+			case GUC_ACTION_NONXACT:
+				Assert(false);
+				break;
 		}
 		Assert(guc_dirty);		/* must be set already */
 		return;
@@ -5531,6 +5612,7 @@ push_old_value(struct config_generic *gconf, GucAction action)
 
 	stack->prev = gconf->stack;
 	stack->nest_level = GUCNestLevel;
+		
 	switch (action)
 	{
 		case GUC_ACTION_SET:
@@ -5542,10 +5624,15 @@ push_old_value(struct config_generic *gconf, GucAction action)
 		case GUC_ACTION_SAVE:
 			stack->state = GUC_SAVE;
 			break;
+		case GUC_ACTION_NONXACT:
+			stack->state = GUC_NONXACT;
+			break;
 	}
 	stack->source = gconf->source;
 	stack->scontext = gconf->scontext;
-	set_stack_value(gconf, &stack->prior);
+
+	if (action != GUC_ACTION_NONXACT)
+		set_stack_value(gconf, &stack->prior);
 
 	gconf->stack = stack;
 
@@ -5640,22 +5727,31 @@ AtEOXact_GUC(bool isCommit, int nestLevel)
 			 * stack entries to avoid leaking memory.  If we do set one of
 			 * those flags, unused fields will be cleaned up after restoring.
 			 */
-			if (!isCommit)		/* if abort, always restore prior value */
-				restorePrior = true;
+			if (!isCommit)
+			{
+				/* GUC_NONXACT does't rollback */
+				if (stack->state != GUC_NONXACT)
+					restorePrior = true;
+			}
 			else if (stack->state == GUC_SAVE)
 				restorePrior = true;
 			else if (stack->nest_level == 1)
 			{
 				/* transaction commit */
-				if (stack->state == GUC_SET_LOCAL)
+				if (stack->state == GUC_SET_LOCAL ||
+					stack->state == GUC_NONXACT_LOCAL)
 					restoreMasked = true;
-				else if (stack->state == GUC_SET)
+				else if (stack->state == GUC_SET ||
+						 stack->state == GUC_NONXACT_SET)
 				{
 					/* we keep the current active value */
 					discard_stack_value(gconf, &stack->prior);
 				}
-				else			/* must be GUC_LOCAL */
+				else if (stack->state != GUC_NONXACT)
+				{
+					/* must be GUC_LOCAL */
 					restorePrior = true;
+				}
 			}
 			else if (prev == NULL ||
 					 prev->nest_level < stack->nest_level - 1)
@@ -5677,11 +5773,27 @@ AtEOXact_GUC(bool isCommit, int nestLevel)
 						break;
 
 					case GUC_SET:
-						/* next level always becomes SET */
-						discard_stack_value(gconf, &stack->prior);
-						if (prev->state == GUC_SET_LOCAL)
+						if (prev->state == GUC_SET ||
+							prev->state == GUC_NONXACT_SET)
+						{
+							discard_stack_value(gconf, &stack->prior);
+						}
+						else if (prev->state == GUC_NONXACT)
+						{
+							prev->scontext = stack->scontext;
+							prev->prior = stack->prior;
+							prev->state = GUC_NONXACT_SET;
+						}
+						else if (prev->state == GUC_SET_LOCAL ||
+								 prev->state == GUC_NONXACT_LOCAL)
+						{
+							discard_stack_value(gconf, &stack->prior);
 							discard_stack_value(gconf, &prev->masked);
-						prev->state = GUC_SET;
+							if (prev->state == GUC_SET_LOCAL)
+								prev->state = GUC_SET;
+							else
+								prev->state = GUC_NONXACT_SET;
+						}
 						break;
 
 					case GUC_LOCAL:
@@ -5692,6 +5804,16 @@ AtEOXact_GUC(bool isCommit, int nestLevel)
 							prev->masked = stack->prior;
 							prev->state = GUC_SET_LOCAL;
 						}
+						else if (prev->state == GUC_NONXACT)
+						{
+							prev->prior = stack->masked;
+							prev->scontext = stack->masked_scontext;
+							prev->masked = stack->masked;
+							prev->masked_scontext = stack->masked_scontext;
+							discard_stack_value(gconf, &stack->prior);
+							discard_stack_value(gconf, &stack->masked);
+							prev->state = GUC_NONXACT_SET;
+						}
 						else
 						{
 							/* else just forget this stack level */
@@ -5700,15 +5822,32 @@ AtEOXact_GUC(bool isCommit, int nestLevel)
 						break;
 
 					case GUC_SET_LOCAL:
-						/* prior state at this level no longer wanted */
-						discard_stack_value(gconf, &stack->prior);
-						/* copy down the masked state */
-						prev->masked_scontext = stack->masked_scontext;
-						if (prev->state == GUC_SET_LOCAL)
-							discard_stack_value(gconf, &prev->masked);
-						prev->masked = stack->masked;
-						prev->state = GUC_SET_LOCAL;
+						if (prev->state == GUC_NONXACT)
+						{
+							prev->prior = stack->prior;
+							prev->masked = stack->prior;
+							discard_stack_value(gconf, &stack->prior);
+							discard_stack_value(gconf, &stack->masked);
+							prev->state = GUC_NONXACT_SET;
+						}
+						else if (prev->state != GUC_NONXACT_SET)
+						{
+							/* prior state at this level no longer wanted */
+							discard_stack_value(gconf, &stack->prior);
+							/* copy down the masked state */
+							prev->masked_scontext = stack->masked_scontext;
+							if (prev->state == GUC_SET_LOCAL)
+								discard_stack_value(gconf, &prev->masked);
+							prev->masked = stack->masked;
+							prev->state = GUC_SET_LOCAL;
+						}
 						break;
+					case GUC_NONXACT:
+					case GUC_NONXACT_SET:
+					case GUC_NONXACT_LOCAL:
+						Assert(false);
+						break;
+						
 				}
 			}
 
@@ -7989,7 +8128,8 @@ set_config_by_name(PG_FUNCTION_ARGS)
 	char	   *name;
 	char	   *value;
 	char	   *new_value;
-	bool		is_local;
+	int			set_action = GUC_ACTION_SET;
+
 
 	if (PG_ARGISNULL(0))
 		ereport(ERROR,
@@ -8009,18 +8149,27 @@ set_config_by_name(PG_FUNCTION_ARGS)
 	 * Get the desired state of is_local. Default to false if provided value
 	 * is NULL
 	 */
-	if (PG_ARGISNULL(2))
-		is_local = false;
-	else
-		is_local = PG_GETARG_BOOL(2);
+	if (!PG_ARGISNULL(2) && PG_GETARG_BOOL(2))
+		set_action = GUC_ACTION_LOCAL;
+
+	/*
+	 * Get the desired state of is_nonxact. Default to false if provided value
+	 * is NULL
+	 */
+	if (!PG_ARGISNULL(3) && PG_GETARG_BOOL(3))
+	{
+		if (set_action == GUC_ACTION_LOCAL)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+					 errmsg("Only one of is_local and is_nonxact can be true")));
+		set_action = GUC_ACTION_NONXACT;
+	}
 
 	/* Note SET DEFAULT (argstring == NULL) is equivalent to RESET */
 	(void) set_config_option(name,
 							 value,
 							 (superuser() ? PGC_SUSET : PGC_USERSET),
-							 PGC_S_SESSION,
-							 is_local ? GUC_ACTION_LOCAL : GUC_ACTION_SET,
-							 true, 0, false);
+							 PGC_S_SESSION, set_action, true, 0, false);
 
 	/* get the new current value */
 	new_value = GetConfigOptionByName(name, NULL, false);
@@ -8029,7 +8178,6 @@ set_config_by_name(PG_FUNCTION_ARGS)
 	PG_RETURN_TEXT_P(cstring_to_text(new_value));
 }
 
-
 /*
  * Common code for DefineCustomXXXVariable subroutines: allocate the
  * new variable's config struct and fill in generic fields.
@@ -8228,6 +8376,13 @@ reapply_stacked_values(struct config_generic *variable,
 										 WARNING, false);
 				break;
 
+			case GUC_NONXACT:
+				(void) set_config_option(name, curvalue,
+										 curscontext, cursource,
+										 GUC_ACTION_NONXACT, true,
+										 WARNING, false);
+				break;
+
 			case GUC_LOCAL:
 				(void) set_config_option(name, curvalue,
 										 curscontext, cursource,
@@ -8247,6 +8402,33 @@ reapply_stacked_values(struct config_generic *variable,
 										 GUC_ACTION_LOCAL, true,
 										 WARNING, false);
 				break;
+
+			case GUC_NONXACT_SET:
+				/* first, apply the masked value as SET */
+				(void) set_config_option(name, stack->masked.val.stringval,
+										 stack->masked_scontext, PGC_S_SESSION,
+										 GUC_ACTION_NONXACT, true,
+										 WARNING, false);
+				/* then apply the current value as LOCAL */
+				(void) set_config_option(name, curvalue,
+										 curscontext, cursource,
+										 GUC_ACTION_SET, true,
+										 WARNING, false);
+				break;
+
+			case GUC_NONXACT_LOCAL:
+				/* first, apply the masked value as SET */
+				(void) set_config_option(name, stack->masked.val.stringval,
+										 stack->masked_scontext, PGC_S_SESSION,
+										 GUC_ACTION_NONXACT, true,
+										 WARNING, false);
+				/* then apply the current value as LOCAL */
+				(void) set_config_option(name, curvalue,
+										 curscontext, cursource,
+										 GUC_ACTION_LOCAL, true,
+										 WARNING, false);
+				break;
+
 		}
 
 		/* If we successfully made a stack entry, adjust its nest level */
@@ -10225,6 +10407,373 @@ GUCArrayReset(ArrayType *array)
 	return newarray;
 }
 
+Size
+GucShmemSize(void)
+{
+	Size size;
+
+	size = sizeof(GucRemoteSetting);
+
+	return size;
+}
+
+void
+GucShmemInit(void)
+{
+	Size	size;
+	bool	found;
+
+	size = sizeof(GucRemoteSetting);
+	remote_setting = (GucRemoteSetting *)
+		ShmemInitStruct("GUC remote setting", size, &found);
+
+	if (!found)
+	{
+		MemSet(remote_setting, 0, size);
+		LWLockInitialize(&remote_setting->lock, LWLockNewTrancheId());
+	}
+
+	LWLockRegisterTranche(remote_setting->lock.tranche, "guc_remote");
+}
+
+/*
+ * set_backend_config: SQL callable function to set GUC variable of remote
+ * session.
+ */
+Datum
+set_backend_config(PG_FUNCTION_ARGS)
+{
+	int		pid   = PG_GETARG_INT32(0);
+	char   *name  = text_to_cstring(PG_GETARG_TEXT_P(1));
+	char   *value = text_to_cstring(PG_GETARG_TEXT_P(2));
+	TimestampTz	cancel_start;
+	PgBackendStatus *beentry;
+	int beid;
+	int rc;
+
+	if (strlen(name) >= NAMEDATALEN)
+		ereport(ERROR,
+				(errcode(ERRCODE_NAME_TOO_LONG),
+				 errmsg("name of GUC variable is too long")));
+	if (strlen(value) >= GUC_REMOTE_MAX_VALUE_LEN)
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("value is too long"),
+				 errdetail("Maximum acceptable length of value is %d",
+					 GUC_REMOTE_MAX_VALUE_LEN - 1)));
+
+	/* find beentry for given pid */
+	beentry = NULL;
+	for (beid = 1;
+		 (beentry = pgstat_fetch_stat_beentry(beid)) &&
+			 beentry->st_procpid != pid ;
+		 beid++);
+
+	/*
+	 * This will be checked out by SendProcSignal but do here to emit
+	 * appropriate message message.
+	 */
+	if (!beentry)
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("process PID %d not found", pid)));
+
+	/* allow only client backends */
+	if (beentry->st_backendType != B_BACKEND)
+		ereport(ERROR,
+				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+				 errmsg("not a client backend")));
+	
+	/*
+	 * Wait if someone is sending a request. We need to wait with timeout
+	 * since the current user of the struct doesn't wake me up.
+	 */
+	LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+	while (remote_setting->state != REMGUC_VACANT)
+	{
+		LWLockRelease(&remote_setting->lock);
+		rc = WaitLatch(&MyProc->procLatch,
+					   WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
+					   200, PG_WAIT_ACTIVITY);
+
+		if (rc & WL_POSTMASTER_DEATH)
+			return (Datum) BoolGetDatum(false);
+
+		CHECK_FOR_INTERRUPTS();
+
+		LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+	}
+
+	/* my turn, send a request */
+	Assert(remote_setting->state == REMGUC_VACANT);
+
+	remote_setting->state = REMGUC_REQUEST;
+	remote_setting->sourcepid = MyProcPid;
+	remote_setting->targetpid = pid;
+	remote_setting->userid = GetUserId();
+
+	strncpy(remote_setting->name, name, NAMEDATALEN);
+	remote_setting->name[NAMEDATALEN - 1] = 0;
+	strncpy(remote_setting->value, value, GUC_REMOTE_MAX_VALUE_LEN);
+	remote_setting->value[GUC_REMOTE_MAX_VALUE_LEN - 1] = 0;
+	remote_setting->sender_latch = MyLatch;
+
+	LWLockRelease(&remote_setting->lock);
+
+	if (SendProcSignal(pid, PROCSIG_REMOTE_GUC, InvalidBackendId) < 0)
+	{
+		remote_setting->state = REMGUC_VACANT;
+		ereport(ERROR,
+				(errmsg("could not signal backend with PID %d: %m", pid)));
+	}
+
+	/*
+	 * This request is processed only while idle time of peer so it may take a
+	 * long time before we get a response.
+	 */
+	LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+	while (remote_setting->state != REMGUC_DONE)
+	{
+		LWLockRelease(&remote_setting->lock);
+		rc = WaitLatch(&MyProc->procLatch,
+					   WL_LATCH_SET | WL_POSTMASTER_DEATH,
+					   -1, PG_WAIT_ACTIVITY);
+
+		/* don't care of the state in the case.. */
+		if (rc & WL_POSTMASTER_DEATH)
+			return (Datum) BoolGetDatum(false);
+
+		LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+
+		/* get out if we got a query cancel request */
+		if (QueryCancelPending)
+			break;
+	}
+
+	/*
+	 * Cancel the requset if possible. We cannot cancel the request in the
+	 * case peer have processed it. We don't see QueryCancelPending but the
+	 * request status so that the case is handled properly.
+	 */
+	if (remote_setting->state == REMGUC_REQUEST)
+	{
+		Assert(QueryCancelPending);
+
+		remote_setting->state = REMGUC_CANCELING;
+		LWLockRelease(&remote_setting->lock);
+
+		if (SendProcSignal(pid,
+						   PROCSIG_REMOTE_GUC, InvalidBackendId) < 0)
+		{
+			remote_setting->state = REMGUC_VACANT;
+			ereport(ERROR,
+					(errmsg("could not signal backend with PID %d: %m",
+							pid)));
+		}
+
+		/* Peer must respond shortly, don't sleep for a long time. */
+		
+		cancel_start = GetCurrentTimestamp();
+
+		LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+		while (remote_setting->state != REMGUC_CANCELED &&
+			   !TimestampDifferenceExceeds(cancel_start, GetCurrentTimestamp(),
+										   GUC_REMOTE_CANCEL_TIMEOUT))
+		{
+			LWLockRelease(&remote_setting->lock);
+			rc = WaitLatch(&MyProc->procLatch,
+						   WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
+						   GUC_REMOTE_CANCEL_TIMEOUT, PG_WAIT_ACTIVITY);
+
+			/* don't care of the state in the case.. */
+			if (rc & WL_POSTMASTER_DEATH)
+				return (Datum) BoolGetDatum(false);
+
+			LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+		}
+
+		if (remote_setting->state != REMGUC_CANCELED)
+		{
+			remote_setting->state = REMGUC_VACANT;
+			ereport(ERROR, (errmsg("failed cancelling remote GUC request")));
+		}
+
+		remote_setting->state = REMGUC_VACANT;
+		LWLockRelease(&remote_setting->lock);
+
+		ereport(INFO,
+				(errmsg("remote GUC change request to PID %d is canceled",
+							  pid)));
+
+		return (Datum) BoolGetDatum(false);
+	}
+
+	Assert (remote_setting->state == REMGUC_DONE);
+
+	/* ereport exits on query cancel, we need this before that */
+	remote_setting->state = REMGUC_VACANT;
+
+	if (QueryCancelPending)
+		ereport(INFO,
+				(errmsg("remote GUC change request to PID %d already completed",
+						pid)));
+				
+	if (!remote_setting->success)
+		ereport(ERROR,
+				(errmsg("%s", remote_setting->value)));
+
+	LWLockRelease(&remote_setting->lock);
+
+	return (Datum) BoolGetDatum(true);
+}
+
+
+void
+HandleRemoteGucSetInterrupt(void)
+{
+	LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+
+	/* check if any request is being sent to me */
+	if (remote_setting->targetpid == MyProcPid)
+	{
+		switch (remote_setting->state)
+		{
+		case REMGUC_REQUEST:
+			InterruptPending = true;
+			RemoteGucChangePending = true;
+			break;
+		case REMGUC_CANCELING:
+			InterruptPending = true;
+			RemoteGucChangePending = true;
+			remote_setting->state = REMGUC_CANCELED;
+			SetLatch(remote_setting->sender_latch);
+			break;
+		default:
+			break;
+		}
+	}
+	LWLockRelease(&remote_setting->lock);
+}
+
+void
+HandleGucRemoteChanges(void)
+{
+	MemoryContext currentcxt = CurrentMemoryContext;
+	bool	canceling = false;
+	bool	process_request = true;
+	int		saveInterruptHoldoffCount = 0;
+	int		saveQueryCancelHoldoffCount = 0;
+
+	RemoteGucChangePending = false;
+	LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+
+	/* skip if this request is no longer for me */
+	if (remote_setting->targetpid != MyProcPid)
+		process_request = false;
+	else
+	{
+		switch (remote_setting->state)
+		{
+		case REMGUC_REQUEST:
+			remote_setting->state = REMGUC_INPROCESS;
+			break;
+		case REMGUC_CANCELING:
+			/*
+			 * This request is already canceled but entered this function
+			 * before receiving signal. Cancel the request here.
+			 */
+			remote_setting->state = REMGUC_CANCELED;
+			remote_setting->success = false;
+			canceling = true;
+			break;
+		case REMGUC_VACANT:
+		case REMGUC_CANCELED:
+		case REMGUC_INPROCESS:
+		case REMGUC_DONE:
+			/* Just ignore the cases */
+			process_request = false;
+			break;
+		}
+	}
+
+	LWLockRelease(&remote_setting->lock);
+
+	if (!process_request)
+		return;
+
+	if (canceling)
+	{
+		SetLatch(remote_setting->sender_latch);
+		return;
+	}
+
+
+	/* Okay, actually modify variable */
+	remote_setting->success = true;
+
+	PG_TRY();
+	{
+		bool 	has_privilege;
+		bool 	is_superuser;
+		bool end_transaction = false;
+		/*
+		 * XXXX: ERROR resets the following varialbes but we don't want that.
+		 */
+		saveInterruptHoldoffCount = InterruptHoldoffCount;
+		saveQueryCancelHoldoffCount = QueryCancelHoldoffCount;
+
+		/* superuser_arg requires a transaction */
+		if (!IsTransactionState())
+		{
+			StartTransactionCommand();
+			end_transaction  = true;
+		}
+		is_superuser = superuser_arg(remote_setting->userid);
+		has_privilege = is_superuser ||
+			has_privs_of_role(remote_setting->userid, GetUserId());
+
+		if (end_transaction)
+			CommitTransactionCommand();
+
+		if (!has_privilege)
+			elog(ERROR, "role %u is not allowed to set GUC variables on the session with PID %d",
+				 remote_setting->userid, MyProcPid);
+		
+		(void) set_config_option(remote_setting->name, remote_setting->value,
+								 is_superuser ? PGC_SUSET : PGC_USERSET,
+								 PGC_S_SESSION, GUC_ACTION_NONXACT,
+								 true, ERROR, false);
+	}
+	PG_CATCH();
+	{
+		ErrorData *errdata;
+		MemoryContextSwitchTo(currentcxt);
+		errdata = CopyErrorData();
+		remote_setting->success = false;
+		strncpy(remote_setting->value, errdata->message,
+				GUC_REMOTE_MAX_VALUE_LEN);
+		remote_setting->value[GUC_REMOTE_MAX_VALUE_LEN - 1] = 0;
+		FlushErrorState();
+
+		/* restore the saved value */
+		InterruptHoldoffCount = saveInterruptHoldoffCount ;
+		QueryCancelHoldoffCount = saveQueryCancelHoldoffCount;
+		
+	}
+	PG_END_TRY();
+
+	ereport(LOG,
+			(errmsg("GUC variable \"%s\" is changed to \"%s\" by request from another backend with PID %d",
+					remote_setting->name, remote_setting->value,
+					remote_setting->sourcepid)));
+
+	LWLockAcquire(&remote_setting->lock, LW_EXCLUSIVE);
+	remote_setting->state = REMGUC_DONE;
+	LWLockRelease(&remote_setting->lock);
+
+	SetLatch(remote_setting->sender_latch);
+}
+
 /*
  * Validate a proposed option setting for GUCArrayAdd/Delete/Reset.
  *
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 4de9fdee44..62a64db022 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -5647,8 +5647,8 @@
   proargtypes => 'text bool', prosrc => 'show_config_by_name_missing_ok' },
 { oid => '2078', descr => 'SET X as a function',
   proname => 'set_config', proisstrict => 'f', provolatile => 'v',
-  proparallel => 'u', prorettype => 'text', proargtypes => 'text text bool',
-  prosrc => 'set_config_by_name' },
+  proparallel => 'u', prorettype => 'text',
+  proargtypes => 'text text bool bool', prosrc => 'set_config_by_name' },
 { oid => '2084', descr => 'SHOW ALL as a function',
   proname => 'pg_show_all_settings', prorows => '1000', proretset => 't',
   provolatile => 's', prorettype => 'record', proargtypes => '',
@@ -9625,6 +9625,12 @@
   proargmodes => '{i,o,o,o,o,o,o,o,o,o}',
   proargnames => '{pid,relid,indid,size,ntup,searches,hits,neg_hits,ageclass,last_update}',
   prosrc => 'pgstat_get_syscache_stats' },
+{ oid => '3424',
+  descr => 'set config of another backend',
+  proname => 'pg_set_backend_config', proisstrict => 'f',
+  proretset => 'f', provolatile => 'v', proparallel => 'u',
+  prorettype => 'bool', proargtypes => 'int4 text text',
+  prosrc => 'set_backend_config' },
 { oid => '3786', descr => 'set up a logical replication slot',
   proname => 'pg_create_logical_replication_slot', provolatile => 'v',
   proparallel => 'u', prorettype => 'record', proargtypes => 'name name bool',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 20add5052c..198fa42f80 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -833,7 +833,8 @@ typedef enum
 	WAIT_EVENT_REPLICATION_ORIGIN_DROP,
 	WAIT_EVENT_REPLICATION_SLOT_DROP,
 	WAIT_EVENT_SAFE_SNAPSHOT,
-	WAIT_EVENT_SYNC_REP
+	WAIT_EVENT_SYNC_REP,
+	WAIT_EVENT_REMOTE_GUC
 } WaitEventIPC;
 
 /* ----------
diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h
index 6db0d69b71..4ad4927d3d 100644
--- a/src/include/storage/procsignal.h
+++ b/src/include/storage/procsignal.h
@@ -42,6 +42,9 @@ typedef enum
 	PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
 	PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK,
 
+	/* Remote GUC setting */
+	PROCSIG_REMOTE_GUC,
+
 	NUM_PROCSIGNALS				/* Must be last! */
 } ProcSignalReason;
 
diff --git a/src/include/utils/guc.h b/src/include/utils/guc.h
index df2e556b02..0f3498fc6d 100644
--- a/src/include/utils/guc.h
+++ b/src/include/utils/guc.h
@@ -193,7 +193,8 @@ typedef enum
 	/* Types of set_config_option actions */
 	GUC_ACTION_SET,				/* regular SET command */
 	GUC_ACTION_LOCAL,			/* SET LOCAL command */
-	GUC_ACTION_SAVE				/* function SET option, or temp assignment */
+	GUC_ACTION_SAVE,			/* function SET option, or temp assignment */
+	GUC_ACTION_NONXACT			/* transactional setting */
 } GucAction;
 
 #define GUC_QUALIFIER_SEPARATOR '.'
@@ -268,6 +269,8 @@ extern int	tcp_keepalives_idle;
 extern int	tcp_keepalives_interval;
 extern int	tcp_keepalives_count;
 
+extern volatile bool RemoteGucChangePending;
+
 #ifdef TRACE_SORT
 extern bool trace_sort;
 #endif
@@ -275,6 +278,11 @@ extern bool trace_sort;
 /*
  * Functions exported by guc.c
  */
+extern Size GucShmemSize(void);
+extern void GucShmemInit(void);
+extern Datum set_backend_setting(PG_FUNCTION_ARGS);
+extern void HandleRemoteGucSetInterrupt(void);
+extern void HandleGucRemoteChanges(void);
 extern void SetConfigOption(const char *name, const char *value,
 				GucContext context, GucSource source);
 
@@ -394,6 +402,9 @@ extern Size EstimateGUCStateSpace(void);
 extern void SerializeGUCState(Size maxsize, char *start_address);
 extern void RestoreGUCState(void *gucstate);
 
+/* Remote GUC setting */
+extern void HandleGucRemoteChanges(void);
+
 /* Support for messages reported from GUC check hooks */
 
 extern PGDLLIMPORT char *GUC_check_errmsg_string;
diff --git a/src/include/utils/guc_tables.h b/src/include/utils/guc_tables.h
index 6f9fdb6a5f..4980a01c97 100644
--- a/src/include/utils/guc_tables.h
+++ b/src/include/utils/guc_tables.h
@@ -115,7 +115,10 @@ typedef enum
 	GUC_SAVE,					/* entry caused by function SET option */
 	GUC_SET,					/* entry caused by plain SET command */
 	GUC_LOCAL,					/* entry caused by SET LOCAL command */
-	GUC_SET_LOCAL				/* entry caused by SET then SET LOCAL */
+	GUC_NONXACT,				/* entry caused by non-transactional ops */
+	GUC_SET_LOCAL,				/* entry caused by SET then SET LOCAL */
+	GUC_NONXACT_SET,			/* entry caused by NONXACT then SET */
+	GUC_NONXACT_LOCAL			/* entry caused by NONXACT then (SET)LOCAL */
 } GucStackState;
 
 typedef struct guc_stack
diff --git a/src/test/regress/expected/guc.out b/src/test/regress/expected/guc.out
index 43ac5f5f11..2c074705c7 100644
--- a/src/test/regress/expected/guc.out
+++ b/src/test/regress/expected/guc.out
@@ -476,6 +476,229 @@ SELECT '2006-08-13 12:34:56'::timestamptz;
  2006-08-13 12:34:56-07
 (1 row)
 
+-- NONXACT followed by SET, SET LOCAL through COMMIT
+BEGIN;
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+ set_config 
+------------
+ 128kB
+(1 row)
+
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SHOW work_mem;	-- must see 512kB
+ work_mem 
+----------
+ 512kB
+(1 row)
+
+COMMIT;
+SHOW work_mem;	-- must see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+-- NONXACT followed by SET, SET LOCAL through ROLLBACK
+BEGIN;
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+ set_config 
+------------
+ 128kB
+(1 row)
+
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SHOW work_mem;	-- must see 512kB
+ work_mem 
+----------
+ 512kB
+(1 row)
+
+ROLLBACK;
+SHOW work_mem;	-- must see 128kB
+ work_mem 
+----------
+ 128kB
+(1 row)
+
+-- SET, SET LOCAL followed by NONXACT through COMMIT
+BEGIN;
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+ set_config 
+------------
+ 128kB
+(1 row)
+
+SHOW work_mem;	-- must see 128kB
+ work_mem 
+----------
+ 128kB
+(1 row)
+
+COMMIT;
+SHOW work_mem;	-- must see 128kB
+ work_mem 
+----------
+ 128kB
+(1 row)
+
+-- SET, SET LOCAL followed by NONXACT through ROLLBACK
+BEGIN;
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+ set_config 
+------------
+ 128kB
+(1 row)
+
+SHOW work_mem;	-- must see 128kB
+ work_mem 
+----------
+ 128kB
+(1 row)
+
+ROLLBACK;
+SHOW work_mem;	-- must see 128kB
+ work_mem 
+----------
+ 128kB
+(1 row)
+
+-- NONXACT and SAVEPOINT
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+ set_config 
+------------
+ 256kB
+(1 row)
+
+SHOW work_mem;
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+SET LOCAL work_mem TO '384kB';
+RELEASE SAVEPOINT a;
+SHOW work_mem; -- will see 384kB
+ work_mem 
+----------
+ 384kB
+(1 row)
+
+COMMIT;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+ set_config 
+------------
+ 256kB
+(1 row)
+
+SHOW work_mem;
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+SET LOCAL work_mem TO '384kB';
+ROLLBACK TO SAVEPOINT a;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+ROLLBACK;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SET LOCAL work_mem TO '384kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+ set_config 
+------------
+ 256kB
+(1 row)
+
+SHOW work_mem;
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+SET LOCAL work_mem TO '384kB';
+RELEASE SAVEPOINT a;
+SHOW work_mem; -- will see 384kB
+ work_mem 
+----------
+ 384kB
+(1 row)
+
+ROLLBACK;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SET LOCAL work_mem TO '384kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+ set_config 
+------------
+ 256kB
+(1 row)
+
+SHOW work_mem;
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+SET LOCAL work_mem TO '384kB';
+ROLLBACK TO SAVEPOINT a;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+COMMIT;
+SHOW work_mem; -- will see 256kB
+ work_mem 
+----------
+ 256kB
+(1 row)
+
+SET work_mem TO DEFAULT;
 --
 -- Test RESET.  We use datestyle because the reset value is forced by
 -- pg_regress, so it doesn't depend on the installation's configuration.
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index 735dd37acf..3569edc22d 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1918,6 +1918,30 @@ pg_stat_sys_tables| SELECT pg_stat_all_tables.relid,
     pg_stat_all_tables.autoanalyze_count
    FROM pg_stat_all_tables
   WHERE ((pg_stat_all_tables.schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (pg_stat_all_tables.schemaname ~ '^pg_toast'::text));
+pg_stat_syscache| SELECT s.pid,
+    (s.relid)::regclass AS relname,
+    (s.indid)::regclass AS cache_name,
+    s.size,
+    s.ntup AS ntuples,
+    s.searches,
+    s.hits,
+    s.neg_hits,
+    s.ageclass,
+    s.nentries,
+    s.last_update
+   FROM (pg_stat_activity a
+     JOIN LATERAL ( SELECT a.pid,
+            pg_get_syscache_stats.relid,
+            pg_get_syscache_stats.indid,
+            pg_get_syscache_stats.size,
+            pg_get_syscache_stats.ntup,
+            pg_get_syscache_stats.searches,
+            pg_get_syscache_stats.hits,
+            pg_get_syscache_stats.neg_hits,
+            pg_get_syscache_stats.ageclass,
+            pg_get_syscache_stats.nentries,
+            pg_get_syscache_stats.last_update
+           FROM pg_get_syscache_stats(a.pid) pg_get_syscache_stats(relid, indid, size, ntup, searches, hits, neg_hits, ageclass, nentries, last_update)) s ON ((a.pid = s.pid)));
 pg_stat_user_functions| SELECT p.oid AS funcid,
     n.nspname AS schemaname,
     p.proname AS funcname,
@@ -2349,7 +2373,7 @@ pg_settings|pg_settings_n|CREATE RULE pg_settings_n AS
     ON UPDATE TO pg_catalog.pg_settings DO INSTEAD NOTHING;
 pg_settings|pg_settings_u|CREATE RULE pg_settings_u AS
     ON UPDATE TO pg_catalog.pg_settings
-   WHERE (new.name = old.name) DO  SELECT set_config(old.name, new.setting, false) AS set_config;
+   WHERE (new.name = old.name) DO  SELECT set_config(old.name, new.setting, false, false) AS set_config;
 rtest_emp|rtest_emp_del|CREATE RULE rtest_emp_del AS
     ON DELETE TO public.rtest_emp DO  INSERT INTO rtest_emplog (ename, who, action, newsal, oldsal)
   VALUES (old.ename, CURRENT_USER, 'fired'::bpchar, '$0.00'::money, old.salary);
diff --git a/src/test/regress/sql/guc.sql b/src/test/regress/sql/guc.sql
index 23e5029780..2fb23caafe 100644
--- a/src/test/regress/sql/guc.sql
+++ b/src/test/regress/sql/guc.sql
@@ -133,6 +133,94 @@ SHOW vacuum_cost_delay;
 SHOW datestyle;
 SELECT '2006-08-13 12:34:56'::timestamptz;
 
+-- NONXACT followed by SET, SET LOCAL through COMMIT
+BEGIN;
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SHOW work_mem;	-- must see 512kB
+COMMIT;
+SHOW work_mem;	-- must see 256kB
+
+-- NONXACT followed by SET, SET LOCAL through ROLLBACK
+BEGIN;
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SHOW work_mem;	-- must see 512kB
+ROLLBACK;
+SHOW work_mem;	-- must see 128kB
+
+-- SET, SET LOCAL followed by NONXACT through COMMIT
+BEGIN;
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+SHOW work_mem;	-- must see 128kB
+COMMIT;
+SHOW work_mem;	-- must see 128kB
+
+-- SET, SET LOCAL followed by NONXACT through ROLLBACK
+BEGIN;
+SET work_mem to '256kB';
+SET LOCAL work_mem to '512kB';
+SELECT set_config('work_mem', '128kB', false, true); -- NONXACT
+SHOW work_mem;	-- must see 128kB
+ROLLBACK;
+SHOW work_mem;	-- must see 128kB
+
+-- NONXACT and SAVEPOINT
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+SHOW work_mem;
+SET LOCAL work_mem TO '384kB';
+RELEASE SAVEPOINT a;
+SHOW work_mem; -- will see 384kB
+COMMIT;
+SHOW work_mem; -- will see 256kB
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+SHOW work_mem;
+SET LOCAL work_mem TO '384kB';
+ROLLBACK TO SAVEPOINT a;
+SHOW work_mem; -- will see 256kB
+ROLLBACK;
+SHOW work_mem; -- will see 256kB
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SET LOCAL work_mem TO '384kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+SHOW work_mem;
+SET LOCAL work_mem TO '384kB';
+RELEASE SAVEPOINT a;
+SHOW work_mem; -- will see 384kB
+ROLLBACK;
+SHOW work_mem; -- will see 256kB
+--
+SET work_mem TO '64kB';
+BEGIN;
+SET work_mem TO '128kB';
+SET LOCAL work_mem TO '384kB';
+SAVEPOINT a;
+SELECT set_config('work_mem', '256kB', false, true); -- NONXACT
+SHOW work_mem;
+SET LOCAL work_mem TO '384kB';
+ROLLBACK TO SAVEPOINT a;
+SHOW work_mem; -- will see 256kB
+COMMIT;
+SHOW work_mem; -- will see 256kB
+
+SET work_mem TO DEFAULT;
 --
 -- Test RESET.  We use datestyle because the reset value is forced by
 -- pg_regress, so it doesn't depend on the installation's configuration.
-- 
2.16.3

