From ed036ea6fea2b5637722530ba3ff36c2596c8ca3 Mon Sep 17 00:00:00 2001
From: Matthias van de Meent <boekewurm+postgres@gmail.com>
Date: Mon, 27 Jul 2026 15:48:32 +0200
Subject: [PATCH v1] Prevent ERRORs in exit handling from causing shmem
 corruption

Shmem shutdown hooks can raise errors before they finish from detaching
the process from the shared memory segments they're responsible for.
This leaves the shmem components in a broken state, which no other
process is expected to be able to fix.  To avoid leaving shmem in such
a corrupted state, we need to increase the level of shmem exit's ERRORs
to PANIC.
---
 src/backend/utils/error/elog.c | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/backend/utils/error/elog.c b/src/backend/utils/error/elog.c
index b9d2c96b97a..2650852d455 100644
--- a/src/backend/utils/error/elog.c
+++ b/src/backend/utils/error/elog.c
@@ -383,6 +383,11 @@ errstart(int elevel, const char *domain)
 		 * 3. the error occurred after proc_exit has begun to run.  (It's
 		 * proc_exit's responsibility to see that this doesn't turn into
 		 * infinite recursion!)
+		 *
+		 * When handling shmem exit callbacks, even FATAL is insufficient:
+		 * if a subsystem is only partially detached we're likely to leak
+		 * memory or otherwise leave shmem in a corrupted state.  In that
+		 * case, we promote the ERROR all the way to PANIC.
 		 */
 		if (elevel == ERROR)
 		{
@@ -390,6 +395,9 @@ errstart(int elevel, const char *domain)
 				ExitOnAnyError ||
 				proc_exit_inprogress)
 				elevel = FATAL;
+
+			if (proc_exit_inprogress && shmem_exit_inprogress)
+				elevel = PANIC;
 		}
 
 		/*
-- 
2.50.1 (Apple Git-155)

