From fc0c737774c4999f809df35c10eb11e93c406673 Mon Sep 17 00:00:00 2001
From: "ZizhuanLiu(X-MAN)" <44973863@qq.com>
Date: Thu, 26 Nov 2026 23:52:53 +0800
Subject: [PATCH v1] Normalize RelabelTypes after stripping PlaceHolderVars

Removing PlaceHolderVars during statistics lookup can expose adjacent
RelabelType nodes below the root of an expression.  The top-level
stripping loop in examine_variable() cannot reach them, so equal() can
fail to match the expression to index or extended-statistics expressions
that have already been simplified by eval_const_expressions().  This can
cause the planner to ignore available expression statistics.

Normalize adjacent and redundant relabels during the existing recursive
PHV-removal walk, after processing each node's children.  Discard inner
relabels and remove the outer relabel too if its type, typmod, and
collation match the final argument.

Add tests in join.sql with relabels inside a function argument.  Cover
both statistics sources and retention of a required outer collation,
with an initial estimate before expression statistics are available.
---
 src/backend/utils/adt/selfuncs.c   | 53 +++++++++++++++++--
 src/test/regress/expected/join.out | 85 ++++++++++++++++++++++++++++++
 src/test/regress/sql/join.sql      | 71 +++++++++++++++++++++++++
 3 files changed, 204 insertions(+), 5 deletions(-)

diff --git a/src/backend/utils/adt/selfuncs.c b/src/backend/utils/adt/selfuncs.c
index 5ee37759..0d129acb 100644
--- a/src/backend/utils/adt/selfuncs.c
+++ b/src/backend/utils/adt/selfuncs.c
@@ -242,6 +242,7 @@ static double convert_timevalue_to_scalar(Datum value, Oid typid,
 										  bool *failure);
 static Node *strip_all_phvs_deep(PlannerInfo *root, Node *node);
 static bool contain_placeholder_walker(Node *node, void *context);
+static Node *strip_all_adjacency_relabeltypes(Node *node);
 static Node *strip_all_phvs_mutator(Node *node, void *context);
 static void examine_simple_variable(PlannerInfo *root, Var *var,
 									VariableStatData *vardata);
@@ -5671,9 +5672,8 @@ examine_variable(PlannerInfo *root, Node *node, int varRelid,
 	basenode = strip_all_phvs_deep(root, node);
 
 	/*
-	 * Look inside any binary-compatible relabeling.  We need to handle nested
-	 * RelabelType nodes here, because the prior stripping of PlaceHolderVars
-	 * may have brought separate RelabelTypes into adjacency.
+	 * Look inside any remaining binary-compatible relabeling at the top
+	 * level.
 	 */
 	while (IsA(basenode, RelabelType))
 		basenode = (Node *) ((RelabelType *) basenode)->arg;
@@ -6013,9 +6013,44 @@ contain_placeholder_walker(Node *node, void *context)
 	return expression_tree_walker(node, contain_placeholder_walker, context);
 }
 
+/*
+ * strip_all_adjacency_relabeltypes
+ *		Normalize adjacent or redundant RelabelTypes at the current node.
+ *
+ * Follow applyRelabelType()'s rules for merging stacked RelabelTypes and
+ * removing no-op relabels: retain only the outer relabel, and drop that too
+ * if its argument already has the required type, typmod, and collation.
+ * The caller has already copied and processed the subtree, so it is safe
+ * to modify the outer relabel in place.
+ */
+static Node *
+strip_all_adjacency_relabeltypes(Node *node)
+{
+	RelabelType *relabel;
+	Node	   *arg;
+
+	if (node == NULL || !IsA(node, RelabelType))
+		return node;
+
+	relabel = (RelabelType *) node;
+	arg = (Node *) relabel->arg;
+
+	while (arg && IsA(arg, RelabelType))
+		arg = (Node *) ((RelabelType *) arg)->arg;
+
+	if (exprType(arg) == relabel->resulttype &&
+		exprTypmod(arg) == relabel->resulttypmod &&
+		exprCollation(arg) == relabel->resultcollid)
+		node = arg;
+	else
+		relabel->arg = (Expr *) arg;
+
+	return node;
+}
+
 /*
  * strip_all_phvs_mutator
- *		Mutator to deeply strip all PlaceHolderVars
+ *		Deeply strip all PlaceHolderVars and normalize RelabelTypes
  */
 static Node *
 strip_all_phvs_mutator(Node *node, void *context)
