From f33cd22ed65321d8fa554f58ed3b265e4854df6d Mon Sep 17 00:00:00 2001
From: Sami Imseih <simseih@amazon.com>
Date: Wed, 11 Sep 2024 14:40:58 -0500
Subject: [PATCH 1/1] Report new queryId after plancache re-validation

---
 src/backend/utils/cache/plancache.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/src/backend/utils/cache/plancache.c b/src/backend/utils/cache/plancache.c
index 5af1a168ec..4ed5e1eca1 100644
--- a/src/backend/utils/cache/plancache.c
+++ b/src/backend/utils/cache/plancache.c
@@ -66,6 +66,7 @@
 #include "storage/lmgr.h"
 #include "tcop/pquery.h"
 #include "tcop/utility.h"
+#include "utils/backend_status.h"
 #include "utils/inval.h"
 #include "utils/memutils.h"
 #include "utils/resowner.h"
@@ -590,6 +591,7 @@ RevalidateCachedQuery(CachedPlanSource *plansource,
 	TupleDesc	resultDesc;
 	MemoryContext querytree_context;
 	MemoryContext oldcxt;
+	ListCell	*lc;
 
 	/*
 	 * For one-shot plans, we do not support revalidation checking; it's
@@ -805,6 +807,22 @@ RevalidateCachedQuery(CachedPlanSource *plansource,
 
 	plansource->is_valid = true;
 
+	/*
+	 * Update the current queryId with the one from the re-validated
+	 * query tree, and only if it's a top-level queryId.
+	 */
+
+	foreach(lc, tlist)
+	{
+		Query *stmt = lfirst_node(Query, lc);
+
+		if (stmt->queryId != UINT64CONST(0))
+		{
+			pgstat_report_query_id(stmt->queryId, false);
+			break;
+		}
+	}
+
 	/* Return transient copy of querytrees for possible use in planning */
 	return tlist;
 }
-- 
2.39.3 (Apple Git-146)

