On Mon, Nov 23, 2026 at 2:47 PM Andrey Borodin <[email protected]> wrote:

> Hi Stepan,
>
> On November 22, 2026, Stepan Neretin wrote:
> > with pgarch feeding file names and getting
> > completed or failed files back one by one?
>
> Yes, that is still the direction I'd prefer. I'd like us to consider
> the archive/restore interface more broadly than parallel execution of
> archive_command.
>
> One missing piece is distinguishing a missing file from a failed
> attempt to check or retrieve it. We use restore_command results to
> discover timelines. Today, an ordinary command failure followed by a
> missing local history file makes existsTimeLineHistory() return false.
> An unavailable archive can therefore look like an unused timeline ID.
> PostgreSQL needs to distinguish not-found from retryable and
> non-retryable errors, rather than infer all of that from success or
> failure of a shell command. That is a correctness issue, not a
> throughput optimization.
>
> For archiving, I'd like a stream of ready files and independent
> per-file acknowledgments, without waiting for a whole batch. Completion
> can be out of order. The contract should distinguish a file being
> durably archived from merely being queued, and describe retry behavior.
> Your submit/poll callbacks look like a useful starting point.
>
> Tools such as WAL-G and pgBackRest already implement parallelism behind
> the synchronous API. In WAL-G we predict adjacent .ready names to avoid
> directory scans, periodically scan for missed or failed uploads, and
> make our own scheduling decisions. PostgreSQL still sees what looks
> like a request to push one file. I'd rather give these tools the
> information they need than make them reconstruct it from archive_status.
>
> I'd also like PostgreSQL to control archive/restore concurrency limits
> and select work, while leaving execution to the tool. For example,
> WAL-G prefetch guesses subsequent segment names and can issue useless
> requests on the old timeline near a switch. When PostgreSQL already has
> the relevant history, it knows where that switch is. Passing the
> intended files to the tool would avoid duplicating that knowledge.
>
> I don't suggest implementing all of this in one patch. Could we first
> agree on the contract we want the async interface to support, including
> a long-lived external process and the restore side, and then build it
> incrementally?
>
> Thank you!
>
>
> Best regards, Andrey Borodin.
>
>

Hi Andrey,

Thanks for the reply.

I agree: stream ready files, get answers one by one, keep a long-lived
helper, and grow the restore side later instead of doing everything at
once.

On Discord, Robert Haas and Christoph Berg said much the same about the
jobs-pool draft.  Robert did not want one short-lived child per file:
warm connections and parallel transfer should live in one helper, or in
a C module.  Christoph wanted archive_library and a simple stdin
protocol with per-file ok/fail answers.  So please treat
archive_command_jobs as superseded.

This series is only the archive side.  A module can keep the old sync
callback, or use submit/poll/cancel.  Each file comes back as success,
retry, or fail, and only pgarch marks .done.  archive_async_max limits
how many files are in flight (default 8).  For shell users there is one
long-lived helper:

  -> archive\t<file>\t<path>
  <- archived\t<file>\tok|retry|fail

No handshake in v1, no %f/%p, Unix only.

Restore can reuse the same helper later with a second verb, plus a
missing answer so timeline probes can tell "not in archive" from "try
again".  Something like:

  -> restore\t<file>\t<path>
  <- restored\t<file>\tok|missing|retry|fail

Classic restore_command would stay as it is.  I would rather settle the
archive half first, then mail that as a follow-up.

Attached v2:

0001 Support async archive callbacks in pgarch.
0002 Add persistent archive_command protocol.
0003 Add TAP coverage for persistent archive_command.

If 0001 alone is easier to review first, I can hold the rest.

Does this direction look closer?

Regards,
Stepan Neretin

[1]
https://www.postgresql.org/message-id/CA%2BYyo5TfMpUE3s%3DWKrWcaYbBWbO2VNyRnRt_5hy-VPrMhjXVWg%40mail.gmail.com
[2]
https://www.postgresql.org/message-id/ECB4BF94-9B6F-4A85-ADA7-4AFBD77C03CD%40yandex-team.ru
[3] https://commitfest.postgresql.org/patch/7686/
From 6841891fa907128ac245591000e082783435dfdd Mon Sep 17 00:00:00 2001
From: Stepan Neretin <[email protected]>
Date: Mon, 23 Nov 2026 22:56:42 +0700
Subject: [PATCH 1/3] Support async archive callbacks in pgarch.

Let archive modules keep several WAL files in flight with submit/poll/
cancel instead of the one-file sync callback.  Each file comes back as
success, retry, or fail, and only pgarch marks .done.  archive_async_max
limits how many are outstanding (default 8).

Discussion: https://postgr.es/m/CA+Yyo5TfMpUE3s=wkrwcaybbwbo2vnyrnrt_5hy-vprmhjx...@mail.gmail.com
---
 doc/src/sgml/archive-modules.sgml             |  61 +-
 src/backend/access/transam/xlog.c             |   1 +
 src/backend/postmaster/pgarch.c               | 676 ++++++++++++++----
 src/backend/utils/misc/guc_parameters.dat     |   9 +
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/access/xlog.h                     |   1 +
 src/include/archive/archive_module.h          |  20 +-
 src/tools/pgindent/typedefs.list              |   5 +
 8 files changed, 639 insertions(+), 135 deletions(-)

diff --git a/doc/src/sgml/archive-modules.sgml b/doc/src/sgml/archive-modules.sgml
index 10ec96eae96..c109c71692e 100644
--- a/doc/src/sgml/archive-modules.sgml
+++ b/doc/src/sgml/archive-modules.sgml
@@ -60,13 +60,19 @@ typedef struct ArchiveModuleCallbacks
     ArchiveStartupCB startup_cb;
     ArchiveCheckConfiguredCB check_configured_cb;
     ArchiveFileCB archive_file_cb;
+    ArchiveSubmitCB submit_cb;
+    ArchivePollCB poll_cb;
+    ArchiveCancelCB cancel_cb;
     ArchiveShutdownCB shutdown_cb;
 } ArchiveModuleCallbacks;
 typedef const ArchiveModuleCallbacks *(*ArchiveModuleInit) (void);
 </programlisting>
 
-   Only the <function>archive_file_cb</function> callback is required.  The
-   others are optional.
+   A module must provide either <function>archive_file_cb</function> for
+   synchronous archiving, or both <function>submit_cb</function> and
+   <function>poll_cb</function> for asynchronous archiving.  Asynchronous
+   modules must also provide <function>cancel_cb</function>.  The remaining
+   callbacks are optional.
   </para>
  </sect1>
 
