From 624f085275af2e989cf144ed09a4fda8effe31ef Mon Sep 17 00:00:00 2001
From: zibuyu <zibuyu423@gmail.com>
Date: Thu, 3 Dec 2026 22:34:11 +0800
Subject: [PATCH] Reuse simplification for interleaved index expressions

Keep two expression sets per relation and sample comparisons after a run of misses. This also covers alternating keys while limiting the cost of deep comparisons for tables with mostly distinct expression indexes.
---
 src/backend/optimizer/util/plancat.c    | 93 +++++++++++++++++--------
 src/test/regress/expected/predicate.out |  1 +
 src/test/regress/sql/predicate.sql      |  1 +
 src/tools/pgindent/typedefs.list        |  2 +
 4 files changed, 69 insertions(+), 28 deletions(-)

diff --git a/src/backend/optimizer/util/plancat.c b/src/backend/optimizer/util/plancat.c
index c0b61c3846..27d57371a0 100644
--- a/src/backend/optimizer/util/plancat.c
+++ b/src/backend/optimizer/util/plancat.c
@@ -65,6 +65,23 @@ typedef struct NotnullHashEntry
 	Bitmapset  *notnullattnums; /* attnums of NOT NULL columns */
 } NotnullHashEntry;
 
+/* Per-relation cache for simplifying repeated index expressions. */
+typedef struct IndexExprCacheEntry
+{
+	List	   *input;
+	List	   *result;
+	uint64		inval_count;
+} IndexExprCacheEntry;
+
+typedef struct IndexExprCache
+{
+	IndexExprCacheEntry entries[2];
+	int			next;
+	int			misses;
+} IndexExprCache;
+
+static List *simplify_index_exprs(PlannerInfo *root, List *exprs,
+								  IndexExprCache *cache);
 
 static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
 									  Relation relation, bool inhparent);
@@ -210,9 +227,7 @@ get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
 		List	   *indexoidlist;
 		LOCKMODE	lmode;
 		ListCell   *l;
-		List	   *prev_rawindexprs = NIL;
-		List	   *prev_indexprs = NIL;
-		uint64		prev_inval_count = 0;
+		IndexExprCache exprcache = {0};
 
 		indexoidlist = RelationGetIndexList(relation);
 
@@ -442,31 +457,8 @@ get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
 				if (varno != 1)
 					ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
 
-				/*
-				 * A table can have many indexes on the same expressions, such
-				 * as partial indexes that differ only in their predicate, and
-				 * simplifying them again can be costly, for instance when it
-				 * retries inlining a SQL function that can't be inlined.  So
-				 * if the expressions are the same as the previous index's,
-				 * just copy the result we got for that one, unless catalog
-				 * invalidations have been processed since then (opening an
-				 * index can do that), as the result might differ now.
-				 * eval_const_expressions() at most fills in opfuncid fields
-				 * of its input, which equal() ignores when zero, so we can
-				 * keep the input to compare with.
-				 */
-				if (prev_rawindexprs != NIL &&
-					prev_inval_count == SharedInvalidMessageCounter &&
-					equal(info->indexprs, prev_rawindexprs))
-					info->indexprs = copyObject(prev_indexprs);
-				else
-				{
-					prev_rawindexprs = info->indexprs;
-					prev_inval_count = SharedInvalidMessageCounter;
-					info->indexprs = (List *)
-						eval_const_expressions(root, (Node *) info->indexprs);
-					prev_indexprs = info->indexprs;
-				}
+				info->indexprs = simplify_index_exprs(root, info->indexprs,
+													  &exprcache);
 			}
 			if (info->indpred)
 			{
@@ -596,6 +588,51 @@ get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
 	table_close(relation, NoLock);
 }
 
