From 7920501aea7877bcda762bf0cdd14b20b817eadb Mon Sep 17 00:00:00 2001
From: Satya Narlapuram <satyanarlapuram@gmail.com>
Date: Sat, 11 Apr 2026 03:35:06 +0000
Subject: [PATCH] Add check_stack_depth() to GRAPH_TABLE rewriter recursive
 functions

generate_setop_from_pathqueries() builds a right-recursive UNION ALL tree
with recursion depth equal to the number of valid path queries. Similarly,
generate_queries_for_path_pattern_recurse() recurses once per path factor
position to enumerate path combinations. Neither function called
check_stack_depth().

Add check_stack_depth() to both functions so that excessive recursion is
caught cleanly with an ERROR rather than a server crash.
---
 src/backend/rewrite/rewriteGraphTable.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/rewrite/rewriteGraphTable.c b/src/backend/rewrite/rewriteGraphTable.c
index 2c3199d3..429ef1cf 100644
--- a/src/backend/rewrite/rewriteGraphTable.c
+++ b/src/backend/rewrite/rewriteGraphTable.c
@@ -17,6 +17,7 @@
 #include "access/sysattr.h"
 #include "access/table.h"
 #include "access/htup_details.h"
+#include "miscadmin.h"
 #include "catalog/pg_operator.h"
 #include "catalog/pg_propgraph_element.h"
 #include "catalog/pg_propgraph_element_label.h"
@@ -361,6 +362,9 @@ generate_queries_for_path_pattern_recurse(RangeTblEntry *rte, List *pathqueries,
 {
 	List	   *path_elems = list_nth_node(List, path_elem_lists, elempos);
 
+	/* Guard against stack overflow due to complex path patterns. */
+	check_stack_depth();
+
 	foreach_ptr(struct path_element, pe, path_elems)
 	{
 		/* Update current path being built with current element. */
@@ -698,6 +702,9 @@ generate_setop_from_pathqueries(List *pathqueries, List **rtable, List **targetl
 	List	   *rtargetlist;
 	ParseNamespaceItem *pni;
 
+	/* Guard against stack overflow due to many path queries. */
+	check_stack_depth();
+
 	/* Recursion termination condition. */
 	if (list_length(pathqueries) == 0)
 	{
-- 
2.43.0

