pg.ddx.io pgsql-hackers@postgresql.org mailing list archivehelp / color / mirror / Atom feed
Postmaster fails to shut down right after crash restart 3+ messages / 2 participants [nested] [flat]
* Postmaster fails to shut down right after crash restart @ 2025-04-24 12:06 Sergey Shinderuk <s.shinderuk@postgrespro.ru> 2026-09-03 12:46 ` Re: Postmaster fails to shut down right after crash restart Andrey Borodin <x4mmm@yandex-team.ru> 0 siblings, 1 reply; 3+ messages in thread From: Sergey Shinderuk @ 2025-04-24 12:06 UTC (permalink / raw) To: pgsql-hackers Hello, While developing a patch and running regression tests I noticed that the postmaster could fail to shut down right after crash restart. It could get stuck in the PM_WAIT_BACKENDS state forever. As far as I understand, the problem occurs when a shutdown signal is received before getting PMSIGNAL_RECOVERY_STARTED from the startup process. In that case the FatalError flag is not cleared, and the postmaster is stuck in PM_WAIT_BACKENDS waiting for the checkpointer, which ignores SIGTERM. To easily reproduce the problem I added pg_usleep in xlogrecovery.c just before SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED). See the patch attached. Then I run a script that simulates a crash and does pg_ctl stop: $ ./init.sh [...] $ ./stop-after-crash.sh waiting for server to start.... done server started waiting for server to shut down............................................................... failed pg_ctl: server does not shut down Some processes are still alive: $ ps uf -C postgres USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND sergey 279874 0.0 0.0 222816 28560 ? Ss 14:25 0:00 /home/sergey/pgwork/devel/install/bin/postgres -D data sergey 279887 0.0 0.0 222772 5664 ? Ss 14:25 0:00 \_ postgres: io worker 0 sergey 279888 0.0 0.0 222772 5664 ? Ss 14:25 0:00 \_ postgres: io worker 1 sergey 279889 0.0 0.0 222772 5664 ? Ss 14:25 0:00 \_ postgres: io worker 2 sergey 279891 0.0 0.0 222884 8480 ? Ss 14:25 0:00 \_ postgres: checkpointer Here is an excerpt from the debug log: postmaster[279874] LOG: all server processes terminated; reinitializing startup[279890] LOG: database system was interrupted; last known up at 2025-04-24 14:25:58 MSK startup[279890] LOG: database system was not properly shut down; automatic recovery in progress postmaster[279874] DEBUG: postmaster received shutdown request signal postmaster[279874] LOG: received fast shutdown request postmaster[279874] DEBUG: updating PMState from PM_STARTUP to PM_STOP_BACKENDS postmaster[279874] DEBUG: sending signal 15/SIGTERM to background writer process with pid 279892 postmaster[279874] DEBUG: sending signal 15/SIGTERM to checkpointer process with pid 279891 postmaster[279874] DEBUG: sending signal 15/SIGTERM to startup process with pid 279890 postmaster[279874] DEBUG: sending signal 15/SIGTERM to io worker process with pid 279889 postmaster[279874] DEBUG: sending signal 15/SIGTERM to io worker process with pid 279888 postmaster[279874] DEBUG: sending signal 15/SIGTERM to io worker process with pid 279887 postmaster[279874] DEBUG: updating PMState from PM_STOP_BACKENDS to PM_WAIT_BACKENDS startup[279890] LOG: invalid record length at 0/175A4D8: expected at least 24, got 0 postmaster[279874] DEBUG: postmaster received pmsignal signal startup[279890] LOG: redo is not required checkpointer[279891] LOG: checkpoint starting: end-of-recovery immediate wait checkpointer[279891] LOG: checkpoint complete: wrote 0 buffers (0.0%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.007 s, sync=0.002 s, total=0.026 s; sync files=2, longest=0.001 s, average=0.001 s; distance=0 kB, estimate=0 kB; lsn=0/175A4D8, redo lsn=0/175A4D8 startup[279890] DEBUG: exit(0) postmaster[279874] DEBUG: updating PMState from PM_WAIT_BACKENDS to PM_WAIT_BACKENDS checkpointer[279891] DEBUG: checkpoint skipped because system is idle checkpointer[279891] DEBUG: checkpoint skipped because system is idle I don't know how to fix this, but thought it's worth reporting. Best regards, -- Sergey Shinderuk https://postgrespro.com/ Attachments:init.sh (application/x-shellscript, 135B) download stop-after-crash.sh (application/x-shellscript, 172B) download logfile.gz (application/gzip, 2.7K) download ^ permalink raw reply [nested|flat] 3+ messages in threaddelay-recovery-started.patch (text/x-patch, 504B) download
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c index 6ce979f2d8b..19ee8b09685 100644 --- a/src/backend/access/transam/xlogrecovery.c +++ b/src/backend/access/transam/xlogrecovery.c @@ -1696,7 +1696,10 @@ PerformWalRecovery(void) * archiver if necessary. */ if (IsUnderPostmaster) + { + pg_usleep(3000000); SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED); + } /* * Allow read-only connections immediately if we're consistent already.
* Re: Postmaster fails to shut down right after crash restart 2025-04-24 12:06 Postmaster fails to shut down right after crash restart Sergey Shinderuk <s.shinderuk@postgrespro.ru> @ 2026-09-03 12:46 ` Andrey Borodin <x4mmm@yandex-team.ru> 2026-09-03 18:08 ` Re: Postmaster fails to shut down right after crash restart Andrey Borodin <x4mmm@yandex-team.ru> 0 siblings, 1 reply; 3+ messages in thread From: Andrey Borodin @ 2026-09-03 12:46 UTC (permalink / raw) To: Sergey Shinderuk <s.shinderuk@postgrespro.ru>; Michael Paquier <michael@paquier.xyz>; +Cc: pgsql-hackers > On 24 Apr 2025, at 17:06, Sergey Shinderuk <s.shinderuk@postgrespro.ru> wrote: > > the postmaster could fail to shut down right after crash restart. It could get stuck in the PM_WAIT_BACKENDS state forever. Hi Sergey, I looked at this and reproduced it on current master. Your diagnosis looks correct: if a smart or fast shutdown request arrives during crash-restart reinitialization, before PMSIGNAL_RECOVERY_STARTED, FatalError remains set. The normal shutdown path then sends SIGTERM to the processes started for crash recovery and waits in PM_WAIT_BACKENDS, but the checkpointer ignores SIGTERM. PFA a three-patch series: 1. Allow wait injection points to be controlled through files under pg_injection_points/ in the data directory. 2. Add a deterministic test for this bug, covering both smart and fast shutdown. 3. Fix the shutdown path. Michael, this looks like the concrete test case that was missing from our July discussion [0]. The test needs all three operations you listed without relying on SQL: request attachment before triggering crash restart so that the point is installed in the replacement shared memory, observe that the startup process has reached it, and release that process after the postmaster has handled the shutdown request. Patch 0001 implements the filesystem approach you suggested. Creating pg_injection_points/<point>/ causes the wait point to be attached when shared memory is initialized. A process waiting there publishes pg_injection_points/<point>/<pid> and removing that file releases the process. The directories are rescanned when shared memory is recreated after a crash, so the wait point survives the exact reset that makes the SQL interface unusable here. Wait points attached only through SQL do not create filesystem state. With patches 0001 and 0002, the test reproduces the hang. Patch 0003 handles a shutdown request received with FatalError set by using HandleFatalError(PMQUIT_FOR_STOP, false). That sends the crash-recovery children SIGQUIT instead of waiting for them after SIGTERM. There is no graceful shutdown checkpoint to perform in the middle of crash recovery; the next startup will run recovery again. The filesystem interface for wait injection points is intended for HEAD. The fix itself is independent and looks suitable for backpatching. Thoughts? Thank you! Best regards, Andrey Borodin. [0] https://www.postgresql.org/message-id/flat/aher0VsjJ8xeNgLq%40paquier.xyz Attachments: download all (3 files, .tar.gz)v1-0001-injection_points-allow-driving-wait-points-throug.patch (application/octet-stream, 21.3K) download
From 3597fe89d2c805d0ec7541b740f9504c69166b49 Mon Sep 17 00:00:00 2001 From: Andrey Borodin <amborodin@acm.org> Date: Tue, 1 Sep 2026 23:58:07 +0500 Subject: [PATCH v1 1/3] injection_points: allow driving wait points through the filesystem Add a filesystem-based way to attach a wait point and to release a specific waiter, for code paths that run before the server can answer SQL -- most importantly early postmaster startup and crash-restart reinitialization, where no backend connection exists and shared memory has just been reset (so a point attached through SQL would be gone). It works alongside the existing SQL path and does not touch the core injection-point registry. State lives under pg_injection_points/ in the data directory: pg_injection_points/<point>/ present -> <point> attached as a wait pg_injection_points/<point>/<pid> present -> that process is parked here The module's shared-memory init callback scans this directory and attaches each subdirectory as a wait point. That callback runs in the postmaster every time shared memory is (re)created, at initial startup and after a crash restart. A directory created before either initialization therefore causes its point to be attached in the new shared-memory instance. A process reaching the point publishes its <pid> file and polls with stat() until it is removed, besides watching the wakeup counter; removing the file releases that one process, and listing the directory shows which processes are blocked. The tree is dropped when the cluster goes away. Everything is plain filesystem state, so there is no platform-specific logic and no out-of-process access to shared memory. Care is taken to keep the markers trustworthy: the waiter file is removed from the wait's error-cleanup callback, so an interrupted or cancelled waiter leaves nothing behind, and the preload scan clears any waiter file left by a process that was killed without running that cleanup -- it runs in the postmaster before any child is (re)forked, so a marker found then is stale by definition and must not be mistaken for a freshly parked waiter. Failure to create a marker is an error rather than a silent downgrade, and only the file actually disappearing (ENOENT) counts as a release, so a wait cannot end for a spurious reason. A point name becomes a path component, so only names built from a portable, separator-free character set publish markers; other names still work as plain SQL-driven wait points. The shutdown-time cleanup is registered only once even though the init callback runs again on each crash restart. --- src/test/modules/injection_points/Makefile | 2 + .../injection_points/injection_points.c | 309 +++++++++++++++++- src/test/modules/injection_points/meson.build | 8 + .../t/001_wait_without_sql.pl | 128 ++++++++ 4 files changed, 441 insertions(+), 6 deletions(-) create mode 100644 src/test/modules/injection_points/t/001_wait_without_sql.pl diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile index 3b136adf126..f163b6df929 100644 --- a/src/test/modules/injection_points/Makefile +++ b/src/test/modules/injection_points/Makefile @@ -27,6 +27,8 @@ ISOLATION = basic \ # some isolation tests require wal_level=replica ISOLATION_OPTS = --temp-config $(top_srcdir)/src/test/modules/injection_points/extra.conf +TAP_TESTS = 1 + # The injection points are cluster-wide, so disable installcheck NO_INSTALLCHECK = 1 diff --git a/src/test/modules/injection_points/injection_points.c b/src/test/modules/injection_points/injection_points.c index 66d8158d0c2..1ade892cf66 100644 --- a/src/test/modules/injection_points/injection_points.c +++ b/src/test/modules/injection_points/injection_points.c @@ -17,6 +17,10 @@ #include "postgres.h" +#include <fcntl.h> +#include <sys/stat.h> + +#include "common/file_utils.h" #include "fmgr.h" #include "funcapi.h" #include "injection_points.h" @@ -24,6 +28,7 @@ #include "nodes/pg_list.h" #include "nodes/value.h" #include "storage/dsm_registry.h" +#include "storage/fd.h" #include "storage/ipc.h" #include "storage/lwlock.h" #include "storage/shmem.h" @@ -45,6 +50,105 @@ PG_MODULE_MAGIC; #define INJ_WAIT_INITIAL_US 10 /* 10us */ #define INJ_WAIT_MAX_US 100000 /* 100ms */ +/* + * Filesystem markers used to drive wait points without any SQL connection, for + * code paths that run before the server can answer SQL (e.g. early postmaster + * startup). They live under a directory in the data directory, one + * subdirectory per attached point and one file per parked process: + * + * pg_injection_points/<point>/ present = <point> attached as a wait; + * pg_injection_points/<point>/<pid> present = that process is parked here. + * + * A test attaches a point by creating its directory (scanned at startup), sees + * who is waiting by listing the directory, and wakes a specific waiter by + * removing its PID file. Everything is plain filesystem state checked with + * stat(), so there is no platform-specific logic and no out-of-process access + * to shared memory. Paths are relative to the data directory, which is the + * working directory of the postmaster and every backend. + */ +#define INJ_POINTS_DIR "pg_injection_points" + +/* "pg_injection_points/<point>" */ +static void +injection_point_dir(char *buf, size_t bufsize, const char *name) +{ + snprintf(buf, bufsize, "%s/%s", INJ_POINTS_DIR, name); +} + +/* "pg_injection_points/<point>/<pid>" */ +static void +injection_point_waiter_path(char *buf, size_t bufsize, + const char *name, int pid) +{ + snprintf(buf, bufsize, "%s/%s/%d", INJ_POINTS_DIR, name, pid); +} + +/* + * A point's name becomes a path component under INJ_POINTS_DIR, so only names + * built from a portable, separator-free character set get a filesystem marker. + * Points with other names still work through the SQL wakeup path; they just do + * not publish a marker. This also bounds the name to a single path component. + */ +static bool +injection_point_name_is_fs_safe(const char *name) +{ + if (name[0] == '\0' || strlen(name) >= INJ_NAME_MAXLEN) + return false; + + for (const char *p = name; *p != '\0'; p++) + { + if (!((*p >= 'A' && *p <= 'Z') || + (*p >= 'a' && *p <= 'z') || + (*p >= '0' && *p <= '9') || + *p == '_' || *p == '-')) + return false; + } + return true; +} + +/* + * Remove any leftover "<pid>" waiter files from a point directory. Called from + * the preload scan, which runs in the postmaster before any child is (re)forked, + * so this clears markers left by processes that were killed without running + * their cleanup - most importantly across a crash-and-restart cycle, where the + * directory is deliberately kept. Without this an out-of-process controller + * could mistake a dead process's marker for a freshly parked waiter. + */ +static void +injection_points_clear_waiters(const char *dirpath) +{ + DIR *dir; + struct dirent *de; + + dir = AllocateDir(dirpath); + if (dir == NULL) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open directory \"%s\": %m", dirpath))); + + while ((de = ReadDir(dir, dirpath)) != NULL) + { + char path[MAXPGPATH]; + const char *p; + + /* Waiter files are named after a PID, i.e. all digits. */ + for (p = de->d_name; *p != '\0'; p++) + { + if (*p < '0' || *p > '9') + break; + } + if (p == de->d_name || *p != '\0') + continue; + + snprintf(path, sizeof(path), "%s/%s", dirpath, de->d_name); + if (unlink(path) != 0 && errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not remove file \"%s\": %m", path))); + } + FreeDir(dir); +} + /* * List of injection points stored in TopMemoryContext attached * locally to this process. @@ -85,6 +189,15 @@ extern PGDLLEXPORT void injection_wait(const char *name, /* track if injection points attached in this process are linked to it */ static bool injection_point_local = false; +/* + * Path of the filesystem marker this process published for a wait point (see + * injection_wait()), so the wait's cleanup callback can remove it on error or + * interrupt as well as on a normal wakeup. A process waits at one point at a + * time, so a single slot is enough. + */ +static char injection_waiter_path[MAXPGPATH]; +static bool injection_have_waiter_file = false; + static void injection_shmem_request(void *arg); static void injection_shmem_init(void *arg); @@ -117,14 +230,117 @@ injection_shmem_request(void *arg) ); } +/* + * Scan INJ_POINTS_DIR for point subdirectories and attach each as a wait point. + * Called from the shared-memory init callback, which runs in the postmaster (or + * a standalone backend) each time shared memory is (re)created - at initial + * startup and again after a crash-and-restart cycle - so the points are in + * place before any child reaches them, all without an SQL connection. A point + * can therefore be attached, by creating its directory, before the server is + * even started, and it survives crash restart because it is re-read here. + */ +static void +injection_points_preload(void) +{ + DIR *dir; + struct dirent *de; + + dir = AllocateDir(INJ_POINTS_DIR); + if (dir == NULL) + { + if (errno == ENOENT) + return; /* no directory means nothing attached */ + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not open directory \"%s\": %m", + INJ_POINTS_DIR))); + } + + while ((de = ReadDir(dir, INJ_POINTS_DIR)) != NULL) + { + InjectionPointCondition condition = {.type = INJ_CONDITION_NONE}; + char path[MAXPGPATH]; + struct stat st; + + if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) + continue; + + /* + * Only names we would ourselves turn into a marker path are accepted, + * which also rejects anything that is not a single path component. + */ + if (!injection_point_name_is_fs_safe(de->d_name)) + continue; + + /* Each subdirectory names a wait point to attach. */ + injection_point_dir(path, sizeof(path), de->d_name); + if (stat(path, &st) != 0) + { + if (errno == ENOENT) + continue; + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not stat file \"%s\": %m", path))); + } + if (!S_ISDIR(st.st_mode)) + continue; + + /* + * Drop any stale waiter files before the replacement children run, so + * a marker left by a process killed without cleanup is not mistaken + * for a new waiter. + */ + injection_points_clear_waiters(path); + + InjectionPointAttach(de->d_name, "injection_points", "injection_wait", + &condition, sizeof(condition)); + } + FreeDir(dir); +} + +/* + * proc_exit callback that removes INJ_POINTS_DIR so markers do not survive the + * cluster. Forked children inherit this callback but must not run it, hence + * the IsUnderPostmaster guard: only the lifecycle owner (postmaster, or a + * standalone backend) cleans up. + */ +static void +injection_points_dir_cleanup(int code, Datum arg) +{ + struct stat st; + + if (!IsUnderPostmaster && stat(INJ_POINTS_DIR, &st) == 0) + (void) rmtree(INJ_POINTS_DIR, true); +} + static void injection_shmem_init(void *arg) { + static bool cleanup_registered = false; + /* * First time through, so initialize. This is shared with the dynamic * initialization using a DSM. */ injection_point_init_state(inj_state, NULL); + + /* + * Attach any wait points requested out of band through marker + * directories. + */ + injection_points_preload(); + + /* + * Make sure the marker directory does not outlive the cluster. This + * callback runs in the postmaster, which persists across crash restarts + * and calls us again each time, so register it only once to avoid + * exhausting the on_proc_exit slots. + */ + if (!cleanup_registered) + { + on_proc_exit(injection_points_dir_cleanup, 0); + cleanup_registered = true; + } } /* @@ -233,9 +449,20 @@ injection_wait_cleanup(int code, Datum arg) SpinLockAcquire(&inj_state->lock); inj_state->name[index][0] = '\0'; SpinLockRelease(&inj_state->lock); + + /* + * Remove our filesystem marker too. This runs both on the normal path + * and from PG_ENSURE_ERROR_CLEANUP on error or interrupt, so a parked + * process that gets cancelled does not leave a stale <pid> file behind. + */ + if (injection_have_waiter_file) + { + (void) unlink(injection_waiter_path); + injection_have_waiter_file = false; + } } -/* Wait until injection_points_wakeup() is called */ +/* Wait until released by injection_points_wakeup() or a removed marker file */ void injection_wait(const char *name, const void *private_data, void *arg) { @@ -245,6 +472,7 @@ injection_wait(const char *name, const void *private_data, void *arg) const InjectionPointCondition *condition = private_data; char *argstr = arg; int delay_us = 0; + struct stat st; if (inj_state == NULL) injection_init_shmem(); @@ -280,18 +508,84 @@ injection_wait(const char *name, const void *private_data, void *arg) name); /* - * Wait until the counter is bumped by injection_points_wakeup(). + * Set up the wait. Register the error-cleanup callback first, then + * publish our presence and loop, so that a failure while creating the + * marker still releases the shared-memory slot and removes any file we + * managed to create. * - * This loop starts with a short delay for responsiveness, enlarged to - * ease the CPU workload in slower environments. + * The loop starts with a short delay for responsiveness, enlarged to ease + * the CPU workload in slower environments. */ delay_us = INJ_WAIT_INITIAL_US; pgstat_report_wait_start(injection_wait_event); PG_ENSURE_ERROR_CLEANUP(injection_wait_cleanup, Int32GetDatum(index)); { - while (pg_atomic_read_u32(&inj_state->wait_counts[index]) == old_wait_counts) + /* + * If this point was attached through the filesystem, publish our + * presence there so an out-of-process test can see that we are parked + * here and release us with no SQL connection. The point directory must + * have been created by the controller: a point attached only through SQL + * must not leave a directory that would reattach it after a crash + * restart. + */ + if (injection_point_name_is_fs_safe(name)) + { + char dirpath[MAXPGPATH]; + struct stat dirst; + + injection_point_dir(dirpath, sizeof(dirpath), name); + if (stat(dirpath, &dirst) != 0) + { + if (errno != ENOENT) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not stat file \"%s\": %m", dirpath))); + } + else if (S_ISDIR(dirst.st_mode)) + { + int fd; + + injection_point_waiter_path(injection_waiter_path, + sizeof(injection_waiter_path), name, + MyProcPid); + fd = OpenTransientFile(injection_waiter_path, + O_RDWR | O_CREAT | O_TRUNC); + if (fd < 0) + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not create file \"%s\": %m", + injection_waiter_path))); + CloseTransientFile(fd); + injection_have_waiter_file = true; + } + } + + /* + * Wait until released, either by injection_points_wakeup() bumping + * the counter or by our waiter file being removed. Only the file + * actually disappearing (ENOENT) counts as a release; any other + * stat() failure is unexpected and raised, so the wait cannot end for + * a spurious reason. + */ + for (;;) { + if (pg_atomic_read_u32(&inj_state->wait_counts[index]) != old_wait_counts) + break; + + if (injection_have_waiter_file) + { + if (stat(injection_waiter_path, &st) != 0) + { + if (errno == ENOENT) + break; + ereport(ERROR, + (errcode_for_file_access(), + errmsg("could not stat file \"%s\": %m", + injection_waiter_path))); + } + } + CHECK_FOR_INTERRUPTS(); pg_usleep(delay_us); if (delay_us < INJ_WAIT_MAX_US) @@ -301,7 +595,10 @@ injection_wait(const char *name, const void *private_data, void *arg) PG_END_ENSURE_ERROR_CLEANUP(injection_wait_cleanup, Int32GetDatum(index)); pgstat_report_wait_end(); - /* Remove this injection point from the waiters. */ + /* + * Remove this injection point from the waiters. This also unlinks our + * filesystem marker, which may still exist after a counter wakeup. + */ injection_wait_cleanup(0, Int32GetDatum(index)); } diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index aff516b901a..6ff4dcbc00f 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -63,4 +63,12 @@ tests += { '--temp-config', files('extra.conf'), ], }, + 'tap': { + 'env': { + 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no', + }, + 'tests': [ + 't/001_wait_without_sql.pl', + ], + }, } diff --git a/src/test/modules/injection_points/t/001_wait_without_sql.pl b/src/test/modules/injection_points/t/001_wait_without_sql.pl new file mode 100644 index 00000000000..5c042f9b025 --- /dev/null +++ b/src/test/modules/injection_points/t/001_wait_without_sql.pl @@ -0,0 +1,128 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Exercise driving a wait injection point purely through the filesystem, with +# no SQL used for the coordination itself. This is meant for code paths that +# run before the server can answer queries (e.g. early postmaster startup). +# +# Layout under the data directory: +# pg_injection_points/<point>/ present -> <point> attached as a wait +# pg_injection_points/<point>/<pid> present -> that backend is parked here +# Removing the <pid> file wakes that backend. + +use strict; +use warnings FATAL => 'all'; + +use Time::HiRes qw(usleep); + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +if ($ENV{enable_injection_points} ne 'yes') +{ + plan skip_all => 'Injection points not supported by this build'; +} + +my $point = 'no-sql-wait'; + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', + "shared_preload_libraries = 'injection_points'"); + +# Attach the wait point before the server is even running, without any SQL: +# just create its directory. The module scans these at startup. +my $root = $node->data_dir . '/pg_injection_points'; +my $pdir = "$root/$point"; +mkdir $root or die "could not create $root: $!"; +mkdir $pdir or die "could not create $pdir: $!"; + +# Plant a stale waiter file, as a process killed without running its cleanup +# would leave behind. The startup scan must remove it, or it could be mistaken +# for a live waiter below. +my $stale = "$pdir/99999999"; +open(my $fh, '>', $stale) or die "could not create $stale: $!"; +close($fh); + +$node->start; + +ok(!-e $stale, 'stale waiter file removed by the startup scan'); + +# The module attached the point from its directory at startup; we never called +# injection_points_attach(). +$node->safe_psql('postgres', 'CREATE EXTENSION injection_points;'); + +my $listed = $node->safe_psql('postgres', + "SELECT count(*) FROM injection_points_list() WHERE point_name = '$point';" +); +is($listed, '1', 'wait point attached from its directory, without SQL'); + +# Fire the point in a background session; it must block in injection_wait(). +my $bg = $node->background_psql('postgres'); +$bg->query_until( + qr/start/, qq[ +\\echo start +SELECT injection_points_run('$point'); +]); + +# Detect that the backend is parked, purely through the filesystem: it +# publishes a file named after its PID inside the point directory. +my $waiter; +foreach my $i (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default) +{ + if (opendir(my $dh, $pdir)) + { + ($waiter) = grep { /^\d+\z/ } readdir($dh); + closedir($dh); + last if defined $waiter; + } + usleep(100_000); +} +if (!ok(defined $waiter, 'backend published its waiter file (filesystem-observable)')) +{ + # Nothing to release; the rest of the sequence would test something else. + # An immediate stop also unblocks the parked background session. + $node->stop('immediate'); + done_testing(); + exit; +} + +# Wake that specific backend without any SQL: remove its waiter file. +unlink "$pdir/$waiter" or die "could not remove waiter file: $!"; + +# The blocked statement now finishes, proving the filesystem wakeup worked. +like($bg->query_safe('SELECT 1;'), + qr/^1$/m, 'backend released by removing its waiter file, without SQL'); + +# A point attached only through SQL must not create filesystem state. In +# particular, leaving a point directory behind would reattach the point without +# its original conditions after a crash restart. +my $sql_point = 'sql-only-wait'; +$node->safe_psql('postgres', + "SELECT injection_points_attach('$sql_point', 'wait');"); +$bg->query_until( + qr/sql-start/, qq[ +\\echo sql-start +SELECT injection_points_run('$sql_point'); +]); +ok($node->poll_query_until( + 'postgres', + "SELECT count(*) = 1 FROM pg_stat_activity " + . "WHERE wait_event_type = 'InjectionPoint' " + . "AND wait_event = '$sql_point';"), + 'SQL-attached injection point reached its wait'); +ok(!-e "$root/$sql_point", + 'SQL-attached wait did not create filesystem control state'); +$node->safe_psql('postgres', + "SELECT injection_points_wakeup('$sql_point');"); +like($bg->query_safe('SELECT 1;'), qr/^1$/m, + 'SQL-attached wait released through SQL'); +$node->safe_psql('postgres', + "SELECT injection_points_detach('$sql_point');"); +$bg->quit; + +# The directory does not survive the cluster. +$node->stop; +ok(!-d $root, 'injection points directory removed at shutdown'); + +done_testing(); -- That's all, folks. May the source be with you. =v1-0002-Add-a-test-for-a-postmaster-shutdown-race-during-.patch (application/octet-stream, 9.5K) download
From 65878f600b243a3afd08a150c0813e612db31420 Mon Sep 17 00:00:00 2001 From: Andrey Borodin <amborodin@acm.org> Date: Tue, 1 Sep 2026 23:58:07 +0500 Subject: [PATCH v1 2/3] Add a test for a postmaster shutdown race during crash restart A fast or smart shutdown that arrives while the postmaster is still reinitializing after a crash -- FatalError set, before the startup process reports PMSIGNAL_RECOVERY_STARTED -- can leave the postmaster stuck in PM_WAIT_BACKENDS forever: the auxiliary processes relaunched for crash recovery are signalled with SIGTERM, but the checkpointer ignores SIGTERM, so the postmaster waits for a process that never exits. Reproducing this needs a deterministic pause just before the recovery-started signal is sent, released only after the shutdown request has been taken. That window cannot be controlled with ordinary SQL-based injection points: crash restart clears existing attachments and terminates the old backends, while new backends cannot execute SQL before the point under test. Use the filesystem control instead: create the point directory before triggering crash restart so the shared-memory initialization callback attaches it in the replacement shared memory, then release the parked startup process by removing its PID file. Add an injection point in PerformWalRecovery() just before SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED), and a TAP test that crashes an auxiliary process, waits for the replacement startup process to park at that point, requests a shutdown, and asserts the postmaster exits in bounded time. The scenario is run twice, once for a fast and once for a smart shutdown, since both go through the affected path. The test fails against the buggy state and passes once the postmaster is fixed; it cleans up a hung server on failure and uses pg_ctl to stay portable. --- src/backend/access/transam/xlogrecovery.c | 4 + src/test/modules/injection_points/meson.build | 1 + .../t/002_shutdown_after_crash_restart.pl | 162 ++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 src/test/modules/injection_points/t/002_shutdown_after_crash_restart.pl diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c index acac97e89d3..64fd763ccbb 100644 --- a/src/backend/access/transam/xlogrecovery.c +++ b/src/backend/access/transam/xlogrecovery.c @@ -63,6 +63,7 @@ #include "utils/fmgrprotos.h" #include "utils/guc.h" #include "utils/guc_hooks.h" +#include "utils/injection_point.h" #include "utils/pgstat_internal.h" #include "utils/pg_lsn.h" #include "utils/ps_status.h" @@ -1662,7 +1663,10 @@ PerformWalRecovery(void) * archiver if necessary. */ if (IsUnderPostmaster) + { + INJECTION_POINT("recovery-before-signal-recovery-started", NULL); SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED); + } /* * Allow read-only connections immediately if we're consistent already. diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build index 6ff4dcbc00f..9065704a56f 100644 --- a/src/test/modules/injection_points/meson.build +++ b/src/test/modules/injection_points/meson.build @@ -69,6 +69,7 @@ tests += { }, 'tests': [ 't/001_wait_without_sql.pl', + 't/002_shutdown_after_crash_restart.pl', ], }, } diff --git a/src/test/modules/injection_points/t/002_shutdown_after_crash_restart.pl b/src/test/modules/injection_points/t/002_shutdown_after_crash_restart.pl new file mode 100644 index 00000000000..f5cfd76c8a6 --- /dev/null +++ b/src/test/modules/injection_points/t/002_shutdown_after_crash_restart.pl @@ -0,0 +1,162 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Regression test for a postmaster shutdown race. A fast or smart shutdown +# that arrives while the postmaster is still reinitializing after a crash -- +# FatalError set, before the startup process reports +# PMSIGNAL_RECOVERY_STARTED -- used to hang forever in PM_WAIT_BACKENDS: the +# auxiliary processes relaunched for crash recovery only react to crash-style +# SIGQUIT, but the shutdown path signalled them with SIGTERM, which the +# checkpointer ignores. +# +# The bug lives in a window that ordinary SQL-based injection points cannot +# reach: +# +# * There is no SQL connection during crash-restart reinitialization, so the +# parked startup process cannot be released with injection_points_wakeup(). +# * The crash resets shared memory, so a point attached through SQL before +# the crash is gone by the time the replacement startup process runs. +# +# The filesystem control added to the injection_points module solves both: the +# marker directory is rescanned whenever shared memory is (re)created, so the +# point is attached in the replacement shared memory after the crash, and the +# parked process is released by removing its PID file. + +use strict; +use warnings FATAL => 'all'; + +use Errno; +use Time::HiRes qw(usleep); + +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +if ($ENV{enable_injection_points} ne 'yes') +{ + plan skip_all => 'Injection points not supported by this build'; +} + +my $point = 'recovery-before-signal-recovery-started'; + +# Both shutdown modes that used to hang go through the same buggy path, so run +# the same scenario for each: fast is SIGINT, smart is SIGTERM. +test_shutdown_during_crash_restart('fast', 'INT'); +test_shutdown_during_crash_restart('smart', 'TERM'); + +done_testing(); + +sub test_shutdown_during_crash_restart +{ + my ($mode, $signal) = @_; + + my $node = PostgreSQL::Test::Cluster->new("crash_shutdown_$mode"); + $node->init; + $node->append_conf('postgresql.conf', <<'EOF'); +shared_preload_libraries = 'injection_points' +restart_after_crash = on +EOF + + $node->start; + + # Request that the wait point be attached at the next shared-memory + # initialization, after the server has started but before triggering crash + # restart. The directory is therefore first seen while shared memory is + # being recreated, when no SQL connection exists. + my $inj_root = $node->data_dir . '/pg_injection_points'; + my $pdir = "$inj_root/$point"; + mkdir $inj_root or die "could not create $inj_root: $!"; + mkdir $pdir or die "could not create $pdir: $!"; + + # The postmaster survives crash restart, so this PID is stable for the + # rest of the scenario. + my $pidfile = $node->data_dir . '/postmaster.pid'; + my $pmpid = slurp_pid($pidfile); + ok($pmpid > 0, "$mode: obtained postmaster pid"); + + # Force a crash-and-restart cycle by SIGKILL'ing an auxiliary process. + # Killing the checkpointer needs no long-lived client connection kept + # alive, and routing the signal through "pg_ctl kill" keeps this portable + # to Windows. + my $ckpt = $node->safe_psql('postgres', + "SELECT pid FROM pg_stat_activity WHERE backend_type = 'checkpointer'" + ); + PostgreSQL::Test::Utils::system_or_bail('pg_ctl', 'kill', 'KILL', $ckpt); + + # Wait, through the filesystem only, until the replacement startup process + # is parked at the injection point just before PMSIGNAL_RECOVERY_STARTED. + # It publishes a file named after its PID inside the point directory. + my $waiter; + foreach my $i (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default) + { + if (opendir(my $dh, $pdir)) + { + ($waiter) = grep { /^\d+\z/ } readdir($dh); + closedir($dh); + last if defined $waiter; + } + usleep(100_000); + } + if (!ok(defined $waiter, + "$mode: startup process reached the pre-recovery-signal injection point" + )) + { + # Without a parked startup process the rest of the sequence would test + # a different scenario; end this one, leaving no server behind. + $node->stop('immediate', fail_ok => 1); + return; + } + + # Request the shutdown while the startup process is still parked. Send + # the signal asynchronously via pg_ctl kill, because a blocking pg_ctl + # stop would never return on the unfixed code. + my $logstart = -s $node->logfile; + PostgreSQL::Test::Utils::system_or_bail('pg_ctl', 'kill', $signal, + $pmpid); + + # Release the startup process strictly after the postmaster has taken the + # shutdown request. This ordering is what reproduces the bug: the + # postmaster handles the shutdown with FatalError still set, and only then + # does the startup process proceed to signal PMSIGNAL_RECOVERY_STARTED + # (which the postmaster now ignores because a shutdown is pending). + # Releasing earlier would let FatalError be cleared first, and the test + # could pass on buggy code. + $node->wait_for_log(qr/received $mode shutdown request/, $logstart); + if (!unlink("$pdir/$waiter") && !$!{ENOENT}) + { + die "could not remove waiter file: $!"; + } + + # The postmaster must now exit within a bounded time; it removes + # postmaster.pid as it goes. On the unfixed code it stays in + # PM_WAIT_BACKENDS forever, waiting on the SIGTERM-ignoring checkpointer, + # and the file remains. + my $stopped = 0; + foreach my $i (1 .. 10 * $PostgreSQL::Test::Utils::timeout_default) + { + if (!-f $pidfile) + { + $stopped = 1; + last; + } + usleep(100_000); + } + ok($stopped, + "$mode: postmaster shuts down when requested during crash restart"); + + # Never leave a hung server behind, even when the assertion above failed: + # an immediate shutdown SIGQUITs the children, which the checkpointer does + # honor. + $node->stop('immediate', fail_ok => 1); + return; +} + +# Read the first line (the PID) of a postmaster.pid file. +sub slurp_pid +{ + my ($path) = @_; + open(my $fh, '<', $path) or die "could not open $path: $!"; + my $line = <$fh>; + close($fh); + chomp $line if defined $line; + return defined $line ? $line + 0 : 0; +} -- That's all, folks. May the source be with you. =^ permalink raw reply [nested|flat] 3+ messages in threadv1-0003-Fix-postmaster-hang-on-shutdown-requested-during-.patch (application/octet-stream, 3.4K) download
From 7f07c21f247fa6d900c82ececb2a48f879ce5814 Mon Sep 17 00:00:00 2001 From: Andrey Borodin <amborodin@acm.org> Date: Tue, 1 Sep 2026 23:58:07 +0500 Subject: [PATCH v1 3/3] Fix postmaster hang on shutdown requested during crash restart If a smart or fast shutdown request arrives while the postmaster is still reinitializing after a crash -- that is, while FatalError is set and before the startup process has signalled PMSIGNAL_RECOVERY_STARTED -- then process_pm_shutdown_request() moved the state machine to PM_STOP_BACKENDS and signalled the children with SIGTERM. The checkpointer relaunched for crash recovery ignores SIGTERM, so the postmaster then waited for it in PM_WAIT_BACKENDS forever. There is no consistent state to preserve in the middle of crash recovery, so in that situation terminate the children the same crash-style way the postmaster already uses elsewhere, via HandleFatalError(), which sends SIGQUIT and heads for PM_WAIT_BACKENDS / PM_NO_CHILDREN. Immediate shutdown was already handled this way; this brings the smart and fast paths in line for the crash-restart window. This is distinct from commit ead8f696b7cd, which handles the startup process *crashing* during crash restart; here the startup process is healthy and the trigger is an incoming shutdown request. Reported-by: Sergey Shinderuk Discussion: https://postgr.es/m/63dcad16-22de-4326-a395-5310bc7e05ff@postgrespro.ru --- src/backend/postmaster/postmaster.c | 35 +++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 5f7a7b368e1..aaf8873c0e7 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -2156,8 +2156,16 @@ process_pm_shutdown_request(void) connsAllowed = false; else if (pmState == PM_STARTUP || pmState == PM_RECOVERY) { - /* There should be no clients, so proceed to stop children */ - UpdatePMState(PM_STOP_BACKENDS); + if (FatalError) + { + /* Crash recovery in progress; see the FastShutdown case */ + HandleFatalError(PMQUIT_FOR_STOP, false); + } + else + { + /* No clients, so proceed to stop children */ + UpdatePMState(PM_STOP_BACKENDS); + } } /* @@ -2190,8 +2198,27 @@ process_pm_shutdown_request(void) if (pmState == PM_STARTUP || pmState == PM_RECOVERY) { - /* Just shut down background processes silently */ - UpdatePMState(PM_STOP_BACKENDS); + if (FatalError) + { + /* + * We are reinitializing after a crash, and the shutdown + * request arrived before the startup process signalled + * PMSIGNAL_RECOVERY_STARTED, which is when FatalError + * would have been cleared. The auxiliary processes + * relaunched for crash recovery expect crash-style + * signalling: in particular the checkpointer ignores + * SIGTERM, so the regular PM_STOP_BACKENDS path would + * wait for it forever. There is no consistent state to + * save mid-recovery anyway, so terminate the children the + * same way the crash path does and head for exit. + */ + HandleFatalError(PMQUIT_FOR_STOP, false); + } + else + { + /* Just shut down background processes silently */ + UpdatePMState(PM_STOP_BACKENDS); + } } else if (pmState == PM_RUN || pmState == PM_HOT_STANDBY) -- That's all, folks. May the source be with you. =
* Re: Postmaster fails to shut down right after crash restart 2025-04-24 12:06 Postmaster fails to shut down right after crash restart Sergey Shinderuk <s.shinderuk@postgrespro.ru> 2026-09-03 12:46 ` Re: Postmaster fails to shut down right after crash restart Andrey Borodin <x4mmm@yandex-team.ru> @ 2026-09-03 18:08 ` Andrey Borodin <x4mmm@yandex-team.ru> 0 siblings, 0 replies; 3+ messages in thread From: Andrey Borodin @ 2026-09-03 18:08 UTC (permalink / raw) To: Sergey Shinderuk <s.shinderuk@postgrespro.ru>; Michael Paquier <michael@paquier.xyz>; +Cc: pgsql-hackers I found an older thread about the same bug[0]. Sorry I missed it before. Justin Pryzby reported it in December 2023. Thomas Munro reproduced it and identified the same window: FatalError is still set, the postmaster has not yet processed PMSIGNAL_RECOVERY_STARTED, and shutdown gets stuck waiting for the checkpointer. Thomas proposed a fix in that thread, and Noah Misch later reproduced the problem and suggested clearing FatalError when the replacement startup process is launched instead [1]. There is also an old CommitFest entry for Thomas's patch [2]. The deterministic test in patch 0002 covers that report as well. Patch 0003 takes a third approach that only became directly available recently. HandleFatalError() did not exist when Thomas posted his patch; after it was introduced, it asserted that FatalError was not already set. ead8f696b7cd removed that restriction. This lets 0003 retain FatalError during crash restart and handle a shutdown request in that interval through HandleFatalError(PMQUIT_FOR_STOP, false). The version from [2] perhaps is easier to backpatch to 15-17 if we want to backpatch. Best regards, Andrey Borodin. [0] https://www.postgresql.org/message-id/flat/ZWlrdQarrZvLsgIk%40pryzbyj2023 [1] https://www.postgresql.org/message-id/20241025181701.ed.nmisch%40google.com [2] https://commitfest.postgresql.org/patch/4884/ ^ permalink raw reply [nested|flat] 3+ messages in thread
end of thread, other threads:[~2026-09-03 18:08 UTC | newest] Thread overview: 3+ messages (download: mbox mbox.gz follow: Atom feed) -- links below jump to the message on this page -- 2025-04-24 12:06 Postmaster fails to shut down right after crash restart Sergey Shinderuk <s.shinderuk@postgrespro.ru> 2026-09-03 12:46 ` Andrey Borodin <x4mmm@yandex-team.ru> 2026-09-03 18:08 ` Andrey Borodin <x4mmm@yandex-team.ru>
This inbox is served by DDX for PostgreSQL; see mirroring instructions for how to clone and mirror all data and code used for this inbox