+/*
+ * Partial indexes can share key expressions and differ only in their
+ * predicates.  Simplifying the same expressions over and over can be costly,
+ * especially if it retries inlining a SQL function that cannot be inlined.
+ * Keep two recent results to handle indexes with interleaved keys.
+ */
+static List *
+simplify_index_exprs(PlannerInfo *root, List *exprs, IndexExprCache *cache)
+{
+	IndexExprCacheEntry *entry;
+	const int	probe_interval = 8;
+
+	/*
+	 * If the keys keep changing, sample periodically to avoid walking long
+	 * expression trees on every miss.  Still update the cache on each miss so
+	 * we can recognize a later run of repeated keys.
+	 */
+	if (cache->misses < probe_interval || cache->misses % probe_interval == 0)
+	{
+		for (int i = 0; i < lengthof(cache->entries); i++)
+		{
+			entry = &cache->entries[i];
+			/* Opening an index can process catalog invalidations. */
+			if (entry->inval_count == SharedInvalidMessageCounter &&
+				equal(exprs, entry->input))
+			{
+				cache->misses = 0;
+				return copyObject(entry->result);
+			}
+		}
+	}
+
+	/*
+	 * eval_const_expressions() can fill in opfuncid fields, but equal()
+	 * ignores those when zero, so we can save its input for comparison.
+	 */
+	entry = &cache->entries[cache->next];
+	cache->next = (cache->next + 1) % lengthof(cache->entries);
+	cache->misses++;
+	entry->input = exprs;
+	entry->inval_count = SharedInvalidMessageCounter;
+	entry->result = (List *) eval_const_expressions(root, (Node *) exprs);
+	return entry->result;
+}
+
 /*
  * get_relation_foreign_keys -
  *	  Retrieves foreign key information for a given relation.
diff --git a/src/test/regress/expected/predicate.out b/src/test/regress/expected/predicate.out
index 904ab86ee9..99579b8304 100644
--- a/src/test/regress/expected/predicate.out
+++ b/src/test/regress/expected/predicate.out
@@ -492,6 +492,7 @@ CREATE FUNCTION pred_key(int) RETURNS text LANGUAGE sql IMMUTABLE
     RETURN concat_ws('-', $1, 'x');
 CREATE INDEX pred_tab_key0_idx ON pred_tab (pred_key(COALESCE(a, 0))) WHERE p = 0;
 CREATE INDEX pred_tab_a_idx ON pred_tab (a);
+CREATE INDEX pred_tab_other_idx ON pred_tab ((a * 2)) WHERE p = 2;
 CREATE INDEX pred_tab_key1_idx ON pred_tab (pred_key(COALESCE(a, 0))) WHERE p = 1;
 CREATE INDEX pred_tab_plus_idx ON pred_tab ((a + 1)) WHERE p = 1;
 ANALYZE pred_tab;
diff --git a/src/test/regress/sql/predicate.sql b/src/test/regress/sql/predicate.sql
index 92dd059105..ba1d2454a6 100644
--- a/src/test/regress/sql/predicate.sql
+++ b/src/test/regress/sql/predicate.sql
@@ -249,6 +249,7 @@ CREATE FUNCTION pred_key(int) RETURNS text LANGUAGE sql IMMUTABLE
     RETURN concat_ws('-', $1, 'x');
 CREATE INDEX pred_tab_key0_idx ON pred_tab (pred_key(COALESCE(a, 0))) WHERE p = 0;
 CREATE INDEX pred_tab_a_idx ON pred_tab (a);
+CREATE INDEX pred_tab_other_idx ON pred_tab ((a * 2)) WHERE p = 2;
 CREATE INDEX pred_tab_key1_idx ON pred_tab (pred_key(COALESCE(a, 0))) WHERE p = 1;
 CREATE INDEX pred_tab_plus_idx ON pred_tab ((a + 1)) WHERE p = 1;
 ANALYZE pred_tab;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194..f09af173c0 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1314,6 +1314,8 @@ IndexDeleteCounts
 IndexDeletePrefetchState
 IndexDoCheckCallback
 IndexElem
+IndexExprCache
+IndexExprCacheEntry
 IndexInfo
 IndexList
 IndexOnlyScan
