From b9483800eb9d8dc9bafb114c602c63d5cf596ee7 Mon Sep 17 00:00:00 2001
From: Alena Rybakina <a.rybakina@postgrespro.ru>
Date: Mon, 30 Oct 2023 14:22:21 +0300
Subject: [PATCH] Fix reject released path: we shouldn't only clean path, but
 we should delete all mentions ottherwice we will face the problem access to
 released memory.

---
 src/backend/optimizer/util/pathnode.c | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)

diff --git a/src/backend/optimizer/util/pathnode.c b/src/backend/optimizer/util/pathnode.c
index 0b1d17b9d33..4df9d34c9f1 100644
--- a/src/backend/optimizer/util/pathnode.c
+++ b/src/backend/optimizer/util/pathnode.c
@@ -619,7 +619,19 @@ add_path(RelOptInfo *parent_rel, Path *new_path)
 	{
 		/* Reject and recycle the new path */
 		if (!IsA(new_path, IndexPath))
-			pfree(new_path);
+		{
+			if(new_path == new_path->parent->cheapest_startup_path)
+				new_path->parent->cheapest_startup_path = NULL;
+			if(new_path == new_path->parent->cheapest_total_path)
+				new_path->parent->cheapest_total_path = NULL;
+			foreach(p1, new_path->parent->pathlist)
+			{
+				Path *path = (Path *) lfirst(p1);
+
+				if (path == new_path)
+					new_path->parent->pathlist = foreach_delete_current(new_path->parent->pathlist, p1);
+			}
+		}
 	}
 }
 
@@ -849,7 +861,17 @@ add_partial_path(RelOptInfo *parent_rel, Path *new_path)
 	else
 	{
 		/* Reject and recycle the new path */
-		pfree(new_path);
+		if(new_path == new_path->parent->cheapest_startup_path)
+			new_path->parent->cheapest_startup_path = NULL;
+		if(new_path == new_path->parent->cheapest_total_path)
+			new_path->parent->cheapest_total_path = NULL;
+		foreach(p1, new_path->parent->pathlist)
+		{
+			Path *path = (Path *) lfirst(p1);
+
+			if (path == new_path)
+				new_path->parent->pathlist = foreach_delete_current(new_path->parent->pathlist, p1);
+		}
 	}
 }
 
-- 
2.34.1