@@ -157,6 +163,57 @@ typedef bool (*ArchiveFileCB) (ArchiveModuleState *state, const char *file, cons
    </note>
   </sect2>
 
+  <sect2 id="archive-module-submit">
+   <title>Submit Callback</title>
+   <para>
+    The <function>submit_cb</function> callback starts archiving one WAL file
+    and must not wait for completion.  Returning <literal>false</literal> means
+    temporary backpressure; the archiver will try again later.
+    <replaceable>file</replaceable> and <replaceable>path</replaceable> have
+    the same meaning as for <function>archive_file_cb</function>.
+
+<programlisting>
+typedef bool (*ArchiveSubmitCB) (ArchiveModuleState *state, const char *file, const char *path);
+</programlisting>
+   </para>
+  </sect2>
+
+  <sect2 id="archive-module-poll">
+   <title>Poll Callback</title>
+   <para>
+    The <function>poll_cb</function> callback waits up to
+    <replaceable>timeout_ms</replaceable> milliseconds for one in-flight
+    archive to complete.  On <literal>true</literal>,
+    <replaceable>*file</replaceable> and <replaceable>*status</replaceable>
+    identify the completed file and must remain valid until the next
+    <function>submit_cb</function> or <function>poll_cb</function> call.
+    Completions may arrive out of order.
+    <literal>ARCHIVE_RESULT_RETRY</literal> asks the archiver to try the file
+    again; <literal>ARCHIVE_RESULT_FAIL</literal> makes it give up for this
+    cycle.
+
+<programlisting>
+typedef bool (*ArchivePollCB) (ArchiveModuleState *state, const char **file,
+                               ArchiveResultStatus *status, long timeout_ms);
+</programlisting>
+   </para>
+  </sect2>
+
+  <sect2 id="archive-module-cancel">
+   <title>Cancel Callback</title>
+   <para>
+    The <function>cancel_cb</function> callback drops all in-flight archive
+    work when the archiver aborts a cycle (for example on shutdown or after a
+    callback error).  It must be safe to call when nothing is in flight.
+    Unlike <function>shutdown_cb</function>, it does not mean the archiver
+    process is exiting.
+
+<programlisting>
+typedef void (*ArchiveCancelCB) (ArchiveModuleState *state);
+</programlisting>
+   </para>
+  </sect2>
+
   <sect2 id="archive-module-shutdown">
    <title>Shutdown Callback</title>
    <para>
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..9419325d2a2 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -125,6 +125,7 @@ int			XLOGbuffers = -1;
 int			XLogArchiveTimeout = 0;
 int			XLogArchiveMode = ARCHIVE_MODE_OFF;
 char	   *XLogArchiveCommand = NULL;
+int			XLogArchiveAsyncMax = 8;
 bool		EnableHotStandby = false;
 bool		fullPageWrites = true;
 bool		wal_log_hints = false;
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index a3fd4f83201..e1122f76760 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -65,6 +65,8 @@
 									 * archive status directory; in seconds. */
 #define PGARCH_RESTART_INTERVAL 10	/* How often to attempt to restart a
 									 * failed archiver; in seconds. */
+#define PGARCH_ASYNC_POLL_MS	1000L
+#define PGARCH_ASYNC_STOP_GRACE_S	60
 
 /*
  * Maximum number of retries allowed when attempting to archive a WAL
@@ -82,6 +84,8 @@
  * Maximum number of .ready files to gather per directory scan.
  */
 #define NUM_FILES_PER_DIRECTORY_SCAN 64
+/* Must match archive_async_max GUC max. */
+#define ARCHIVE_ASYNC_SLOT_LIMIT	64
 
 /* Shared memory area for archiver process */
 typedef struct PgArchData
@@ -134,6 +138,18 @@ struct arch_files_state
 
 static struct arch_files_state *arch_files = NULL;
 
+typedef struct ArchInFlight
+{
+	char		xlog[MAX_XFN_CHARS + 1];	/* empty = free */
+	int			failures;
+	bool		waiting;
+	time_t		not_before;
+} ArchInFlight;
+
+static ArchInFlight arch_inflight[ARCHIVE_ASYNC_SLOT_LIMIT];
+static int	arch_inflight_count = 0;
+static bool archiver_use_async = false;
+
 /*
  * Flags set by interrupt handlers for later service in the main loop.
  */
@@ -146,6 +162,7 @@ static volatile sig_atomic_t ready_to_stop = false;
 static void pgarch_waken_stop(SIGNAL_ARGS);
 static void pgarch_MainLoop(void);
 static void pgarch_ArchiverCopyLoop(void);
+static void pgarch_ArchiverAsyncLoop(void);
 static bool pgarch_archiveXlog(char *xlog);
 static bool pgarch_readyXlog(char *xlog);
 static void pgarch_archiveDone(char *xlog);
@@ -154,6 +171,22 @@ static void ProcessPgArchInterrupts(void);
 static int	ready_file_comparator(Datum a, Datum b, void *arg);
 static void LoadArchiveLibrary(void);
 static void pgarch_call_module_shutdown_cb(int code, Datum arg);
+static void pgarch_module_error_cleanup(MemoryContext oldcontext);
+static bool pgarch_archive_configured(void);
+static int	pgarch_wal_file_present(const char *xlog);
+static ArchInFlight *pgarch_inflight_find(const char *xlog);
+static ArchInFlight *pgarch_inflight_acquire(const char *xlog);
+static bool pgarch_inflight_blocked(const ArchInFlight *slot);
+static void pgarch_inflight_clear(void);
+static void pgarch_abort_async_inflight(void);
+static void pgarch_set_activity(const char *fmt, const char *xlog);
+static long pgarch_async_retry_sleep(bool have_deferred);
+static bool pgarch_async_finish(ArchInFlight *slot, ArchiveResultStatus status);
+static void pgarch_async_submit_ready(char *deferred, bool *give_up);
+static bool pgarch_async_should_abort(time_t *stop_deadline);
+static int	pgarch_submitXlog(char *xlog);
+static int	pgarch_pollXlog(char *file, ArchiveResultStatus *status,
+							 long timeout_ms);
 
 static void PgArchShmemRequest(void *arg);
 static void PgArchShmemInit(void *arg);
@@ -348,6 +381,8 @@ pgarch_MainLoop(void)
 		/* Do what we're here for */
 		pgarch_ArchiverCopyLoop();
 
+		time_to_stop = ready_to_stop;
+
 		/*
 		 * Sleep until a signal is received, or until a poll is forced by
 		 * PGARCH_AUTOWAKE_INTERVAL, or until postmaster dies.
@@ -382,6 +417,12 @@ pgarch_ArchiverCopyLoop(void)
 {
 	char		xlog[MAX_XFN_CHARS + 1];
 
+	if (archiver_use_async)
+	{
+		pgarch_ArchiverAsyncLoop();
+		return;
+	}
+
 	/* force directory scan in the first call to pgarch_readyXlog() */
 	arch_files->arch_files_size = 0;
 
@@ -394,12 +435,10 @@ pgarch_ArchiverCopyLoop(void)
 	while (pgarch_readyXlog(xlog))
 	{
 		int			failures = 0;
-		int			failures_orphan = 0;
 
 		for (;;)
 		{
-			struct stat stat_buf;
-			char		pathname[MAXPGPATH];
+			int			wal_present;
 
 			/*
 			 * Do not initiate any more archive commands after receiving
@@ -418,59 +457,14 @@ pgarch_ArchiverCopyLoop(void)
 			 */
 			ProcessPgArchInterrupts();
 
-			/* Reset variables that might be set by the callback */
-			arch_module_check_errdetail_string = NULL;
-
-			/* can't do anything if not configured ... */
-			if (ArchiveCallbacks->check_configured_cb != NULL &&
-				!ArchiveCallbacks->check_configured_cb(archive_module_state))
-			{
-				ereport(WARNING,
-						(errmsg("\"archive_mode\" enabled, yet archiving is not configured"),
-						 arch_module_check_errdetail_string ?
-						 errdetail_internal("%s", arch_module_check_errdetail_string) : 0));
+			if (!pgarch_archive_configured())
 				return;
-			}
-
-			/*
-			 * Since archive status files are not removed in a durable manner,
-			 * a system crash could leave behind .ready files for WAL segments
-			 * that have already been recycled or removed.  In this case,
-			 * simply remove the orphan status file and move on.  unlink() is
-			 * used here as even on subsequent crashes the same orphan files
-			 * would get removed, so there is no need to worry about
-			 * durability.
-			 */
-			snprintf(pathname, MAXPGPATH, XLOGDIR "/%s", xlog);
-			if (stat(pathname, &stat_buf) != 0 && errno == ENOENT)
-			{
-				char		xlogready[MAXPGPATH];
-
-				StatusFilePath(xlogready, xlog, ".ready");
-				if (unlink(xlogready) == 0)
-				{
-					ereport(WARNING,
-							(errmsg("removed orphan archive status file \"%s\"",
-									xlogready)));
 
-					/* leave loop and move to the next status file */
-					break;
-				}
-
-				if (++failures_orphan >= NUM_ORPHAN_CLEANUP_RETRIES)
-				{
-					ereport(WARNING,
-							(errmsg("removal of orphan archive status file \"%s\" failed too many times, will try again later",
-									xlogready)));
-
-					/* give up cleanup of orphan status files */
-					return;
-				}
-
-				/* wait a bit before retrying */
-				pg_usleep(1000000L);
-				continue;
-			}
+			wal_present = pgarch_wal_file_present(xlog);
+			if (wal_present < 0)
+				return;
+			if (wal_present == 0)
+				break;
 
 			if (pgarch_archiveXlog(xlog))
 			{
@@ -506,6 +500,482 @@ pgarch_ArchiverCopyLoop(void)
 	}
 }
 
+static void
+pgarch_module_error_cleanup(MemoryContext oldcontext)
+{
+	error_context_stack = NULL;
+
+	HOLD_INTERRUPTS();
+
+	EmitErrorReport();
+
+	disable_all_timeouts(false);
+	LWLockReleaseAll();
+	ConditionVariableCancelSleep();
+	pgstat_report_wait_end();
+	pgaio_error_cleanup();
+	ReleaseAuxProcessResources(false);
+	AtEOXact_Files(false);
+	AtEOXact_HashTables(false);
+
+	MemoryContextSwitchTo(oldcontext);
+	FlushErrorState();
+	MemoryContextReset(archive_context);
+	PG_exception_stack = NULL;
+
+	RESUME_INTERRUPTS();
+}
+
+static bool
+pgarch_archive_configured(void)
+{
+	arch_module_check_errdetail_string = NULL;
+	if (ArchiveCallbacks->check_configured_cb != NULL &&
+		!ArchiveCallbacks->check_configured_cb(archive_module_state))
+	{
+		ereport(WARNING,
+				(errmsg("\"archive_mode\" enabled, yet archiving is not configured"),
+				 arch_module_check_errdetail_string ?
+				 errdetail_internal("%s", arch_module_check_errdetail_string) : 0));
+		return false;
+	}
+	return true;
+}
+
+/*
+ * Return 1 if present, 0 if an orphan .ready was removed, -1 after too
+ * many cleanup failures.
+ *
+ * Since archive status files are not removed in a durable manner, a system
+ * crash could leave behind .ready files for WAL segments that have already
+ * been recycled or removed.  In this case, simply remove the orphan status
+ * file and move on.  unlink() is used here as even on subsequent crashes
+ * the same orphan files would get removed, so there is no need to worry
+ * about durability.
+ */
+static int
+pgarch_wal_file_present(const char *xlog)
+{
+	struct stat stat_buf;
+	char		pathname[MAXPGPATH];
+	char		xlogready[MAXPGPATH];
+	int			failures_orphan = 0;
+
+	snprintf(pathname, MAXPGPATH, XLOGDIR "/%s", xlog);
+	if (stat(pathname, &stat_buf) == 0 || errno != ENOENT)
+		return 1;
+
+	StatusFilePath(xlogready, xlog, ".ready");
+	for (;;)
+	{
+		if (unlink(xlogready) == 0)
+		{
+			ereport(WARNING,
+					(errmsg("removed orphan archive status file \"%s\"",
+							xlogready)));
+			return 0;
+		}
+
+		if (++failures_orphan >= NUM_ORPHAN_CLEANUP_RETRIES)
+		{
+			ereport(WARNING,
+					(errmsg("removal of orphan archive status file \"%s\" failed too many times, will try again later",
+							xlogready)));
+			return -1;
+		}
+
+		pg_usleep(1000000L);
+	}
+}
+
+static ArchInFlight *
+pgarch_inflight_find(const char *xlog)
+{
+	for (int i = 0; i < ARCHIVE_ASYNC_SLOT_LIMIT; i++)
+	{
+		if (arch_inflight[i].xlog[0] != '\0' &&
+			strcmp(arch_inflight[i].xlog, xlog) == 0)
+			return &arch_inflight[i];
+	}
+	return NULL;
+}
+
+static ArchInFlight *
+pgarch_inflight_acquire(const char *xlog)
+{
+	ArchInFlight *slot = pgarch_inflight_find(xlog);
+
+	if (slot != NULL)
+		return slot;
+
+	for (int i = 0; i < ARCHIVE_ASYNC_SLOT_LIMIT; i++)
+	{
+		if (arch_inflight[i].xlog[0] == '\0')
+		{
+			slot = &arch_inflight[i];
+			strlcpy(slot->xlog, xlog, sizeof(slot->xlog));
+			slot->failures = 0;
+			slot->waiting = false;
+			slot->not_before = 0;
+			return slot;
+		}
+	}
+	return NULL;
+}
+
+static bool
+pgarch_inflight_blocked(const ArchInFlight *slot)
+{
+	return slot->waiting ||
+		slot->failures >= NUM_ARCHIVE_RETRIES ||
+		(slot->not_before != 0 && time(NULL) < slot->not_before);
+}
+
+static void
+pgarch_inflight_clear(void)
+{
+	MemSet(arch_inflight, 0, sizeof(arch_inflight));
+	arch_inflight_count = 0;
+}
+
+static void
+pgarch_abort_async_inflight(void)
+{
+	if (ArchiveCallbacks->cancel_cb != NULL)
+		ArchiveCallbacks->cancel_cb(archive_module_state);
+	pgarch_inflight_clear();
+}
+
+static void
+pgarch_abort_async_inflight_msg(const char *msg)
+{
+	if (arch_inflight_count > 0)
+		ereport(LOG, (errmsg("%s", msg)));
+	pgarch_abort_async_inflight();
+}
+
+static void
+pgarch_set_activity(const char *fmt, const char *xlog)
+{
+	char		activitymsg[MAXFNAMELEN + 16];
+
+	snprintf(activitymsg, sizeof(activitymsg), fmt, xlog);
+	set_ps_display(activitymsg);
+}
+
+static long
+pgarch_async_retry_sleep(bool have_deferred)
+{
+	time_t		now = time(NULL);
+	time_t		wait_until = 0;
+	bool		pending = have_deferred;
+	bool		have_wait = false;
+
+	for (int i = 0; i < ARCHIVE_ASYNC_SLOT_LIMIT; i++)
+	{
+		if (arch_inflight[i].xlog[0] == '\0' ||
+			arch_inflight[i].waiting ||
+			arch_inflight[i].failures >= NUM_ARCHIVE_RETRIES)
+			continue;
+		pending = true;
+		if (arch_inflight[i].not_before == 0 ||
+			arch_inflight[i].not_before <= now)
+			return PGARCH_ASYNC_POLL_MS;
+		if (!have_wait || arch_inflight[i].not_before < wait_until)
+		{
+			wait_until = arch_inflight[i].not_before;
+			have_wait = true;
+		}
+	}
+
+	if (!pending)
+		return -1;
+	if (have_wait && wait_until > now)
+		return (wait_until - now) * 1000L;
+	return PGARCH_ASYNC_POLL_MS;
+}
+
+static bool
+pgarch_async_finish(ArchInFlight *slot, ArchiveResultStatus status)
+{
+	if (slot->waiting)
+	{
+		arch_inflight_count--;
+		slot->waiting = false;
+	}
+
+	if (status == ARCHIVE_RESULT_SUCCESS)
+	{
+		pgarch_archiveDone(slot->xlog);
+		pgstat_report_archiver(slot->xlog, false);
+		pgarch_set_activity("last was %s", slot->xlog);
+		MemSet(slot, 0, sizeof(*slot));
+		return false;
+	}
+
+	pgstat_report_archiver(slot->xlog, true);
+	pgarch_set_activity("failed on %s", slot->xlog);
+
+	if (status == ARCHIVE_RESULT_FAIL)
+		slot->failures = NUM_ARCHIVE_RETRIES;
+	else
+	{
+		slot->failures++;
+		slot->not_before = time(NULL) + 1;
+	}
+
+	if (slot->failures < NUM_ARCHIVE_RETRIES)
+		return false;
+
+	ereport(WARNING,
+			(errmsg("archiving write-ahead log file \"%s\" failed too many times, will try again later",
+					slot->xlog)));
+	return true;
+}
+
+static int
+pgarch_submitXlog(char *xlog)
+{
+	sigjmp_buf	local_sigjmp_buf;
+	MemoryContext oldcontext;
+	char		pathname[MAXPGPATH];
+	int			result;
+
+	snprintf(pathname, MAXPGPATH, XLOGDIR "/%s", xlog);
+	oldcontext = MemoryContextSwitchTo(archive_context);
+
+	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
+	{
+		pgarch_module_error_cleanup(oldcontext);
+		result = -1;
+	}
+	else
+	{
+		bool		ok;
+
+		PG_exception_stack = &local_sigjmp_buf;
+		ok = ArchiveCallbacks->submit_cb(archive_module_state, xlog, pathname);
+		PG_exception_stack = NULL;
+		MemoryContextSwitchTo(oldcontext);
+		MemoryContextReset(archive_context);
+		result = ok ? 1 : 0;
+	}
+
+	return result;
+}
+
+static int
+pgarch_pollXlog(char *file, ArchiveResultStatus *status, long timeout_ms)
+{
+	sigjmp_buf	local_sigjmp_buf;
+	MemoryContext oldcontext;
+	const char *modulefile = NULL;
+	int			result;
+
+	oldcontext = MemoryContextSwitchTo(archive_context);
+
+	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
+	{
+		pgarch_module_error_cleanup(oldcontext);
+		result = -1;
+	}
+	else
+	{
+		bool		got;
+
+		PG_exception_stack = &local_sigjmp_buf;
+		got = ArchiveCallbacks->poll_cb(archive_module_state, &modulefile,
+										status, timeout_ms);
+		if (got)
+		{
+			if (modulefile == NULL || modulefile[0] == '\0')
+				file[0] = '\0';
+			else
+				strlcpy(file, modulefile, MAX_XFN_CHARS + 1);
+			result = 1;
+		}
+		else
+			result = 0;
+		PG_exception_stack = NULL;
+		MemoryContextSwitchTo(oldcontext);
+		MemoryContextReset(archive_context);
+	}
+
+	return result;
+}
+
+static void
+pgarch_async_submit_ready(char *deferred, bool *give_up)
+{
+	char		xlog[MAX_XFN_CHARS + 1];
+
+	while (!*give_up &&
+		   arch_inflight_count < XLogArchiveAsyncMax)
+	{
+		int			wal_present;
+		int			cbres;
+		ArchInFlight *slot;
+
+		if (deferred[0] != '\0')
+		{
+			strlcpy(xlog, deferred, sizeof(xlog));
+			deferred[0] = '\0';
+		}
+		else if (!pgarch_readyXlog(xlog))
+			break;
+
+		slot = pgarch_inflight_find(xlog);
+		if (slot != NULL && pgarch_inflight_blocked(slot))
+		{
+			strlcpy(deferred, xlog, MAX_XFN_CHARS + 1);
+			break;
+		}
+
+		wal_present = pgarch_wal_file_present(xlog);
+		if (wal_present < 0)
+		{
+			*give_up = true;
+			break;
+		}
+		if (wal_present == 0)
+		{
+			if (slot != NULL)
+				MemSet(slot, 0, sizeof(*slot));
+			continue;
+		}
+
+		slot = pgarch_inflight_acquire(xlog);
+		if (slot == NULL)
+		{
+			if (arch_inflight_count == 0)
+				*give_up = true;
+			else
+				strlcpy(deferred, xlog, MAX_XFN_CHARS + 1);
+			break;
+		}
+
+		pgarch_set_activity("submitting %s", xlog);
+		cbres = pgarch_submitXlog(xlog);
+		if (cbres < 0)
+		{
+			/*
+			 * Module ERROR may leave other in-flight work inconsistent with
+			 * core tracking.  Cancel everything and retry later.
+			 */
+			pgarch_abort_async_inflight();
+			strlcpy(deferred, xlog, MAX_XFN_CHARS + 1);
+			break;
+		}
+		if (cbres == 0)
+		{
+			strlcpy(deferred, xlog, MAX_XFN_CHARS + 1);
+			break;
+		}
+
+		slot->waiting = true;
+		arch_inflight_count++;
+	}
+}
+
+static bool
+pgarch_async_should_abort(time_t *stop_deadline)
+{
+	if (ShutdownRequestPending || !PostmasterIsAlive())
+	{
+		pgarch_abort_async_inflight_msg("canceling in flight archive commands due to shutdown");
+		return true;
+	}
+
+	ProcessPgArchInterrupts();
+	if (!pgarch_archive_configured())
+	{
+		pgarch_abort_async_inflight_msg("canceling in flight archive commands because archiving is no longer configured");
+		return true;
+	}
+
+	if (ready_to_stop)
+	{
+		time_t		now = time(NULL);
+
+		if (*stop_deadline == 0)
+			*stop_deadline = now + PGARCH_ASYNC_STOP_GRACE_S;
+		else if (now >= *stop_deadline ||
+				 now < *stop_deadline - PGARCH_ASYNC_STOP_GRACE_S)
+		{
+			pgarch_abort_async_inflight_msg("canceling in flight archive commands due to shutdown");
+			return true;
+		}
+	}
+	return false;
+}
+
+static void
+pgarch_ArchiverAsyncLoop(void)
+{
+	bool		give_up = false;
+	char		deferred[MAX_XFN_CHARS + 1];
+	time_t		stop_deadline = 0;
+
+	arch_files->arch_files_size = 0;
+	pgarch_inflight_clear();
+	deferred[0] = '\0';
+
+	for (;;)
+	{
+		char		done_file[MAX_XFN_CHARS + 1];
+		ArchiveResultStatus status;
+		int			cbres;
+		ArchInFlight *slot;
+
+		if (pgarch_async_should_abort(&stop_deadline))
+			return;
+
+		pgarch_async_submit_ready(deferred, &give_up);
+
+		if (arch_inflight_count == 0)
+		{
+			long		sleep_ms;
+
+			if (give_up || ShutdownRequestPending)
+				return;
+
+			sleep_ms = pgarch_async_retry_sleep(deferred[0] != '\0');
+			if (sleep_ms < 0)
+				return;
+			(void) WaitLatch(MyLatch,
+							 WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
+							 sleep_ms,
+							 WAIT_EVENT_ARCHIVER_MAIN);
+			ResetLatch(MyLatch);
+			continue;
+		}
+
+		cbres = pgarch_pollXlog(done_file, &status, PGARCH_ASYNC_POLL_MS);
+		if (cbres < 0)
+		{
+			pgarch_abort_async_inflight_msg("canceling in flight archive commands after archive module error");
+			return;
+		}
+		if (cbres == 0)
+			continue;
+
+		slot = (done_file[0] != '\0') ? pgarch_inflight_find(done_file) : NULL;
+		if (slot == NULL || !slot->waiting)
+		{
+			ereport(WARNING,
+					(errmsg("asynchronous archive module returned unexpected file \"%s\"",
+							done_file)));
+			pgarch_abort_async_inflight();
+			return;
+		}
+
+		if (pgarch_async_finish(slot, status))
+			give_up = true;
+		if (give_up && arch_inflight_count == 0)
+			return;
+	}
+}
+
 /*
  * pgarch_archiveXlog
  *
@@ -519,15 +989,10 @@ pgarch_archiveXlog(char *xlog)
 	sigjmp_buf	local_sigjmp_buf;
 	MemoryContext oldcontext;
 	char		pathname[MAXPGPATH];
-	char		activitymsg[MAXFNAMELEN + 16];
 	bool		ret;
 
 	snprintf(pathname, MAXPGPATH, XLOGDIR "/%s", xlog);
-
-	/* Report archive activity in PS display */
-	snprintf(activitymsg, sizeof(activitymsg), "archiving %s", xlog);
-	set_ps_display(activitymsg);
-
+	pgarch_set_activity("archiving %s", xlog);
 	oldcontext = MemoryContextSwitchTo(archive_context);
 
 	/*
@@ -537,85 +1002,23 @@ pgarch_archiveXlog(char *xlog)
 	 * code and maintain.  Therefore, we create our own exception handler to
 	 * catch ERRORs and return false instead of restarting the archiver
 	 * whenever there is a failure.
-	 *
-	 * We assume ERRORs from the archiving callback are the most common
-	 * exceptions experienced by the archiver, so we opt to handle exceptions
-	 * here instead of PgArchiverMain() to avoid reinitializing the archiver
-	 * too frequently.  We could instead add a sigsetjmp() block to
-	 * PgArchiverMain() and use PG_TRY/PG_CATCH here, but the extra code to
-	 * avoid the odd archiver restart doesn't seem worth it.
 	 */
 	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
 	{
-		/* Since not using PG_TRY, must reset error stack by hand */
-		error_context_stack = NULL;
-
-		/* Prevent interrupts while cleaning up */
-		HOLD_INTERRUPTS();
-
-		/* Report the error to the server log. */
-		EmitErrorReport();
-
-		/*
-		 * Try to clean up anything the archive module left behind.  We try to
-		 * cover anything that an archive module could conceivably have left
-		 * behind, but it is of course possible that modules could be doing
-		 * unexpected things that require additional cleanup.  Module authors
-		 * should be sure to do any extra required cleanup in a PG_CATCH block
-		 * within the archiving callback, and they are encouraged to notify
-		 * the pgsql-hackers mailing list so that we can add it here.
-		 */
-		disable_all_timeouts(false);
-		LWLockReleaseAll();
-		ConditionVariableCancelSleep();
-		pgstat_report_wait_end();
-		pgaio_error_cleanup();
-		ReleaseAuxProcessResources(false);
-		AtEOXact_Files(false);
-		AtEOXact_HashTables(false);
-
-		/*
-		 * Return to the original memory context and clear ErrorContext for
-		 * next time.
-		 */
-		MemoryContextSwitchTo(oldcontext);
-		FlushErrorState();
-
-		/* Flush any leaked data */
-		MemoryContextReset(archive_context);
-
-		/* Remove our exception handler */
-		PG_exception_stack = NULL;
-
-		/* Now we can allow interrupts again */
-		RESUME_INTERRUPTS();
-
-		/* Report failure so that the archiver retries this file */
+		pgarch_module_error_cleanup(oldcontext);
 		ret = false;
 	}
 	else
 	{
-		/* Enable our exception handler */
 		PG_exception_stack = &local_sigjmp_buf;
-
-		/* Archive the file! */
 		ret = ArchiveCallbacks->archive_file_cb(archive_module_state,
 												xlog, pathname);
-
-		/* Remove our exception handler */
 		PG_exception_stack = NULL;
-
-		/* Reset our memory context and switch back to the original one */
 		MemoryContextSwitchTo(oldcontext);
 		MemoryContextReset(archive_context);
 	}
 
-	if (ret)
-		snprintf(activitymsg, sizeof(activitymsg), "last was %s", xlog);
-	else
-		snprintf(activitymsg, sizeof(activitymsg), "failed on %s", xlog);
-	set_ps_display(activitymsg);
-
+	pgarch_set_activity(ret ? "last was %s" : "failed on %s", xlog);
 	return ret;
 }
 
@@ -623,10 +1026,9 @@ pgarch_archiveXlog(char *xlog)
  * pgarch_readyXlog
  *
  * Return name of the oldest xlog file that has not yet been archived.
- * No notification is set that file archiving is now in progress, so
- * this would need to be extended if multiple concurrent archival
- * tasks were created. If a failure occurs, we will completely
- * re-copy the file at the next available opportunity.
+ * Concurrent callers must skip in-flight names themselves. If a failure
+ * occurs, we will completely re-copy the file at the next available
+ * opportunity.
  *
  * It is important that we return the oldest, so that we archive xlogs
  * in order that they were written, for two reasons:
@@ -901,6 +1303,7 @@ ProcessPgArchInterrupts(void)
 
 			proc_exit(0);
 		}
