From 5daf4b5b761c2df7a1ca143a58b16241f8412c35 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 v5 4/4] Avoid adding backend context to repack worker messages

REPACK CONCURRENTLY propagates errors and notices from its decoding worker
to the backend through a shared-memory message queue.  ThrowErrorData
processes the backend's current error context stack when reporting such a
message.

The backend may be running with an error context that was established
after the decoding worker was launched, for example while evaluating an
index expression.  In that case, a message originating in the decoding
worker could acquire an unrelated and misleading CONTEXT line from the
backend.

Save the error context stack when launching the decoding worker and use
that stack while reporting messages received from it.  Restore the
backend's current stack afterward when reporting a notice returns
normally.
---
 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 1b1a8213358..ba83e3ce1ab 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. */
@@ -3889,6 +3892,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\"",
@@ -4283,6 +4289,7 @@ ProcessRepackMessage(StringInfo msg)
 		case PqMsg_NoticeResponse:
 			{
 				ErrorData	edata;
+				ErrorContextCallback *save_error_context_stack;
 
 				/* Parse ErrorResponse or NoticeResponse. */
 				pq_parse_errornotice(msg, &edata);
@@ -4301,9 +4308,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

