From e5848bc3f9de7becc2a5273ff0e0d4685f7905fa Mon Sep 17 00:00:00 2001
From: jcoleman <jtc331@gmail.com>
Date: Wed, 21 Jun 2023 14:31:44 -0400
Subject: [PATCH v2] Fix memory leak in incremental sort rescan

There are multiple issues here that this solves:
1. The sort states are incorrectly set to NULL during a rescan (despite
   the comment saying otherwise), and so we never end them.
2. presorted_keys is also incorrectly set to NULL during a rescan.
2. Because fullsort_state is improperly NULL we additionally call
   preparePresortedCols more than once, leaking memory there as well.
---
 src/backend/executor/nodeIncrementalSort.c | 7 -------
 1 file changed, 7 deletions(-)

diff --git a/src/backend/executor/nodeIncrementalSort.c b/src/backend/executor/nodeIncrementalSort.c
index 34257ce34b..7683e3341c 100644
--- a/src/backend/executor/nodeIncrementalSort.c
+++ b/src/backend/executor/nodeIncrementalSort.c
@@ -1140,7 +1140,6 @@ ExecReScanIncrementalSort(IncrementalSortState *node)
 	node->outerNodeDone = false;
 	node->n_fullsort_remaining = 0;
 	node->bound_Done = 0;
-	node->presorted_keys = NULL;
 
 	node->execution_status = INCSORT_LOADFULLSORT;
 
@@ -1153,15 +1152,9 @@ ExecReScanIncrementalSort(IncrementalSortState *node)
 	 * cause a leak.
 	 */
 	if (node->fullsort_state != NULL)
-	{
 		tuplesort_reset(node->fullsort_state);
-		node->fullsort_state = NULL;
-	}
 	if (node->prefixsort_state != NULL)
-	{
 		tuplesort_reset(node->prefixsort_state);
-		node->prefixsort_state = NULL;
-	}
 
 	/*
 	 * If chgParam of subnode is not null, then the plan will be re-scanned by
-- 
2.39.2 (Apple Git-143)