+
 	}
 }
 
@@ -937,7 +1340,22 @@ LoadArchiveLibrary(void)
 
 	ArchiveCallbacks = (*archive_init) ();
 
-	if (ArchiveCallbacks->archive_file_cb == NULL)
+	if ((ArchiveCallbacks->submit_cb == NULL) !=
+		(ArchiveCallbacks->poll_cb == NULL))
+		ereport(ERROR,
+				(errmsg("archive modules must provide both submit and poll callbacks for asynchronous archiving")));
+
+	archiver_use_async = (ArchiveCallbacks->submit_cb != NULL);
+	if (archiver_use_async)
+	{
+		if (ArchiveCallbacks->archive_file_cb != NULL)
+			ereport(ERROR,
+					(errmsg("archive modules must not register both synchronous and asynchronous archive callbacks")));
+		if (ArchiveCallbacks->cancel_cb == NULL)
+			ereport(ERROR,
+					(errmsg("asynchronous archive modules must provide a cancel callback")));
+	}
+	else if (ArchiveCallbacks->archive_file_cb == NULL)
 		ereport(ERROR,
 				(errmsg("archive modules must register an archive callback")));
 
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..eeefbf0ceea 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -67,6 +67,15 @@
   assign_hook => 'assign_application_name',
 },
 
