From 0da5963f0a66511a038b0a7e8f535e6a6a0a3f72 Mon Sep 17 00:00:00 2001
From: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Date: Wed, 7 Oct 2026 15:32:30 +0900
Subject: [PATCH v4 4/4] Preserve an error context before launching a repack
 worker

---
 src/backend/commands/repack.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a584e138ada..eb70e8f8c62 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -148,6 +148,9 @@ typedef struct DecodingWorker
 
 	/* Handle of the error queue. */
 	shm_mq_handle *error_mqh;
+
+	/* Error context stack in effect when the worker was started. */
+	ErrorContextCallback *error_context_stack;
 } DecodingWorker;
 
 /* Pointer to currently running decoding worker. */
@@ -3850,6 +3853,9 @@ start_repack_decoding_worker(Oid relid)
 
 	decoding_worker->error_mqh = shm_mq_attach(mq, decoding_worker->seg, NULL);
 
+	/* Preserve an error context stack */
+	decoding_worker->error_context_stack = error_context_stack;
+
 	memset(&bgw, 0, sizeof(bgw));
 	snprintf(bgw.bgw_name, BGW_MAXLEN,
 			 "REPACK decoding worker for relation \"%s\"",
@@ -4244,6 +4250,7 @@ ProcessRepackMessage(StringInfo msg)
 		case PqMsg_NoticeResponse:
 			{
 				ErrorData	edata;
+				ErrorContextCallback *save_error_context_stack;
 
 				/* Parse ErrorResponse or NoticeResponse. */
 				pq_parse_errornotice(msg, &edata);
@@ -4262,9 +4269,19 @@ ProcessRepackMessage(StringInfo msg)
 				else
 					edata.context = pstrdup(_("REPACK decoding worker"));
 
+				/*
+				 * Context beyond that should use the error context callbacks
+				 * that were in effect when the repack worker was launched, not
+				 * the current ones.
+				 */
+				save_error_context_stack = error_context_stack;
+				error_context_stack = decoding_worker->error_context_stack;
+
 				/* Rethrow error or print notice. */
 				ThrowErrorData(&edata);
 
+				/* Not an error, so restore previous context stack. */
+				error_context_stack = save_error_context_stack;
 				break;
 			}
 
-- 
2.52.0