@@ -6030,7 +6065,15 @@ strip_all_phvs_mutator(Node *node, void *context)
 		return strip_all_phvs_mutator((Node *) phv->phexpr, context);
 	}
 
-	return expression_tree_mutator(node, strip_all_phvs_mutator, context);
+	node = expression_tree_mutator(node, strip_all_phvs_mutator, context);
+
+	/*
+	 * Stripping PHVs can expose adjacent or redundant RelabelTypes at any
+	 * depth.  Normalize them after processing the children, so they do not
+	 * prevent matching to index or statistics expressions that have already
+	 * been simplified by eval_const_expressions().
+	 */
+	return strip_all_adjacency_relabeltypes(node);
 }
 
 /*
diff --git a/src/test/regress/expected/join.out b/src/test/regress/expected/join.out
index 440511d2..a254f1ad 100644
--- a/src/test/regress/expected/join.out
+++ b/src/test/regress/expected/join.out
@@ -13349,6 +13349,91 @@ WHERE ss.unique1 = ss.phv AND t1.unique1 < 100;
       42
 (1 row)
 
+-- Removing a PHV can expose adjacent RelabelTypes inside a function argument:
+-- lower(RT_C(PHV(RT_POSIX(E)))) -> lower(RT_C(RT_POSIX(E)))).
+-- Top-level RelabelType stripping in examine_variable() cannot reach them.
+-- Check row estimates, since the plan shape need not change.
+CREATE FUNCTION check_phv_estimated_rows(query text)
+RETURNS TABLE (estimated int, actual int)
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  EXECUTE 'EXPLAIN (ANALYZE, FORMAT JSON) ' || query INTO plan;
+  RETURN QUERY SELECT (plan->0->'Plan'->>'Plan Rows')::int,
+                      (plan->0->'Plan'->>'Actual Rows')::numeric::int;
+END;
+$$;
+-- COALESCE makes the expression on the nullable side require a PHV.
+CREATE TABLE phv_relabel_left (id int) WITH (autovacuum_enabled = off);
+CREATE TABLE phv_relabel_right (id int, a text COLLATE "C")
+  WITH (autovacuum_enabled = off);
+INSERT INTO phv_relabel_left SELECT g FROM generate_series(1, 1000) g;
+INSERT INTO phv_relabel_right SELECT g, chr(65 + g % 10) || g
+  FROM generate_series(1, 1000) g;
+-- Without expression statistics, the number of groups is overestimated.
+ANALYZE phv_relabel_left, phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+ estimated | actual 
+-----------+--------
+      1000 |     10
+(1 row)
+
+-- PHV removal exposes relabels that cancel inside lower()'s argument.
+CREATE INDEX phv_relabel_idx ON phv_relabel_right
+  (lower(coalesce(left(a, 1), '')));
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+ estimated | actual 
+-----------+--------
+        10 |     10
+(1 row)
+
+DROP INDEX phv_relabel_idx;
+-- The same normalization is needed to match expression statistics.
+CREATE STATISTICS phv_relabel_stats ON (lower(coalesce(left(a, 1), '')))
+  FROM phv_relabel_right;
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+ estimated | actual 
+-----------+--------
+        10 |     10
+(1 row)
+
+DROP STATISTICS phv_relabel_stats;
+-- Keep the outer collation when it differs from the underlying expression.
+CREATE STATISTICS phv_relabel_stats
+  ON (lower(coalesce(left(a, 1), '') COLLATE "default"))
+  FROM phv_relabel_right;
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "default"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "default")
+$$);
+ estimated | actual 
+-----------+--------
+        10 |     10
+(1 row)
+
+DROP TABLE phv_relabel_left, phv_relabel_right;
+DROP FUNCTION check_phv_estimated_rows(text);
 --
 -- Test for a nested loop join involving index scan, transforming OR-clauses
 -- to SAOP.
diff --git a/src/test/regress/sql/join.sql b/src/test/regress/sql/join.sql
index 45dcd48d..f16736f9 100644
--- a/src/test/regress/sql/join.sql
+++ b/src/test/regress/sql/join.sql
@@ -5075,6 +5075,77 @@ SELECT t1.unique1 FROM tenk1 t1 LEFT JOIN
   (SELECT *, 42 AS phv FROM tenk1 t2) ss ON t1.unique2 = ss.unique2
 WHERE ss.unique1 = ss.phv AND t1.unique1 < 100;
 
+-- Removing a PHV can expose adjacent RelabelTypes inside a function argument:
+-- lower(RT_C(PHV(RT_POSIX(E)))) -> lower(RT_C(RT_POSIX(E)))).
+-- Top-level RelabelType stripping in examine_variable() cannot reach them.
+-- Check row estimates, since the plan shape need not change.
+CREATE FUNCTION check_phv_estimated_rows(query text)
+RETURNS TABLE (estimated int, actual int)
+LANGUAGE plpgsql AS $$
+DECLARE
+  plan json;
+BEGIN
+  EXECUTE 'EXPLAIN (ANALYZE, FORMAT JSON) ' || query INTO plan;
+  RETURN QUERY SELECT (plan->0->'Plan'->>'Plan Rows')::int,
+                      (plan->0->'Plan'->>'Actual Rows')::numeric::int;
+END;
+$$;
+
+-- COALESCE makes the expression on the nullable side require a PHV.
+CREATE TABLE phv_relabel_left (id int) WITH (autovacuum_enabled = off);
+CREATE TABLE phv_relabel_right (id int, a text COLLATE "C")
+  WITH (autovacuum_enabled = off);
+INSERT INTO phv_relabel_left SELECT g FROM generate_series(1, 1000) g;
+INSERT INTO phv_relabel_right SELECT g, chr(65 + g % 10) || g
+  FROM generate_series(1, 1000) g;
+
+-- Without expression statistics, the number of groups is overestimated.
+ANALYZE phv_relabel_left, phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+
+-- PHV removal exposes relabels that cancel inside lower()'s argument.
+CREATE INDEX phv_relabel_idx ON phv_relabel_right
+  (lower(coalesce(left(a, 1), '')));
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+DROP INDEX phv_relabel_idx;
+
+-- The same normalization is needed to match expression statistics.
+CREATE STATISTICS phv_relabel_stats ON (lower(coalesce(left(a, 1), '')))
+  FROM phv_relabel_right;
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "C"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "C")
+$$);
+DROP STATISTICS phv_relabel_stats;
+
+-- Keep the outer collation when it differs from the underlying expression.
+CREATE STATISTICS phv_relabel_stats
+  ON (lower(coalesce(left(a, 1), '') COLLATE "default"))
+  FROM phv_relabel_right;
+ANALYZE phv_relabel_right;
+SELECT * FROM check_phv_estimated_rows($$
+  SELECT lower(r.x COLLATE "default"), count(*) FROM phv_relabel_left l
+    LEFT JOIN (SELECT id, coalesce(left(a, 1), '') COLLATE "POSIX" AS x
+               FROM phv_relabel_right) r ON l.id = r.id
+    GROUP BY lower(r.x COLLATE "default")
+$$);
+DROP TABLE phv_relabel_left, phv_relabel_right;
+DROP FUNCTION check_phv_estimated_rows(text);
+
 --
 -- Test for a nested loop join involving index scan, transforming OR-clauses
 -- to SAOP.
-- 
2.43.0