+{ name => 'archive_async_max', type => 'int', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
+  short_desc => 'Sets the maximum number of WAL files in flight for asynchronous archiving.',
+  long_desc => 'Used by asynchronous archive modules. Ignored by synchronous archive_file_cb modules.',
+  variable => 'XLogArchiveAsyncMax',
+  boot_val => '8',
+  min => '1',
+  max => '64',
+},
+
 { name => 'archive_cleanup_command', type => 'string', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVE_RECOVERY',
   short_desc => 'Sets the shell command that will be executed at every restart point.',
   variable => 'archiveCleanupCommand',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06c..f1d8033267f 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -297,6 +297,7 @@
 #archive_library = ''           # library to use to archive a WAL file
                                 # (empty string indicates archive_command should
                                 # be used)
+#archive_async_max = 8          # max in-flight files for async archiving
 #archive_command = ''           # command to use to archive a WAL file
                                 # placeholders: %p = path of file to archive
                                 #               %f = file name only
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 2bf5714b51e..b57f7477709 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -44,6 +44,7 @@ extern PGDLLIMPORT int XLOGbuffers;
 extern PGDLLIMPORT int XLogArchiveTimeout;
 extern PGDLLIMPORT int wal_retrieve_retry_interval;
 extern PGDLLIMPORT char *XLogArchiveCommand;
+extern PGDLLIMPORT int XLogArchiveAsyncMax;
 extern PGDLLIMPORT bool EnableHotStandby;
 extern PGDLLIMPORT bool fullPageWrites;
 extern PGDLLIMPORT bool wal_log_hints;
diff --git a/src/include/archive/archive_module.h b/src/include/archive/archive_module.h
index 146275558c5..f53a06f3a5a 100644
--- a/src/include/archive/archive_module.h
+++ b/src/include/archive/archive_module.h
@@ -30,14 +30,23 @@ typedef struct ArchiveModuleState
 /*
  * Archive module callbacks
  *
- * These callback functions should be defined by archive libraries and returned
- * via _PG_archive_module_init().  ArchiveFileCB is the only required callback.
- * For more information about the purpose of each callback, refer to the
- * archive modules documentation.
+ * Returned via _PG_archive_module_init().  Provide archive_file_cb, or
+ * submit_cb plus poll_cb with cancel_cb.
  */
+typedef enum ArchiveResultStatus
+{
+	ARCHIVE_RESULT_SUCCESS,
+	ARCHIVE_RESULT_RETRY,
+	ARCHIVE_RESULT_FAIL
+} ArchiveResultStatus;
+
 typedef void (*ArchiveStartupCB) (ArchiveModuleState *state);
 typedef bool (*ArchiveCheckConfiguredCB) (ArchiveModuleState *state);
 typedef bool (*ArchiveFileCB) (ArchiveModuleState *state, const char *file, const char *path);
+typedef bool (*ArchiveSubmitCB) (ArchiveModuleState *state, const char *file, const char *path);
+typedef bool (*ArchivePollCB) (ArchiveModuleState *state, const char **file,
+							   ArchiveResultStatus *status, long timeout_ms);
+typedef void (*ArchiveCancelCB) (ArchiveModuleState *state);
 typedef void (*ArchiveShutdownCB) (ArchiveModuleState *state);
 
 typedef struct ArchiveModuleCallbacks
@@ -46,6 +55,9 @@ typedef struct ArchiveModuleCallbacks
 	ArchiveCheckConfiguredCB check_configured_cb;
 	ArchiveFileCB archive_file_cb;
 	ArchiveShutdownCB shutdown_cb;
+	ArchiveSubmitCB submit_cb;
+	ArchivePollCB poll_cb;
+	ArchiveCancelCB cancel_cb;
 } ArchiveModuleCallbacks;
 
 /*
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..322699e2af3 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -133,6 +133,7 @@ ApplyRemoteCtx
 ApplySubXactData
 Archive
 ArchiveCheckConfiguredCB
+ArchiveCancelCB
 ArchiveEntryPtrType
 ArchiveFileCB
 ArchiveFormat
@@ -142,8 +143,12 @@ ArchiveModuleCallbacks
 ArchiveModuleInit
 ArchiveModuleState
 ArchiveOpts
+ArchivePollCB
+ArchiveResultStatus
 ArchiveShutdownCB
 ArchiveStartupCB
+ArchiveSubmitCB
+ArchInFlight
 ArchiveStreamState
 ArchivedWALFile
 ArchivedWAL_hash
-- 
2.56.1

From 386778490c327d61ddd453e00423fbe1942f81a2 Mon Sep 17 00:00:00 2001
From: Stepan Neretin <[email protected]>
Date: Mon, 23 Nov 2026 22:56:42 +0700
Subject: [PATCH 3/3] Add TAP coverage for persistent archive_command.

Cover basic archive success, %f/%p rejection, mode toggles, retry,
helper death with outstanding work, and cancel of a hung helper.

Discussion: https://postgr.es/m/CA+Yyo5TfMpUE3s=wkrwcaybbwbo2vnyrnrt_5hy-vprmhjx...@mail.gmail.com
---
 src/test/recovery/meson.build                 |   1 +
 .../t/062_archive_command_persistent.pl       | 263 ++++++++++++++++++
 2 files changed, 264 insertions(+)
 create mode 100644 src/test/recovery/t/062_archive_command_persistent.pl

diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..650a5e639f7 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
       't/059_remote_apply_status_interval.pl',
       't/060_multixact_crashed_updater.pl',
       't/061_recovery_target_prefetch.pl',
+      't/062_archive_command_persistent.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/062_archive_command_persistent.pl b/src/test/recovery/t/062_archive_command_persistent.pl
new file mode 100644
index 00000000000..1c891d092a4
--- /dev/null
+++ b/src/test/recovery/t/062_archive_command_persistent.pl
@@ -0,0 +1,263 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+#
+# Tests for archive_command_persistent: one long-lived helper fed over stdin.
+#
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+use Time::HiRes qw(usleep);
+
+my $node = PostgreSQL::Test::Cluster->new('persistent');
+$node->init(has_archiving => 1, allows_streaming => 1);
+
+if ($PostgreSQL::Test::Utils::windows_os)
+{
+	$node->start;
+	my $offset = -s $node->logfile;
+	$node->append_conf('postgresql.conf',
+		'archive_command_persistent = on');
+	$node->reload;
+	$node->wait_for_log(
+		qr/"archive_command_persistent" is not supported on Windows/,
+		$offset);
+	is( $node->safe_psql('postgres', 'SHOW archive_command_persistent'),
+		'off', 'archive_command_persistent rejected on Windows');
+	$node->stop;
+	done_testing();
+	exit;
+}
+
+my $helper = $node->basedir . '/archive_persistent_helper.pl';
+my $archive_dir = $node->archive_dir;
+my $hang_log = $node->basedir . '/hang_helper.log';
+
+append_to_file(
+	$helper, <<'EOF');
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use File::Copy qw(copy);
+use IO::Handle;
+
+my $dest = $ENV{ARCHIVE_DEST} // die "ARCHIVE_DEST not set\n";
+my $delay_ms = $ENV{ARCHIVE_DELAY_MS} // 0;
+my $hang = ($ENV{ARCHIVE_HANG} // '') eq '1';
+my $fail_once = $ENV{ARCHIVE_FAIL_ONCE_FILE} // '';
+my $fail_done = 0;
+my $exit_after = $ENV{ARCHIVE_EXIT_AFTER} // 0;
+my $seen = 0;
+
+STDIN->autoflush(1);
+STDOUT->autoflush(1);
+
+if ($hang)
+{
+	my $log = $ENV{ARCHIVE_HANG_LOG} // die "ARCHIVE_HANG_LOG not set\n";
+	open my $fh, '>>', $log or die $!;
+	print $fh "$$\n";
+	close $fh;
+	sleep 1000;
+	exit 0;
+}
+
+while (my $line = <STDIN>)
+{
+	chomp $line;
+	next if $line eq '';
+	my ($cmd, $file, $path) = split /\t/, $line, 3;
+	$cmd eq 'archive' or die "bad request: $line\n";
+	defined $file and defined $path or die "bad request: $line\n";
+
+	if ($delay_ms > 0)
+	{
+		select(undef, undef, undef, $delay_ms / 1000.0);
+	}
+
+	if ($fail_once ne '' && !$fail_done && $file eq $fail_once)
+	{
+		$fail_done = 1;
+		print "archived\t$file\tretry\n";
+		next;
+	}
+
+	my $target = "$dest/$file";
+	copy($path, $target) or die "copy $path -> $target: $!\n";
+	print "archived\t$file\tok\n";
+
+	$seen++;
+	exit 0 if $exit_after > 0 && $seen >= $exit_after;
+}
+exit 0;
+EOF
+chmod 0755, $helper or die "chmod $helper: $!";
+
+my $helper_cmd = "env ARCHIVE_DEST=$archive_dir $helper";
+my $classic_cmd = "cp \"%p\" \"$archive_dir/%f\"";
+
+$node->append_conf(
+	'postgresql.conf', qq{
+archive_command_persistent = on
+archive_async_max = 4
+archive_command = '$helper_cmd'
+});
+$node->start;
+$node->safe_psql('postgres', 'CREATE TABLE t_arch(i int)');
+
+sub switch_wal
+{
+	my ($tag) = @_;
+	$node->safe_psql('postgres',
+		"INSERT INTO t_arch VALUES ($tag); SELECT pg_switch_wal()");
+}
+
+sub archived_count
+{
+	return $node->safe_psql('postgres',
+		q{SELECT archived_count FROM pg_stat_archiver});
+}
+
+sub wait_archived_gt
+{
+	my ($before, $msg) = @_;
+	ok(
+		$node->poll_query_until(
+			'postgres',
+			qq{SELECT archived_count > $before FROM pg_stat_archiver},
+			't'),
+		$msg);
+}
+
+sub wait_archiver_alive
+{
+	$node->poll_query_until(
+		'postgres',
+		q{SELECT count(*) = 1 FROM pg_stat_activity WHERE backend_type = 'archiver'},
+		't')
+	  or die 'timed out waiting for archiver';
+}
+
+sub reload_persistent
+{
+	my ($on, $extra) = @_;
+	my $val = $on ? 'on' : 'off';
+	my $offset = -s $node->logfile;
+	$node->append_conf(
+		'postgresql.conf',
+		"archive_command_persistent = $val\n" . ($extra // ''));
+	$node->reload;
+	$node->wait_for_log(
+		qr/restarting archiver process because value of "archive_command_persistent" was changed/,
+		$offset);
+	wait_archiver_alive();
+}
+
+sub reload_archive_command
+{
+	my ($cmd) = @_;
+	my $offset = -s $node->logfile;
+	$node->append_conf('postgresql.conf',
+		"archive_command = '$cmd'\n");
+	$node->reload;
+	$node->wait_for_log(
+		qr/restarting archiver process because value of "archive_command" was changed/,
+		$offset);
+	wait_archiver_alive();
+}
+
+# Basic persistent archive.
+for (1 .. 4) { switch_wal($_); }
+ok(
+	$node->poll_query_until(
+		'postgres', q{SELECT archived_count >= 4 FROM pg_stat_archiver}, 't'),
+	'persistent archive_command archives WAL');
+
+# %f/%p are rejected while persistent is on.
+{
+	my $offset = -s $node->logfile;
+	$node->append_conf('postgresql.conf',
+		"archive_command = 'cp \"%p\" \"/tmp/%f\"'\n");
+	$node->reload;
+	$node->wait_for_log(
+		qr/restarting archiver process because value of "archive_command" was changed/,
+		$offset);
+	$node->wait_for_log(
+		qr/archive_command.*must not contain %f or %p/,
+		$offset);
+	reload_archive_command($helper_cmd);
+}
+
+# Toggle persistent off/on and keep archiving.
+reload_persistent(0, "archive_command = '$classic_cmd'\n");
+my $before = archived_count();
+switch_wal(100);
+wait_archived_gt($before, 'classic archive_command works after persistent=off');
+
+reload_persistent(1, "archive_command = '$helper_cmd'\n");
+$before = archived_count();
+switch_wal(101);
+wait_archived_gt($before, 'persistent mode archives again after re-enable');
+
+# Helper can ask for retry once.
+{
+	my $seg = $node->safe_psql('postgres',
+		q{SELECT pg_walfile_name(pg_current_wal_lsn())});
+	my $retry_cmd =
+		"env ARCHIVE_DEST=$archive_dir ARCHIVE_FAIL_ONCE_FILE=$seg $helper";
+	reload_archive_command($retry_cmd);
+	$before = archived_count();
+	switch_wal(102);
+	wait_archived_gt($before, 'retry response still allows eventual success');
+	reload_archive_command($helper_cmd);
+}
+
+# Helper death with outstanding submits still drains via RETRY.
+{
+	my $die_cmd =
+		"env ARCHIVE_DEST=$archive_dir ARCHIVE_DELAY_MS=200 ARCHIVE_EXIT_AFTER=1 $helper";
+	reload_archive_command($die_cmd);
+	$before = archived_count();
+	for my $i (1 .. 4) { switch_wal(150 + $i); }
+	ok(
+		$node->poll_query_until(
+			'postgres',
+			qq{SELECT archived_count >= $before + 4 FROM pg_stat_archiver},
+			't'),
+		'helper death mid-flight still archives via RETRY');
+	reload_archive_command($helper_cmd);
+}
+
+# Hung helper is cancelled on shutdown.
+unlink $hang_log if -f $hang_log;
+my $hang_cmd =
+	"env ARCHIVE_DEST=$archive_dir ARCHIVE_HANG=1 ARCHIVE_HANG_LOG=$hang_log $helper";
+reload_persistent(0, "archive_command = '$classic_cmd'\n");
+reload_persistent(1, "archive_command = '$hang_cmd'\n");
+switch_wal(200);
+switch_wal(201);
+
+my $hang_pid;
+for (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default)
+{
+	if (-f $hang_log)
+	{
+		($hang_pid) = grep { length } split /\n/, slurp_file($hang_log);
+		last if defined $hang_pid;
+	}
+	usleep(100_000);
+}
+ok(defined $hang_pid, 'hung persistent helper started');
+
+my $offset = -s $node->logfile;
+ok($node->stop('fast', timeout => 120),
+	'stop with hung persistent archive_command');
+like(
+	slurp_file($node->logfile, $offset),
+	qr/canceling in flight archive commands due to shutdown/,
+	'shutdown canceled in-flight persistent archive work');
+ok(!kill(0, $hang_pid), "hang helper pid $hang_pid gone after stop")
+  if defined $hang_pid;
+
+done_testing();
-- 
2.56.1

From a81e8af2db2d19ade4efb70601a09d3e3ea6b742 Mon Sep 17 00:00:00 2001
From: Stepan Neretin <[email protected]>
Date: Mon, 23 Nov 2026 22:56:42 +0700
Subject: [PATCH 2/3] Add persistent archive_command protocol.

With archive_command_persistent on, start one long-lived helper and feed
it files over stdin instead of calling system() per file.  It answers
ok, retry, or fail.  No %f/%p in this mode, Unix only for now, and a
mode or command change restarts the archiver so the helper is rebuilt.

Discussion: https://postgr.es/m/CA+Yyo5TfMpUE3s=wkrwcaybbwbo2vnyrnrt_5hy-vprmhjx...@mail.gmail.com
---
 src/backend/access/transam/xlog.c             |  19 +
 src/backend/archive/shell_archive.c           | 667 +++++++++++++++++-
 src/backend/postmaster/pgarch.c               |  36 +
 src/backend/utils/misc/guc_parameters.dat     |  10 +-
 src/backend/utils/misc/postgresql.conf.sample |   1 +
 src/include/access/xlog.h                     |   1 +
 src/include/utils/guc_hooks.h                 |   2 +
 7 files changed, 727 insertions(+), 9 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 9419325d2a2..aba78926551 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -125,6 +125,7 @@ int			XLOGbuffers = -1;
 int			XLogArchiveTimeout = 0;
 int			XLogArchiveMode = ARCHIVE_MODE_OFF;
 char	   *XLogArchiveCommand = NULL;
+bool		XLogArchiveCommandPersistent = false;
 int			XLogArchiveAsyncMax = 8;
 bool		EnableHotStandby = false;
 bool		fullPageWrites = true;
@@ -5447,6 +5448,24 @@ show_archive_command(void)
 		return "(disabled)";
 }
 
+bool
+check_archive_command_persistent(bool *newval, void **extra, GucSource source)
+{
+#ifdef WIN32
+	if (*newval)
+	{
+		GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
+		GUC_check_errmsg("\"archive_command_persistent\" is not supported on Windows");
+		return false;
+	}
+#else
+	(void) newval;
+#endif
+	(void) extra;
+	(void) source;
+	return true;
+}
+
 /*
  * GUC show_hook for in_hot_standby
  */
