Hi,
Follow up to [1] and the older parallel archiver threads [2][3].
Today archiving often runs in peaks. One file starts, finishes, then the
next starts, so throughput is stop and go. That is especially noticeable
when the archive target is slow, for example object storage such as S3 or
a distant NFS share, where each file pays a long wait. Async work keeps
several files in flight and reports each one as it completes, so
utilization stays high instead of sitting idle between handoffs.
There is a second pain point. pgarch currently blocks inside system() for
the whole archive_command, so a hung script can leave the archiver stuck
until someone kills the child by hand.
The idea here is simple. pgarch keeps a small fixed pool of archive
workers. Ready files go into free slots, and when a worker finishes the
next file takes its place. Core still marks .done and can cancel stuck
work on shutdown. archive_command_jobs sets the pool size, default 1.
On Unix values from 2 to 8 start one short lived archive_command child
per slot. The feature is not available on Windows yet. Existing sync
modules keep working as before.
Attached archive_jobs_bench.sh builds a .ready backlog, then times how
long archive_command_jobs takes to drain it. The command optionally
sleeps, then copies each WAL file into an archive directory.
PGBIN=/path/to/bin ./archive_jobs_bench.sh [rounds] [delay_ms/jobs ...]
delay=500ms + cp, 16 files (median of 3)
jobs=1 8.35s
jobs=2 4.18s (~2.0x)
jobs=4 2.12s (~3.9x)
jobs=8 1.10s (~7.6x)
delay=0 + cp, 120 files (median of 3)
jobs=1 1.93s
jobs=2 1.02s (~1.9x)
jobs=4 0.43s (~4.5x)
jobs=8 0.29s (~6.7x)
Andrey Borodin put the same peak load complaint from the walg side and
preferred a pipe style protocol over batches. Would it make sense to grow
this later into that shape, with pgarch feeding file names and getting
completed or failed files back one by one?
I used AI to sketch the first prototype, then cleaned it up by hand. The
series is still large, but the shape looks promising to me. Does this
direction seem reasonable?
Regards,
Stepan Neretin
[1]
https://www.postgresql.org/message-id/CA%2BYyo5QRxow54ekSUWu4qzckYWhSg5BWiFfQ37UdU3QGBC3Kxg%40mail.gmail.com
[2]
https://www.postgresql.org/message-id/flat/BC335D75-105B-403F-9473-976C8BBC32E3%40yandex-team.ru
[3]
https://www.postgresql.org/message-id/BC4D6BB2-6976-4397-A417-A6A30EEDC63E%40amazon.com
From 69307328bb0b6ead0ed08e26b3b02c9a2fd5e561 Mon Sep 17 00:00:00 2001
From: Stepan Neretin <[email protected]>
Date: Wed, 4 Nov 2026 13:34:54 +0700
Subject: [PATCH 1/2] Support async archive callbacks in pgarch.
Add optional submit_cb, poll_cb, and cancel_cb, and drive multiple in
flight WAL files. Modules use archive_file_cb or the async pair with
cancel_cb. On SIGUSR2, drain in flight work for up to 60s before cancel.
ShutdownRequestPending still aborts at once.
---
src/backend/postmaster/pgarch.c | 659 +++++++++++++++++++++------
src/include/archive/archive_module.h | 20 +-
src/tools/pgindent/typedefs.list | 5 +
3 files changed, 551 insertions(+), 133 deletions(-)
diff --git a/src/backend/postmaster/pgarch.c b/src/backend/postmaster/pgarch.c
index a3fd4f83201..930e7a2f559 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
@@ -134,6 +136,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[NUM_FILES_PER_DIRECTORY_SCAN];
+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 +160,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 +169,20 @@ 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 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 +377,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 +413,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 +431,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 +453,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 +496,469 @@ 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 < NUM_FILES_PER_DIRECTORY_SCAN; 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 < NUM_FILES_PER_DIRECTORY_SCAN; 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 < NUM_FILES_PER_DIRECTORY_SCAN; 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_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 (;;)
+ {
+ int skips = 0;
+ char xlog[MAX_XFN_CHARS + 1];
+ char done_file[MAX_XFN_CHARS + 1];
+ ArchiveResultStatus status;
+ int cbres;
+ ArchInFlight *slot;
+
+ if (ShutdownRequestPending || !PostmasterIsAlive())
+ {
+ pgarch_abort_async_inflight_msg("canceling in flight archive commands due to shutdown");
+ return;
+ }
+
+ ProcessPgArchInterrupts();
+ if (!pgarch_archive_configured())
+ {
+ pgarch_abort_async_inflight_msg("canceling in flight archive commands because archiving is no longer configured");
+ return;
+ }
+
+ 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;
+ }
+ }
+
+ while (!give_up &&
+ arch_inflight_count < NUM_FILES_PER_DIRECTORY_SCAN &&
+ skips < NUM_FILES_PER_DIRECTORY_SCAN)
+ {
+ int wal_present;
+
+ 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))
+ {
+ skips++;
+ continue;
+ }
+
+ 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, sizeof(deferred));
+ break;
+ }
+
+ skips = 0;
+ pgarch_set_activity("submitting %s", xlog);
+
+ cbres = pgarch_submitXlog(xlog);
+ if (cbres < 0)
+ {
+ if (pgarch_async_finish(slot, ARCHIVE_RESULT_RETRY))
+ give_up = true;
+ continue;
+ }
+ if (cbres == 0)
+ {
+ strlcpy(deferred, xlog, sizeof(deferred));
+ break;
+ }
+
+ slot->waiting = true;
+ arch_inflight_count++;
+ }
+
+ 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)
+ {
+ (void) WaitLatch(MyLatch,
+ WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
+ PGARCH_ASYNC_POLL_MS,
+ WAIT_EVENT_ARCHIVER_MAIN);
+ ResetLatch(MyLatch);
+ continue;
+ }
+ 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 +972,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 +985,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 +1009,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 +1286,7 @@ ProcessPgArchInterrupts(void)
proc_exit(0);
}
+
}
}
@@ -937,7 +1323,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/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.0
From 6b64542ea666784b2574167b1429e4a72adbfa7b Mon Sep 17 00:00:00 2001
From: Stepan Neretin <[email protected]>
Date: Wed, 4 Nov 2026 13:35:40 +0700
Subject: [PATCH 2/2] Add archive_command_jobs.
Allow up to eight concurrent short lived archive_command children on
Unix. Default 1 keeps the sync system() path. GUC changes restart the
archiver. Windows rejects values above 1. TAP covers reload, failure,
hang jobs, and shutdown cancel.
---
src/backend/access/transam/xlog.c | 15 +
src/backend/archive/shell_archive.c | 348 +++++++++++++++---
src/backend/postmaster/pgarch.c | 10 +
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 +
src/test/recovery/meson.build | 1 +
.../recovery/t/062_archive_command_jobs.pl | 198 ++++++++++
9 files changed, 533 insertions(+), 53 deletions(-)
create mode 100644 src/test/recovery/t/062_archive_command_jobs.pl
diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index fd37ea4f607..f99f379f383 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 XLogArchiveCommandJobs = 1;
bool EnableHotStandby = false;
bool fullPageWrites = true;
bool wal_log_hints = false;
@@ -5446,6 +5447,20 @@ show_archive_command(void)
return "(disabled)";
}
+bool
+check_archive_command_jobs(int *newval, void **extra, GucSource source)
+{
+#ifdef WIN32
+ if (*newval > 1)
+ {
+ GUC_check_errcode(ERRCODE_FEATURE_NOT_SUPPORTED);
+ GUC_check_errmsg("\"archive_command_jobs\" greater than 1 is not supported on Windows");
+ return false;
+ }
+#endif
+ 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..b1f4ab1b3b9 100644
--- a/src/backend/archive/shell_archive.c
+++ b/src/backend/archive/shell_archive.c
@@ -15,32 +15,84 @@
*/
#include "postgres.h"
+#include <signal.h>
#include <sys/wait.h>
+#ifndef WIN32
+#include <unistd.h>
+#endif
#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 "pgstat.h"
+#ifndef WIN32
+#include "postmaster/fork_process.h"
+#endif
+#include "miscadmin.h"
+#include "storage/latch.h"
#include "utils/wait_event.h"
+/* Keep in sync with archive_command_jobs GUC maximum. */
+#define ARCHIVE_COMMAND_JOBS_MAX 8
+
+#ifndef WIN32
+static struct
+{
+ pid_t pid;
+ char file[MAX_XFN_CHARS + 1];
+} shell_jobs[ARCHIVE_COMMAND_JOBS_MAX];
+static int shell_nactive = 0;
+static char shell_done_file[MAX_XFN_CHARS + 1];
+static bool shell_sigchld_armed = false;
+
+static void shell_sigchld_handler(SIGNAL_ARGS);
+static void shell_prepare_child(void);
+static void shell_kill_job(pid_t pid);
+#endif
+
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);
+#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);
+#endif
-static const ArchiveModuleCallbacks shell_archive_callbacks = {
- .startup_cb = NULL,
+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
+};
+#endif
+
const ArchiveModuleCallbacks *
shell_archive_init(void)
{
- return &shell_archive_callbacks;
+#ifndef WIN32
+ if (XLogArchiveCommandJobs > 1)
+ return &shell_archive_async_callbacks;
+#endif
+ return &shell_archive_sync_callbacks;
}
static bool
@@ -54,13 +106,11 @@ shell_archive_configured(ArchiveModuleState *state)
return false;
}
-static bool
-shell_archive_file(ArchiveModuleState *state, const char *file,
- const char *path)
+static char *
+shell_build_command(const char *file, const char *path)
{
- char *xlogarchcmd;
char *nativePath = NULL;
- int rc;
+ char *cmd;
if (path)
{
@@ -68,76 +118,268 @@ shell_archive_file(ArchiveModuleState *state, const char *file,
make_native_path(nativePath);
}
- xlogarchcmd = replace_percent_placeholders(XLogArchiveCommand,
- "archive_command", "fp",
- file, nativePath);
+ cmd = replace_percent_placeholders(XLogArchiveCommand,
+ "archive_command", "fp",
+ file, nativePath);
+ if (nativePath)
+ pfree(nativePath);
+ return cmd;
+}
+
+static void
+shell_report_failure(const char *cmd, int rc)
+{
+ int lev = wait_result_is_any_signal(rc, true) ? FATAL : LOG;
+
+ if (WIFEXITED(rc))
+ {
+ ereport(lev,
+ (errmsg("archive command failed with exit code %d",
+ WEXITSTATUS(rc)),
+ errdetail("The failed archive command was: %s",
+ cmd)));
+ }
+ else if (WIFSIGNALED(rc))
+ {
+#if defined(WIN32)
+ ereport(lev,
+ (errmsg("archive command was terminated by exception 0x%X",
+ WTERMSIG(rc)),
+ errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
+ errdetail("The failed archive command was: %s",
+ cmd)));
+#else
+ ereport(lev,
+ (errmsg("archive command was terminated by signal %d: %s",
+ WTERMSIG(rc), pg_strsignal(WTERMSIG(rc))),
+ errdetail("The failed archive command was: %s",
+ cmd)));
+#endif
+ }
+ else
+ {
+ ereport(lev,
+ (errmsg("archive command exited with unrecognized status %d",
+ rc),
+ errdetail("The failed archive command was: %s",
+ cmd)));
+ }
+}
+
+static bool
+shell_archive_file(ArchiveModuleState *state, const char *file,
+ const char *path)
+{
+ char *cmd = shell_build_command(file, path);
+ int rc;
ereport(DEBUG3,
(errmsg_internal("executing archive command \"%s\"",
- xlogarchcmd)));
+ cmd)));
fflush(NULL);
pgstat_report_wait_start(WAIT_EVENT_ARCHIVE_COMMAND);
- rc = system(xlogarchcmd);
+ rc = system(cmd);
pgstat_report_wait_end();
if (rc != 0)
+ shell_report_failure(cmd, rc);
+ else
+ elog(DEBUG1, "archived write-ahead log file \"%s\"", file);
+
+ pfree(cmd);
+ return (rc == 0);
+}
+
+#ifndef WIN32
+static void
+shell_report_file_failure(const char *file, int rc)
+{
+ char pathname[MAXPGPATH];
+ char *cmd;
+
+ snprintf(pathname, MAXPGPATH, XLOGDIR "/%s", file);
+ cmd = shell_build_command(file, pathname);
+ shell_report_failure(cmd, rc);
+ pfree(cmd);
+}
+
+static bool
+shell_archive_submit(ArchiveModuleState *state, const char *file,
+ const char *path)
+{
+ char *cmd;
+ pid_t pid;
+
+ if (shell_nactive >= XLogArchiveCommandJobs)
+ return false;
+
+ cmd = shell_build_command(file, path);
+ ereport(DEBUG3,
+ (errmsg_internal("submitting archive command \"%s\"",
+ cmd)));
+
+ pid = fork_process();
+ if (pid == 0)
+ {
+ if (setpgid(0, 0) < 0)
+ _exit(1);
+ shell_prepare_child();
+ execl("/bin/sh", "sh", "-c", cmd, (char *) NULL);
+ _exit(127);
+ }
+ if (pid < 0)
{
- /*
- * If either the shell itself, or a called command, died on a signal,
- * abort the archiver. We do this because system() ignores SIGINT and
- * SIGQUIT while waiting; so a signal is very likely something that
- * should have interrupted us too. Also die if the shell got a hard
- * "command not found" type of error. If we overreact it's no big
- * deal, the postmaster will just start the archiver again.
- */
- int lev = wait_result_is_any_signal(rc, true) ? FATAL : LOG;
-
- if (WIFEXITED(rc))
+ ereport(LOG,
+ (errmsg("could not fork archive command: %m"),
+ errdetail("The failed archive command was: %s",
+ cmd)));
+ pfree(cmd);
+ return false;
+ }
+
+ /* EACCES means the child already set its process group. */
+ if (setpgid(pid, pid) < 0 && errno != EACCES)
+ ereport(LOG,
+ (errmsg("could not set process group for archive command: %m")));
+
+ shell_jobs[shell_nactive].pid = pid;
+ strlcpy(shell_jobs[shell_nactive].file, file,
+ sizeof(shell_jobs[shell_nactive].file));
+ shell_nactive++;
+ pfree(cmd);
+ return true;
+}
+
+static bool
+shell_try_reap(const char **file, ArchiveResultStatus *status)
+{
+ int i;
+
+ for (i = 0; i < shell_nactive; i++)
+ {
+ int waitstatus;
+ pid_t done;
+
+ for (;;)
+ {
+ done = waitpid(shell_jobs[i].pid, &waitstatus, WNOHANG);
+ if (!(done < 0 && errno == EINTR))
+ break;
+ }
+
+ if (done == 0)
+ continue;
+
+ strlcpy(shell_done_file, shell_jobs[i].file, sizeof(shell_done_file));
+ *file = shell_done_file;
+ shell_jobs[i] = shell_jobs[--shell_nactive];
+
+ if (done < 0)
{
- ereport(lev,
- (errmsg("archive command failed with exit code %d",
- WEXITSTATUS(rc)),
- errdetail("The failed archive command was: %s",
- xlogarchcmd)));
+ ereport(LOG,
+ (errmsg("could not wait for archive command: %m"),
+ errdetail("While waiting for write-ahead log file \"%s\"",
+ shell_done_file)));
+ *status = ARCHIVE_RESULT_RETRY;
}
- else if (WIFSIGNALED(rc))
+ else if (waitstatus == 0)
{
-#if defined(WIN32)
- ereport(lev,
- (errmsg("archive command was terminated by exception 0x%X",
- WTERMSIG(rc)),
- errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
- errdetail("The failed archive command was: %s",
- xlogarchcmd)));
-#else
- ereport(lev,
- (errmsg("archive command was terminated by signal %d: %s",
- WTERMSIG(rc), pg_strsignal(WTERMSIG(rc))),
- errdetail("The failed archive command was: %s",
- xlogarchcmd)));
-#endif
+ *status = ARCHIVE_RESULT_SUCCESS;
+ elog(DEBUG1, "archived write-ahead log file \"%s\"",
+ shell_done_file);
}
else
{
- ereport(lev,
- (errmsg("archive command exited with unrecognized status %d",
- rc),
- errdetail("The failed archive command was: %s",
- xlogarchcmd)));
+ if (wait_result_is_any_signal(waitstatus, true))
+ shell_archive_cancel(NULL);
+ shell_report_file_failure(shell_done_file, waitstatus);
+ *status = ARCHIVE_RESULT_RETRY;
}
- pfree(xlogarchcmd);
+ return true;
+ }
+
+ return false;
+}
+
+static void
+shell_sigchld_handler(SIGNAL_ARGS)
+{
+ int save_errno = errno;
+ SetLatch(MyLatch);
+ errno = save_errno;
+}
+
+static void
+shell_prepare_child(void)
+{
+ pqsignal(SIGHUP, PG_SIG_DFL);
+ pqsignal(SIGINT, PG_SIG_DFL);
+ pqsignal(SIGTERM, PG_SIG_DFL);
+ pqsignal(SIGQUIT, PG_SIG_DFL);
+ pqsignal(SIGALRM, PG_SIG_DFL);
+ pqsignal(SIGPIPE, PG_SIG_DFL);
+ pqsignal(SIGUSR1, PG_SIG_DFL);
+ pqsignal(SIGUSR2, PG_SIG_DFL);
+ pqsignal(SIGCHLD, PG_SIG_DFL);
+ sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
+}
+
+static void
+shell_kill_job(pid_t pid)
+{
+ int status;
+
+ if (kill(-pid, SIGKILL) < 0 && errno != ESRCH)
+ kill(pid, SIGKILL);
+
+ while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
+ ;
+}
+
+static bool
+shell_archive_poll(ArchiveModuleState *state, const char **file,
+ ArchiveResultStatus *status, long timeout_ms)
+{
+ if (shell_try_reap(file, status))
+ return true;
+ if (timeout_ms <= 0 || shell_nactive <= 0)
return false;
+
+ if (!shell_sigchld_armed)
+ {
+ pqsignal(SIGCHLD, shell_sigchld_handler);
+ shell_sigchld_armed = true;
}
- pfree(xlogarchcmd);
+ if (shell_try_reap(file, status))
+ return true;
- elog(DEBUG1, "archived write-ahead log file \"%s\"", file);
- return true;
+ (void) WaitLatch(MyLatch,
+ WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
+ timeout_ms,
+ WAIT_EVENT_ARCHIVE_COMMAND);
+ ResetLatch(MyLatch);
+
+ return shell_try_reap(file, status);
}
+static void
+shell_archive_cancel(ArchiveModuleState *state)
+{
+ while (shell_nactive > 0)
+ {
+ shell_nactive--;
+ shell_kill_job(shell_jobs[shell_nactive].pid);
+ }
+}
+#endif /* !WIN32 */
+
static void
shell_archive_shutdown(ArchiveModuleState *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 930e7a2f559..4d806597e97 100644
--- a/src/backend/postmaster/pgarch.c
+++ b/src/backend/postmaster/pgarch.c
@@ -147,6 +147,7 @@ typedef struct ArchInFlight
static ArchInFlight arch_inflight[NUM_FILES_PER_DIRECTORY_SCAN];
static int arch_inflight_count = 0;
static bool archiver_use_async = false;
+static int archiver_shell_jobs = 1;
/*
* Flags set by interrupt handlers for later service in the main loop.
@@ -1287,6 +1288,14 @@ ProcessPgArchInterrupts(void)
proc_exit(0);
}
+ if (XLogArchiveLibrary[0] == '\0' &&
+ XLogArchiveCommandJobs != archiver_shell_jobs)
+ {
+ ereport(LOG,
+ (errmsg("restarting archiver process because value of "
+ "\"archive_command_jobs\" was changed")));
+ proc_exit(0);
+ }
}
}
@@ -1329,6 +1338,7 @@ LoadArchiveLibrary(void)
(errmsg("archive modules must provide both submit and poll callbacks for asynchronous archiving")));
archiver_use_async = (ArchiveCallbacks->submit_cb != NULL);
+ archiver_shell_jobs = XLogArchiveCommandJobs;
if (archiver_use_async)
{
if (ArchiveCallbacks->archive_file_cb != NULL)
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..0e67e1d32c8 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -81,6 +81,16 @@
show_hook => 'show_archive_command',
},
+{ name => 'archive_command_jobs', type => 'int', context => 'PGC_SIGHUP', group => 'WAL_ARCHIVING',
+ short_desc => 'Sets the maximum number of concurrent archive_command processes.',
+ long_desc => 'Values greater than 1 are not supported on Windows.',
+ variable => 'XLogArchiveCommandJobs',
+ boot_val => '1',
+ min => '1',
+ max => '8',
+ check_hook => 'check_archive_command_jobs',
+},
+
{ 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 b492b3af06c..90226cbe631 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -301,6 +301,7 @@
# 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"'
+#archive_command_jobs = 1 # max concurrent archive_command processes (Unix)
#archive_timeout = 0 # force a WAL file switch after this
# number of seconds; 0 disables
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 2bf5714b51e..c3a6f73fd1a 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 XLogArchiveCommandJobs;
extern PGDLLIMPORT bool EnableHotStandby;
extern PGDLLIMPORT bool fullPageWrites;
extern PGDLLIMPORT bool wal_log_hints;
diff --git a/src/include/utils/guc_hooks.h b/src/include/utils/guc_hooks.h
index 8e3c067f760..10fdd6040f6 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_jobs(int *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,
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..811ca481f86 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_jobs.pl',
],
},
}
diff --git a/src/test/recovery/t/062_archive_command_jobs.pl b/src/test/recovery/t/062_archive_command_jobs.pl
new file mode 100644
index 00000000000..3a458d542ee
--- /dev/null
+++ b/src/test/recovery/t/062_archive_command_jobs.pl
@@ -0,0 +1,198 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+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('jobs');
+$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_jobs = 2');
+ $node->reload;
+ $node->wait_for_log(
+ qr/"archive_command_jobs" greater than 1 is not supported on Windows/,
+ $offset);
+ is( $node->safe_psql('postgres', 'SHOW archive_command_jobs'),
+ '1', 'archive_command_jobs > 1 rejected on Windows');
+ $node->stop;
+ done_testing();
+ exit;
+}
+
+$node->append_conf('postgresql.conf', 'archive_command_jobs = 2');
+$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 reload_jobs
+{
+ my ($jobs, $extra) = @_;
+ my $offset = -s $node->logfile;
+ $node->append_conf(
+ 'postgresql.conf',
+ qq{archive_command_jobs = $jobs\n} . ($extra // ''));
+ $node->reload;
+ $node->wait_for_log(
+ qr/restarting archiver process because value of "archive_command_jobs" was changed/,
+ $offset);
+ $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 after archive_command_jobs change';
+}
+
+sub wait_for_hang_pids
+{
+ my ($hang_log, $want) = @_;
+ my @pids;
+
+ for (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default)
+ {
+ if (-f $hang_log)
+ {
+ @pids = grep { length } split /\n/, slurp_file($hang_log);
+ last if @pids >= $want;
+ }
+ usleep(100_000);
+ }
+ return @pids;
+}
+
+# Basic async archive.
+for (1 .. 3) { switch_wal(1); }
+ok(
+ $node->poll_query_until(
+ 'postgres', q{SELECT archived_count >= 3 FROM pg_stat_archiver}, 't'),
+ 'archive_command_jobs=2 archives WAL');
+
+# Reload between async and sync modes.
+reload_jobs(3);
+reload_jobs(1);
+is( $node->safe_psql('postgres', 'SHOW archive_command_jobs'),
+ '1', 'SHOW archive_command_jobs is 1 after reload');
+my $before = archived_count();
+switch_wal(10);
+wait_archived_gt($before, 'archive advances after reload to jobs=1');
+
+# Failure under jobs=2, then recover.
+reload_jobs(2);
+my $bad_cmd = 'cp "%p_does_not_exist" "%f_does_not_exist"';
+my $failed_before = $node->safe_psql('postgres',
+ q{SELECT failed_count FROM pg_stat_archiver});
+
+$node->safe_psql(
+ 'postgres', qq{
+ ALTER SYSTEM SET archive_command TO '$bad_cmd';
+ SELECT pg_reload_conf();
+});
+switch_wal(11);
+ok(
+ $node->poll_query_until(
+ 'postgres',
+ qq{SELECT failed_count > $failed_before FROM pg_stat_archiver},
+ 't'),
+ 'failing archive_command under jobs=2 increments failed_count');
+
+# Use the segment the archiver actually failed on, not the pre-switch LSN.
+my $segment_name = $node->safe_psql('postgres',
+ q{SELECT last_failed_wal FROM pg_stat_archiver});
+ok($segment_name ne '', 'last_failed_wal reported after failure');
+my $segment_ready =
+ $node->data_dir . "/pg_wal/archive_status/$segment_name.ready";
+ok(-f $segment_ready, ".ready retained for $segment_name after failure");
+
+$node->safe_psql(
+ 'postgres', q{
+ ALTER SYSTEM RESET archive_command;
+ SELECT pg_reload_conf();
+});
+$before = archived_count();
+switch_wal(12);
+wait_archived_gt($before, 'archival recovers after good archive_command');
+{
+ my $cleared = 0;
+ for (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default)
+ {
+ if (!-f $segment_ready)
+ {
+ $cleared = 1;
+ last;
+ }
+ usleep(100_000);
+ }
+ ok($cleared, ".ready cleared for $segment_name after recovery");
+}
+
+# Concurrent hang jobs and shutdown cancel.
+my $hang = $node->basedir . '/hang_archive.sh';
+my $hang_log = $node->basedir . '/hang_archive.log';
+my $good_cmd = 'cp "%p" "' . $node->archive_dir . '/%f"';
+append_to_file(
+ $hang, qq{#!/bin/sh
+echo \$\$ >>'$hang_log'
+sleep 1000
+});
+chmod 0755, $hang or die "chmod $hang: $!";
+
+unlink $hang_log if -f $hang_log;
+reload_jobs(3, qq{archive_command = '$hang "%p" "%f"'\n});
+switch_wal(2);
+switch_wal(3);
+my @hang_pids = wait_for_hang_pids($hang_log, 2);
+cmp_ok(scalar(@hang_pids), '>=', 2, 'two archive_command jobs ran concurrently');
+
+reload_jobs(2, qq{archive_command = '$good_cmd'\n});
+ok(!kill(0, $_), "hang archive pid $_ gone after reload") for @hang_pids;
+$before = archived_count();
+switch_wal(13);
+wait_archived_gt($before, 'archiving drains after restoring good archive_command');
+
+unlink $hang_log if -f $hang_log;
+reload_jobs(3, qq{archive_command = '$hang "%p" "%f"'\n});
+switch_wal(4);
+switch_wal(5);
+@hang_pids = wait_for_hang_pids($hang_log, 2);
+cmp_ok(scalar(@hang_pids), '>=', 2, 'two hang archive_command jobs before stop');
+
+my $offset = -s $node->logfile;
+# Allow headroom past PGARCH_ASYNC_STOP_GRACE_S.
+ok($node->stop('fast', timeout => 120),
+ 'stop with hung archive_command jobs');
+like(
+ slurp_file($node->logfile, $offset),
+ qr/canceling in flight archive commands due to shutdown/,
+ 'shutdown canceled in flight archive commands after hung job grace');
+ok(!kill(0, $_), "hang archive pid $_ gone after stop") for @hang_pids;
+
+done_testing();
--
2.56.0
#!/bin/bash
# Time archive_command_jobs clearing a WAL backlog.
#
# Usage: PGBIN=/path/to/bin ./archive_jobs_bench.sh [rounds] [points]
# rounds default 3
# points delay_ms/jobs list, default "500/1 500/2 500/4 500/8"
# Env: PGBIN WORKDIR KEEP FILES PORT
set -eu -o pipefail
rounds=${1:-3}
if [ $# -ge 2 ]; then
shift
points="$*"
else
points="500/1 500/2 500/4 500/8"
fi
FILES=${FILES:-16}
PORT=${PORT:-56789}
if [ -n "${PGBIN:-}" ]; then export PATH=$PGBIN:$PATH; fi
for b in initdb pg_ctl postgres psql; do
command -v $b >/dev/null || { echo "$b not found (set PGBIN)" >&2; exit 1; }
done
if [ -n "${WORKDIR:-}" ]; then
R=$WORKDIR
mkdir -p "$R"
else
R=$(mktemp -d "$PWD/archjobs.XXXXXX")
fi
S=$R/sock
A=$R/archive
mkdir -p "$S" "$A"
export PGOPTIONS="-c client_min_messages=warning"
q() { psql -X -q -At -h "$S" -p "$PORT" -d postgres -v ON_ERROR_STOP=1 "$@"; }
stop() {
pg_ctl -D "$R/data" -m immediate stop >/dev/null 2>&1 || true
if [ "${KEEP:-0}" = 1 ]; then echo "# kept $R"; else rm -rf "$R"; fi
}
trap stop EXIT
cat >"$R/arch.sh" <<'EOF'
#!/bin/bash
set -eu
DELAY=$1; DEST=$2; SRC=$3; NAME=$4
if [ "$DELAY" != 0 ] && [ "$DELAY" != 0.0 ]; then sleep "$DELAY"; fi
exec cp -- "$SRC" "$DEST/$NAME"
EOF
chmod +x "$R/arch.sh"
initdb -A trust -N -D "$R/data" >/dev/null
cat >>"$R/data/postgresql.conf" <<EOF
port = $PORT
unix_socket_directories = '$S'
listen_addresses = ''
archive_mode = on
archive_command = ''
archive_command_jobs = 1
wal_level = replica
max_wal_senders = 0
fsync = off
synchronous_commit = off
full_page_writes = off
autovacuum = off
EOF
pg_ctl -D "$R/data" -l "$R/pg.log" -w start >/dev/null
if ! q -c 'SHOW archive_command_jobs' >/dev/null 2>&1; then
echo "server lacks archive_command_jobs (wrong PGBIN?)" >&2; exit 1
fi
q -c 'CREATE TABLE t(i int)'
echo "# $(postgres --version); $(nproc) CPUs; rounds=$rounds FILES=$FILES"
echo "# workdir $R"
drain() {
local delay_ms=$1 jobs=$2
local delay_sec before want t0 t1 failed n
delay_sec=$(awk -v m="$delay_ms" 'BEGIN { printf "%.3f", m / 1000 }')
q -c "ALTER SYSTEM SET archive_command TO ''"
q -c "SELECT pg_reload_conf()" >/dev/null
sleep 0.1
rm -f "$A"/*
before=$(q -c 'SELECT archived_count FROM pg_stat_archiver')
n=0
while [ "$n" -lt "$FILES" ]; do
q -c 'INSERT INTO t VALUES (1); SELECT pg_switch_wal()' >/dev/null
n=$((n + 1))
done
q -c "ALTER SYSTEM SET archive_command TO \$\$$R/arch.sh $delay_sec $A %p %f\$\$"
q -c "ALTER SYSTEM SET archive_command_jobs TO $jobs"
q -c "SELECT pg_reload_conf()" >/dev/null
until [ "$(q -c "SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'archiver'")" = 1 ]
do sleep 0.05; done
want=$((before + FILES))
t0=$(date +%s.%N)
while :; do
if [ "$(q -c 'SELECT archived_count FROM pg_stat_archiver')" -ge "$want" ]; then
break
fi
failed=$(q -c 'SELECT failed_count FROM pg_stat_archiver')
if [ "$failed" -gt 0 ]; then
echo "drain failed (failed_count=$failed). See $R/pg.log" >&2
exit 1
fi
sleep 0.05
done
t1=$(date +%s.%N)
awk -v r="$round" -v d="$delay_ms" -v j="$jobs" -v a="$t0" -v b="$t1" -v n="$FILES" 'BEGIN {
printf "DRAIN round=%d delay_ms=%d jobs=%d files=%d secs=%.3f files_per_s=%.2f\n",
r, d, j, n, b - a, n / (b - a) }'
}
pts=($points)
out=$R/drains.txt
: >"$out"
for round in $(seq "$rounds"); do
order=("${pts[@]}")
if [ $((round % 2)) = 0 ]; then
order=()
for ((i = ${#pts[@]} - 1; i >= 0; i--)); do order+=("${pts[$i]}"); done
fi
for pt in "${order[@]}"; do
delay_ms=${pt%%/*}
jobs=${pt##*/}
drain "$delay_ms" "$jobs" | tee -a "$out"
done
done
echo "# summary"
python3 - "$out" <<'PY'
import sys
from collections import defaultdict
from statistics import median
rows = defaultdict(list)
for line in open(sys.argv[1]):
if not line.startswith('DRAIN'):
continue
parts = dict(p.split('=', 1) for p in line.split()[1:])
key = (int(parts['delay_ms']), int(parts['jobs']))
rows[key].append(float(parts['secs']))
for delay, jobs in sorted(rows):
vals = rows[(delay, jobs)]
med = median(vals)
base_vals = rows.get((delay, 1))
if base_vals and med > 0:
speedup = f'{median(base_vals) / med:.2f}x'
else:
speedup = 'n/a'
print(
f'delay_ms={delay} jobs={jobs} '
f'median={med:.3f}s n={len(vals)} vs jobs=1={speedup}'
)
PY