diff --git a/src/backend/archive/shell_archive.c b/src/backend/archive/shell_archive.c
index 0b427a68809..25248f69cb5 100644
--- a/src/backend/archive/shell_archive.c
+++ b/src/backend/archive/shell_archive.c
@@ -15,43 +15,122 @@
  */
 #include "postgres.h"
 
+#include <fcntl.h>
+#include <signal.h>
 #include <sys/wait.h>
+#include <unistd.h>
 
 #include "access/xlog.h"
+#include "access/xlog_internal.h"
 #include "archive/archive_module.h"
 #include "archive/shell_archive.h"
 #include "common/percentrepl.h"
+#include "libpq/pqsignal.h"
+#include "miscadmin.h"
 #include "pgstat.h"
+#ifndef WIN32
+#include "postmaster/fork_process.h"
+#endif
+#include "storage/ipc.h"
+#include "storage/latch.h"
+#include "utils/timestamp.h"
 #include "utils/wait_event.h"
 
+/* Must match archive_async_max GUC max. */
+#define SHELL_OUTSTANDING_MAX	64
+
 static bool shell_archive_configured(ArchiveModuleState *state);
 static bool shell_archive_file(ArchiveModuleState *state,
 							   const char *file,
 							   const char *path);
 static void shell_archive_shutdown(ArchiveModuleState *state);
 
-static const ArchiveModuleCallbacks shell_archive_callbacks = {
-	.startup_cb = NULL,
+#ifndef WIN32
+static bool shell_archive_submit(ArchiveModuleState *state,
+								 const char *file,
+								 const char *path);
+static bool shell_archive_poll(ArchiveModuleState *state,
+							   const char **file,
+							   ArchiveResultStatus *status,
+							   long timeout_ms);
+static void shell_archive_cancel(ArchiveModuleState *state);
+
+static void shell_sigchld_handler(SIGNAL_ARGS);
+static void shell_prepare_child(void);
+static bool shell_command_has_file_placeholders(const char *cmd);
+static void shell_reset_child(void);
+static void shell_kill_child(void);
+static bool shell_child_alive(void);
+static bool shell_ensure_child(void);
+static bool shell_spawn_child(void);
+static int shell_write_line(const char *line);
+static bool shell_read_line(char *buf, size_t buflen, long timeout_ms);
+static bool shell_outstanding_add(const char *file);
+static bool shell_outstanding_remove(const char *file);
+static void shell_fail_outstanding(void);
+static bool shell_take_retry(const char **file, ArchiveResultStatus *status);
+static bool shell_parse_result(const char *line, char *file, size_t filelen,
+							   ArchiveResultStatus *status);
+#endif
+
+static const ArchiveModuleCallbacks shell_archive_sync_callbacks = {
 	.check_configured_cb = shell_archive_configured,
 	.archive_file_cb = shell_archive_file,
 	.shutdown_cb = shell_archive_shutdown
 };
 
+#ifndef WIN32
+static const ArchiveModuleCallbacks shell_archive_async_callbacks = {
+	.check_configured_cb = shell_archive_configured,
+	.shutdown_cb = shell_archive_shutdown,
+	.submit_cb = shell_archive_submit,
+	.poll_cb = shell_archive_poll,
+	.cancel_cb = shell_archive_cancel
+};
+
+static pid_t shell_child_pid = 0;
+static int	shell_to_child = -1;
+static int	shell_from_child = -1;
+static bool shell_sigchld_armed = false;
+static char shell_inbuf[MAXPGPATH];
+static int	shell_inlen = 0;
+static char shell_result_file[MAX_XFN_CHARS + 1];
+static char shell_outstanding[SHELL_OUTSTANDING_MAX][MAX_XFN_CHARS + 1];
+static int	shell_noutstanding = 0;
+static bool shell_report_retry = false;
+#endif
+
 const ArchiveModuleCallbacks *
 shell_archive_init(void)
 {
-	return &shell_archive_callbacks;
+#ifndef WIN32
+	if (XLogArchiveCommandPersistent)
+		return &shell_archive_async_callbacks;
+#endif
+	return &shell_archive_sync_callbacks;
 }
 
 static bool
 shell_archive_configured(ArchiveModuleState *state)
 {
-	if (XLogArchiveCommand[0] != '\0')
-		return true;
+	(void) state;
 
-	arch_module_check_errdetail("\"%s\" is not set.",
-								"archive_command");
-	return false;
+	if (XLogArchiveCommand[0] == '\0')
+	{
+		arch_module_check_errdetail("\"%s\" is not set.",
+									"archive_command");
+		return false;
+	}
+
+#ifndef WIN32
+	if (XLogArchiveCommandPersistent &&
+		shell_command_has_file_placeholders(XLogArchiveCommand))
+	{
+		arch_module_check_errdetail("\"archive_command\" must not contain %%f or %%p when \"archive_command_persistent\" is on.");
+		return false;
+	}
+#endif
+	return true;
 }
 
 static bool
@@ -136,8 +215,580 @@ shell_archive_file(ArchiveModuleState *state, const char *file,
 	return true;
 }
 
+#ifndef WIN32
+
+static bool
+shell_command_has_file_placeholders(const char *cmd)
+{
+	const char *p;
+
+	for (p = cmd; *p != '\0'; p++)
+	{
+		if (p[0] != '%')
+			continue;
+		if (p[1] == '%')
+		{
+			p++;
+			continue;
+		}
+		if (p[1] == 'f' || p[1] == 'p')
+			return true;
+		if (p[1] != '\0')
+			p++;
+	}
+	return false;
+}
+
+static void
+shell_sigchld_handler(SIGNAL_ARGS)
+{
+	int			save_errno = errno;
+
+	SetLatch(MyLatch);
+	errno = save_errno;
+}
+
+static void
+shell_prepare_child(void)
+{
+	int			sigs[] = {
+		SIGHUP, SIGINT, SIGTERM, SIGQUIT, SIGALRM,
+		SIGPIPE, SIGUSR1, SIGUSR2, SIGCHLD
+	};
+	int			i;
+
+	for (i = 0; i < lengthof(sigs); i++)
+		pqsignal(sigs[i], PG_SIG_DFL);
+	sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
+}
+
+static void
+shell_reset_child(void)
+{
+	if (shell_to_child >= 0)
+	{
+		close(shell_to_child);
+		shell_to_child = -1;
+	}
+	if (shell_from_child >= 0)
+	{
+		close(shell_from_child);
+		shell_from_child = -1;
+	}
+	shell_child_pid = 0;
+	shell_inlen = 0;
+}
+
+static void
+shell_kill_child(void)
+{
+	int			status;
+	int			tries;
+
+	if (shell_child_pid > 0)
+	{
+		/* Close stdin first so helpers that read until EOF can exit. */
+		if (shell_to_child >= 0)
+		{
+			close(shell_to_child);
+			shell_to_child = -1;
+		}
+
+		if (kill(shell_child_pid, SIGTERM) < 0 && errno != ESRCH)
+			ereport(LOG,
+					(errmsg("could not signal archive command: %m")));
+
+		for (tries = 0; tries < 10; tries++)
+		{
+			pid_t		done = waitpid(shell_child_pid, &status, WNOHANG);
+
+			if (done == shell_child_pid || (done < 0 && errno != EINTR))
+				break;
+			if (done < 0 && errno == EINTR)
+				continue;
+
+			pg_usleep(10000L);
+		}
+
+		if (waitpid(shell_child_pid, &status, WNOHANG) == 0)
+		{
+			if (kill(shell_child_pid, SIGKILL) < 0 && errno != ESRCH)
+				ereport(LOG,
+						(errmsg("could not kill archive command: %m")));
+			while (waitpid(shell_child_pid, &status, WNOHANG) == 0)
+				pg_usleep(10000L);
+		}
+	}
+	shell_reset_child();
+}
+
+static bool
+shell_child_alive(void)
+{
+	int			status;
+	pid_t		done;
+
+	if (shell_child_pid <= 0)
+		return false;
+
+	for (;;)
+	{
+		done = waitpid(shell_child_pid, &status, WNOHANG);
+		if (!(done < 0 && errno == EINTR))
+			break;
+	}
+
+	if (done == 0)
+		return true;
+
+	if (done == shell_child_pid)
+	{
+		if (status != 0)
+			ereport(LOG,
+					(errmsg("persistent archive command failed: %s",
+							wait_result_to_str(status))));
+	}
+	else if (done < 0)
+		ereport(LOG,
+				(errmsg("could not wait for archive command: %m")));
+
+	shell_reset_child();
+	return false;
+}
+
+static bool
+shell_outstanding_add(const char *file)
+{
+	int			i;
+
+	if (shell_noutstanding >= XLogArchiveAsyncMax ||
+		shell_noutstanding >= SHELL_OUTSTANDING_MAX)
+		return false;
+
+	for (i = 0; i < shell_noutstanding; i++)
+	{
+		if (strcmp(shell_outstanding[i], file) == 0)
+			return false;
+	}
+
+	strlcpy(shell_outstanding[shell_noutstanding], file,
+			sizeof(shell_outstanding[0]));
+	shell_noutstanding++;
+	return true;
+}
+
+static bool
+shell_outstanding_remove(const char *file)
+{
+	int			i;
+
+	for (i = 0; i < shell_noutstanding; i++)
+	{
+		if (strcmp(shell_outstanding[i], file) == 0)
+		{
+			if (i < --shell_noutstanding)
+				strlcpy(shell_outstanding[i],
+						shell_outstanding[shell_noutstanding],
+						sizeof(shell_outstanding[0]));
+			return true;
+		}
+	}
+	return false;
+}
+
+static void
+shell_fail_outstanding(void)
+{
+	if (shell_noutstanding > 0)
+		shell_report_retry = true;
+	shell_kill_child();
+}
+
+static bool
+shell_take_retry(const char **file, ArchiveResultStatus *status)
+{
+	if (!shell_report_retry || shell_noutstanding <= 0)
+		return false;
+
+	shell_noutstanding--;
+	strlcpy(shell_result_file, shell_outstanding[shell_noutstanding],
+			sizeof(shell_result_file));
+	if (shell_noutstanding == 0)
+		shell_report_retry = false;
+	*file = shell_result_file;
+	*status = ARCHIVE_RESULT_RETRY;
+	return true;
+}
+
+/*
+ * Write one protocol line to the helper.
+ * Returns 1 on success, 0 on backpressure (EAGAIN), -1 on hard error.
+ */
+static int
+shell_write_line(const char *line)
+{
+	size_t		len = strlen(line);
+	size_t		off = 0;
+
+	while (off < len)
+	{
+		ssize_t		rc = write(shell_to_child, line + off, len - off);
+
+		if (rc < 0)
+		{
+			if (errno == EINTR)
+				continue;
+			/*
+			 * Backpressure is only safe before any bytes of this line were
+			 * queued.  A partial line would desynchronize the protocol.
+			 */
+			if ((errno == EAGAIN || errno == EWOULDBLOCK) && off == 0)
+				return 0;
+			ereport(LOG,
+					(errmsg("could not write to archive command: %m")));
+			return -1;
+		}
+		off += (size_t) rc;
+	}
+	return 1;
+}
+
+static bool
+shell_read_line(char *buf, size_t buflen, long timeout_ms)
+{
+	TimestampTz deadline = 0;
+	bool		have_deadline = false;
+
+	if (timeout_ms > 0)
+	{
+		deadline = GetCurrentTimestamp() + timeout_ms * 1000;
+		have_deadline = true;
+	}
+
+	if (!shell_sigchld_armed)
+	{
+		pqsignal(SIGCHLD, shell_sigchld_handler);
+		shell_sigchld_armed = true;
+	}
+
+	for (;;)
+	{
+		char	   *nl;
+		long		wait_ms;
+		int			rc;
+		ssize_t		nread;
+
+		nl = memchr(shell_inbuf, '\n', shell_inlen);
+		if (nl != NULL)
+		{
+			size_t		linelen = nl - shell_inbuf;
+
+			if (linelen >= buflen)
+			{
+				ereport(LOG,
+						(errmsg("archive command response line too long")));
+				shell_fail_outstanding();
+				return false;
+			}
+			memcpy(buf, shell_inbuf, linelen);
+			buf[linelen] = '\0';
+			if (linelen > 0 && buf[linelen - 1] == '\r')
+				buf[linelen - 1] = '\0';
+			linelen++;
+			shell_inlen -= linelen;
+			memmove(shell_inbuf, shell_inbuf + linelen, shell_inlen);
+			return true;
+		}
+
+		if (shell_report_retry)
+			return false;
+		if (!shell_child_alive())
+		{
+			shell_fail_outstanding();
+			return false;
+		}
+
+		if (have_deadline)
+		{
+			long		secs;
+			int			usecs;
+
+			if (TimestampDifferenceExceeds(deadline, GetCurrentTimestamp(), 0))
+				return false;
+			TimestampDifference(GetCurrentTimestamp(), deadline, &secs, &usecs);
+			wait_ms = secs * 1000 + usecs / 1000;
+			if (wait_ms <= 0)
+				wait_ms = 1;
+		}
+		else
+			wait_ms = 0;
+
+		rc = WaitLatchOrSocket(MyLatch,
+							  WL_LATCH_SET | WL_TIMEOUT |
+							  WL_SOCKET_READABLE | WL_EXIT_ON_PM_DEATH,
+							  shell_from_child,
+							  wait_ms,
+							  WAIT_EVENT_ARCHIVE_COMMAND);
+		ResetLatch(MyLatch);
+
+		if (!(rc & WL_SOCKET_READABLE))
+		{
+			if (!have_deadline)
+				return false;
+			continue;
+		}
+
+		if (shell_inlen >= (int) sizeof(shell_inbuf))
+		{
+			ereport(LOG,
+					(errmsg("archive command response line too long")));
+			shell_fail_outstanding();
+			return false;
+		}
+
+		nread = read(shell_from_child, shell_inbuf + shell_inlen,
+					 sizeof(shell_inbuf) - shell_inlen);
+		if (nread < 0)
+		{
+			if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
+				continue;
+			ereport(LOG,
+					(errmsg("could not read from archive command: %m")));
+			shell_fail_outstanding();
+			return false;
+		}
+		if (nread == 0)
+		{
+			shell_fail_outstanding();
+			return false;
+		}
+		shell_inlen += (int) nread;
+
+		if (!have_deadline)
+		{
+			nl = memchr(shell_inbuf, '\n', shell_inlen);
+			if (nl == NULL)
+				return false;
+		}
+	}
+}
+
+static bool
+shell_parse_result(const char *line, char *file, size_t filelen,
+				   ArchiveResultStatus *status)
+{
+	const char *file_start;
+	const char *file_end;
+	const char *result;
+	size_t		n;
+
+	if (strncmp(line, "archived\t", 9) != 0)
+		return false;
+
+	file_start = line + 9;
+	file_end = strchr(file_start, '\t');
+	if (file_end == NULL || file_end == file_start)
+		return false;
+
+	n = file_end - file_start;
+	if (n >= filelen)
+		return false;
+	memcpy(file, file_start, n);
+	file[n] = '\0';
+
+	result = file_end + 1;
+	if (strcmp(result, "ok") == 0)
+		*status = ARCHIVE_RESULT_SUCCESS;
+	else if (strcmp(result, "retry") == 0)
+		*status = ARCHIVE_RESULT_RETRY;
+	else if (strcmp(result, "fail") == 0)
+		*status = ARCHIVE_RESULT_FAIL;
+	else
+		return false;
+	return true;
+}
+
+static bool
+shell_spawn_child(void)
+{
+	int			inpipe[2];
+	int			outpipe[2];
+	pid_t		pid;
+
+	if (pipe(inpipe) < 0)
+	{
+		ereport(LOG,
+				(errcode_for_socket_access(),
+				 errmsg("could not create pipe for archive command: %m")));
+		return false;
+	}
+	if (pipe(outpipe) < 0)
+	{
+		ereport(LOG,
+				(errcode_for_socket_access(),
+				 errmsg("could not create pipe for archive command: %m")));
+		close(inpipe[0]);
+		close(inpipe[1]);
+		return false;
+	}
+
+	fflush(NULL);
+	pid = fork_process();
+	if (pid == 0)
+	{
+		shell_prepare_child();
+		close(inpipe[1]);
+		close(outpipe[0]);
+		if (dup2(inpipe[0], STDIN_FILENO) < 0 ||
+			dup2(outpipe[1], STDOUT_FILENO) < 0)
+			_exit(126);
+		close(inpipe[0]);
+		close(outpipe[1]);
+		execl("/bin/sh", "sh", "-c", XLogArchiveCommand, (char *) NULL);
+		_exit(127);
+	}
+
+	close(inpipe[0]);
+	close(outpipe[1]);
+	if (pid < 0)
+	{
+		ereport(LOG,
+				(errmsg("could not fork archive command: %m")));
+		close(inpipe[1]);
+		close(outpipe[0]);
+		return false;
+	}
+
+	shell_child_pid = pid;
+	shell_to_child = inpipe[1];
+	shell_from_child = outpipe[0];
+	shell_inlen = 0;
+	if (!pg_set_noblock(shell_to_child) ||
+		!pg_set_noblock(shell_from_child))
+	{
+		ereport(LOG,
+				(errmsg("could not set nonblocking mode for archive command pipe: %m")));
+		shell_kill_child();
+		return false;
+	}
+
+	ereport(DEBUG1,
+			(errmsg_internal("started persistent archive command \"%s\"",
+							 XLogArchiveCommand)));
+	return true;
+}
+
+static bool
+shell_ensure_child(void)
+{
+	if (shell_child_pid > 0)
+	{
+		if (shell_child_alive())
+			return true;
+
+		shell_fail_outstanding();
+		if (shell_report_retry)
+			return false;
+	}
+	return shell_spawn_child();
+}
+
+static bool
+shell_archive_submit(ArchiveModuleState *state,
+					 const char *file,
+					 const char *path)
+{
+	char		line[MAXPGPATH + MAX_XFN_CHARS + 32];
+	char		nativePath[MAXPGPATH];
+
+	(void) state;
+
+	if (shell_report_retry)
+		return false;
+	if (shell_noutstanding >= XLogArchiveAsyncMax)
+		return false;
+	if (!shell_ensure_child())
+		return false;
+
+	strlcpy(nativePath, path, sizeof(nativePath));
+	make_native_path(nativePath);
+
+	if (!shell_outstanding_add(file))
+		return false;
+
+	snprintf(line, sizeof(line), "archive\t%s\t%s\n", file, nativePath);
+	switch (shell_write_line(line))
+	{
+		case 1:
+			return true;
+		case 0:
+			/* Pipe full: leave helper alone and ask caller to back off. */
+			shell_outstanding_remove(file);
+			return false;
+		default:
+			shell_outstanding_remove(file);
+			shell_fail_outstanding();
+			return false;
+	}
+}
+
+static bool
+shell_archive_poll(ArchiveModuleState *state, const char **file,
+				   ArchiveResultStatus *status, long timeout_ms)
+{
+	char		line[MAXPGPATH];
+
+	(void) state;
+
+	if (shell_take_retry(file, status))
+		return true;
+
+	if (shell_child_pid <= 0)
+	{
+		if (shell_noutstanding > 0)
+		{
+			shell_fail_outstanding();
+			return shell_take_retry(file, status);
+		}
+		return false;
+	}
+
+	if (!shell_read_line(line, sizeof(line), timeout_ms))
+		return shell_take_retry(file, status);
+
+	if (!shell_parse_result(line, shell_result_file, sizeof(shell_result_file),
+						   status) ||
+		!shell_outstanding_remove(shell_result_file))
+	{
+		ereport(LOG,
+				(errmsg("archive command sent bad response \"%s\"", line)));
+		shell_fail_outstanding();
+		return shell_take_retry(file, status);
+	}
+
+	*file = shell_result_file;
+	if (*status == ARCHIVE_RESULT_SUCCESS)
+		elog(DEBUG1, "archived write-ahead log file \"%s\"", shell_result_file);
+	return true;
+}
+
+static void
+shell_archive_cancel(ArchiveModuleState *state)
+{
+	(void) state;
+	shell_noutstanding = 0;
+	shell_report_retry = false;
+	shell_kill_child();
+}
+
+#endif										/* !WIN32 */
+
 static void
 shell_archive_shutdown(ArchiveModuleState *state)
 {
+	(void) state;
+#ifndef WIN32
+	shell_archive_cancel(state);
+#endif
 	elog(DEBUG1, "archiver process shutting down");
 }
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index e1122f76760..b36aece72e0 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -149,6 +149,8 @@ typedef struct ArchInFlight
 static ArchInFlight arch_inflight[ARCHIVE_ASYNC_SLOT_LIMIT];
 static int	arch_inflight_count = 0;
 static bool archiver_use_async = false;
+static bool archiver_shell_persistent = false;
+static char *archiver_shell_command = NULL;
 
 /*
  * Flags set by interrupt handlers for later service in the main loop.
@@ -1273,6 +1275,7 @@ ProcessPgArchInterrupts(void)
 	{
 		char	   *archiveLib = pstrdup(XLogArchiveLibrary);
 		bool		archiveLibChanged;
+		bool		old_persistent = XLogArchiveCommandPersistent;
 
 		ConfigReloadPending = false;
 		ProcessConfigFile(PGC_SIGHUP);
@@ -1304,6 +1307,30 @@ ProcessPgArchInterrupts(void)
 			proc_exit(0);
 		}
 
+		/*
+		 * Persistent vs classic shell archiving selects different module
+		 * callbacks at archiver start, so adopt the new mode via restart.
+		 * Likewise, a persistent helper is started with a fixed command
+		 * string, so restart when that command changes under persistent
+		 * mode.
+		 */
+		if (old_persistent != XLogArchiveCommandPersistent)
+		{
+			ereport(LOG,
+					(errmsg("restarting archiver process because value of "
+							"\"archive_command_persistent\" was changed")));
+			proc_exit(0);
+		}
+
+		if (archiver_shell_persistent &&
+			archiver_shell_command != NULL &&
+			strcmp(archiver_shell_command, XLogArchiveCommand) != 0)
+		{
+			ereport(LOG,
+					(errmsg("restarting archiver process because value of "
+							"\"archive_command\" was changed")));
+			proc_exit(0);
+		}
 	}
 }
 
@@ -1359,6 +1386,15 @@ LoadArchiveLibrary(void)
 		ereport(ERROR,
 				(errmsg("archive modules must register an archive callback")));
 
+	/*
+	 * Remember the shell settings used for this archiver lifetime so SIGHUP
+	 * can decide whether a restart is required.
+	 */
+	archiver_shell_persistent = XLogArchiveCommandPersistent;
+	if (archiver_shell_command)
+		pfree(archiver_shell_command);
+	archiver_shell_command = pstrdup(XLogArchiveCommand);
+
 	archive_module_state = palloc0_object(ArchiveModuleState);
 	if (ArchiveCallbacks->startup_cb != NULL)
 		ArchiveCallbacks->startup_cb(archive_module_state);
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index eeefbf0ceea..ca61f1e4e86 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -69,7 +69,7 @@
 
 { name => 'archive_async_max', type => 'int', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
   short_desc => 'Sets the maximum number of WAL files in flight for asynchronous archiving.',
-  long_desc => 'Used by asynchronous archive modules. Ignored by synchronous archive_file_cb modules.',
+  long_desc => 'Used by asynchronous archive modules and by persistent archive_command. Ignored by synchronous archive_file_cb modules.',
   variable => 'XLogArchiveAsyncMax',
   boot_val => '8',
   min => '1',
@@ -90,6 +90,14 @@
   show_hook => 'show_archive_command',
 },
 
+{ name => 'archive_command_persistent', type => 'bool', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
+  short_desc => 'Runs archive_command as a long-lived process fed over stdin.',
+  long_desc => 'When on, PostgreSQL starts archive_command once and feeds it ready WAL file names. The command must not contain %f or %p placeholders.',
+  variable => 'XLogArchiveCommandPersistent',
+  boot_val => 'false',
+  check_hook => 'check_archive_command_persistent',
+},
+
 { name => 'archive_library', type => 'string', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
   short_desc => 'Sets the library that will be called to archive a WAL file.',
   long_desc => 'An empty string means use "archive_command".',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index f1d8033267f..df46bc2bcdd 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -299,6 +299,7 @@
                                 # be used)
 #archive_async_max = 8          # max in-flight files for async archiving
 #archive_command = ''           # command to use to archive a WAL file
+#archive_command_persistent = off # feed archive_command over stdin
                                 # placeholders: %p = path of file to archive
                                 #               %f = file name only
                                 # e.g. 'test ! -f "/mnt/server/archivedir/%f" && cp "%p" "/mnt/server/archivedir/%f"'
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index b57f7477709..18ee8131eb8 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -44,6 +44,7 @@ extern PGDLLIMPORT int XLOGbuffers;
 extern PGDLLIMPORT int XLogArchiveTimeout;
 extern PGDLLIMPORT int wal_retrieve_retry_interval;
 extern PGDLLIMPORT char *XLogArchiveCommand;
+extern PGDLLIMPORT bool XLogArchiveCommandPersistent;
 extern PGDLLIMPORT int XLogArchiveAsyncMax;
 extern PGDLLIMPORT bool EnableHotStandby;
 extern PGDLLIMPORT bool fullPageWrites;
diff --git a/src/include/utils/guc_hooks.h b/src/include/utils/guc_hooks.h
index 8e3c067f760..b20315e72af 100644
--- a/src/include/utils/guc_hooks.h
+++ b/src/include/utils/guc_hooks.h
@@ -29,6 +29,8 @@ extern bool check_application_name(char **newval, void **extra,
 								   GucSource source);
 extern void assign_application_name(const char *newval, void *extra);
 extern const char *show_archive_command(void);
+extern bool check_archive_command_persistent(bool *newval, void **extra,
+											 GucSource source);
 extern bool check_autovacuum_work_mem(int *newval, void **extra,
 									  GucSource source);
 extern bool check_vacuum_buffer_usage_limit(int *newval, void **extra,
-- 
2.56.1

Reply via email to