From 44edd0a127af28d4b71316259da65c233c28e69f Mon Sep 17 00:00:00 2001
From: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Date: Sat, 14 Nov 2026 01:14:47 +0500
Subject: [PATCH] Keep separate equivalence classes for grouping-set outputs.

Two outputs of one expression can hold different values when grouping
sets null them separately. equal() does not see that, so they shared
one EquivalenceClass. ORDER BY, LIMIT and DISTINCT ON used the first
target entry, and a sorted aggregate could skip the Sort.

A column that only some grouping sets null now gets its own
EquivalenceClass, matched by sortref, as volatile sort keys already are.
Pathkeys for the grouping input stay shared. Those values are equal
before nulling.
---
 src/backend/nodes/outfuncs.c               |   1 +
 src/backend/optimizer/path/equivclass.c    | 105 ++++++++++++++++-----
 src/backend/optimizer/path/indxpath.c      |   8 +-
 src/backend/optimizer/path/pathkeys.c      |  42 ++++++---
 src/backend/optimizer/plan/createplan.c    |  22 +++--
 src/backend/optimizer/plan/initsplan.c     |   2 +-
 src/include/nodes/pathnodes.h              |  17 ++++
 src/include/optimizer/paths.h              |   3 +-
 src/test/regress/expected/groupingsets.out |  84 +++++++++++++++++
 src/test/regress/sql/groupingsets.sql      |  36 +++++++
 10 files changed, 267 insertions(+), 53 deletions(-)

diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index 40990143927..ba06a3a19bd 100644
--- a/src/backend/nodes/outfuncs.c
+++ b/src/backend/nodes/outfuncs.c
@@ -477,6 +477,7 @@ _outEquivalenceClass(StringInfo str, const EquivalenceClass *node)
 	WRITE_BITMAPSET_FIELD(ec_relids);
 	WRITE_BOOL_FIELD(ec_has_const);
 	WRITE_BOOL_FIELD(ec_has_volatile);
+	WRITE_BOOL_FIELD(ec_sortref_specific);
 	WRITE_BOOL_FIELD(ec_broken);
 	WRITE_UINT_FIELD(ec_sortref);
 	WRITE_UINT_FIELD(ec_min_security);
diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index 439cb651c01..36e27cffc9f 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -308,8 +308,8 @@ process_equivalence(PlannerInfo *root,
 		EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
 		ListCell   *lc2;
 
-		/* Never match to a volatile EC */
-		if (cur_ec->ec_has_volatile)
+		/* Value is not identified by the expression alone */
+		if (EC_SORTREF_SPECIFIC(cur_ec))
 			continue;
 
 		/*
@@ -491,6 +491,7 @@ process_equivalence(PlannerInfo *root,
 		ec->ec_relids = NULL;
 		ec->ec_has_const = false;
 		ec->ec_has_volatile = false;
+		ec->ec_sortref_specific = false;
 		ec->ec_broken = false;
 		ec->ec_sortref = 0;
 		ec->ec_min_security = restrictinfo->security_level;
@@ -701,6 +702,36 @@ add_child_eq_member(PlannerInfo *root, EquivalenceClass *ec, int ec_index,
 	return em;
 }
 
+/*
+ * sortref_nulled_by_grouping_sets
+ *		True when some grouping sets include this sortref and others do not.
+ *
+ * The output column is then NULL in some sets and the underlying value in
+ * others.  A column that is in every set is never nulled.
+ */
+static bool
+sortref_nulled_by_grouping_sets(PlannerInfo *root, Index sortref)
+{
+	ListCell   *lc;
+	bool		in_some = false;
+	bool		missing_from_some = false;
+
+	if (sortref == 0 || root->parse->groupingSets == NIL)
+		return false;
+
+	foreach(lc, root->parse->groupingSets)
+	{
+		if (list_member_int((List *) lfirst(lc), (int) sortref))
+			in_some = true;
+		else
+			missing_from_some = true;
+
+		if (in_some && missing_from_some)
+			return true;
+	}
+
+	return false;
+}
 
 /*
  * get_eclass_for_sort_expr
@@ -711,6 +742,12 @@ add_child_eq_member(PlannerInfo *root, EquivalenceClass *ec, int ec_index,
  * sortref is the SortGroupRef of the originating SortGroupClause, if any,
  * or zero if not.  (It should never be zero if the expression is volatile!)
  *
+ * below_grouping is true when the expression is the grouping input, after
+ * the grouping step's nulling bit has been removed.  Those values are equal
+ * across sortrefs that grouping sets will later null separately, so they
+ * share an ordinary EC.  A post-grouping reference to a column that only
+ * some sets null does not.
+ *
  * If rel is not NULL, it identifies a specific relation we're considering
  * a path for, and indicates that child EC members for that relation can be
  * considered.  Otherwise child members are ignored.  (Note: since child EC
@@ -741,7 +778,8 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 						 Oid collation,
 						 Index sortref,
 						 Relids relids,
-						 bool create_it)
+						 bool create_it,
+						 bool below_grouping)
 {
 	JoinDomain *jdomain;
 	Relids		expr_relids;
@@ -749,12 +787,16 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 	EquivalenceMember *newem;
 	ListCell   *lc1;
 	MemoryContext oldcontext;
+	bool		sortref_specific;
 
 	/*
 	 * Ensure the expression exposes the correct type and collation.
 	 */
 	expr = canonicalize_ec_expression(expr, opcintype, collation);
 
+	sortref_specific = (!below_grouping &&
+						sortref_nulled_by_grouping_sets(root, sortref));
+
 	/*
 	 * Since SortGroupClause nodes are top-level expressions (GROUP BY, ORDER
 	 * BY, etc), they can be presumed to belong to the top JoinDomain.
@@ -771,12 +813,20 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 		EquivalenceMember *cur_em;
 
 		/*
-		 * Never match to a volatile EC, except when we are looking at another
-		 * reference to the same volatile SortGroupClause.
+		 * A volatile EC matches only another reference to the same
+		 * SortGroupClause.  A grouping-set EC matches only that sortref, and
+		 * not a below-grouping reference to the same expression.  A
+		 * post-grouping column that only some sets null must not join an
+		 * ordinary EC for the same expr.
 		 */
 		if (cur_ec->ec_has_volatile &&
 			(sortref == 0 || sortref != cur_ec->ec_sortref))
 			continue;
+		if (cur_ec->ec_sortref_specific &&
+			(below_grouping || sortref != cur_ec->ec_sortref))
+			continue;
+		if (sortref_specific && !cur_ec->ec_sortref_specific)
+			continue;
 
 		if (collation != cur_ec->ec_collation)
 			continue;
@@ -829,14 +879,16 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 	newec->ec_relids = NULL;
 	newec->ec_has_const = false;
 	newec->ec_has_volatile = contain_volatile_functions((Node *) expr);
+	newec->ec_sortref_specific = sortref_specific;
 	newec->ec_broken = false;
 	newec->ec_sortref = sortref;
 	newec->ec_min_security = UINT_MAX;
 	newec->ec_max_security = 0;
 	newec->ec_merged = NULL;
 
-	if (newec->ec_has_volatile && sortref == 0) /* should not happen */
-		elog(ERROR, "volatile EquivalenceClass has no sortref");
+	if ((newec->ec_has_volatile || newec->ec_sortref_specific) &&
+		sortref == 0)			/* should not happen */
+		elog(ERROR, "sortref-specific EquivalenceClass has no sortref");
 
 	/*
 	 * Get the precise set of relids appearing in the expression.
@@ -855,6 +907,7 @@ get_eclass_for_sort_expr(PlannerInfo *root,
 	if (newec->ec_has_const)
 	{
 		if (newec->ec_has_volatile ||
+			newec->ec_sortref_specific ||
 			expression_returns_set((Node *) expr) ||
 			contain_agg_clause((Node *) expr) ||
 			contain_window_function((Node *) expr))
@@ -1087,9 +1140,11 @@ relation_can_be_sorted_early(PlannerInfo *root, RelOptInfo *rel,
 	ListCell   *lc;
 
 	/*
-	 * Reject volatile ECs immediately; such sorts must always be postponed.
+	 * Reject ECs whose value is not the expression.  A volatile sort must run
+	 * at the right plan step.  A grouping-set output that only some sets null
+	 * cannot be produced by sorting the input relation.
 	 */
-	if (ec->ec_has_volatile)
+	if (EC_SORTREF_SPECIFIC(ec))
 		return false;
 
 	/*
@@ -2353,8 +2408,8 @@ reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo,
 		/* Ignore EC unless it contains pseudoconstants */
 		if (!cur_ec->ec_has_const)
 			continue;
-		/* Never match to a volatile EC */
-		if (cur_ec->ec_has_volatile)
+		/* Value is not identified by the expression alone */
+		if (EC_SORTREF_SPECIFIC(cur_ec))
 			continue;
 		/* It has to match the outer-join clause as to semantics, too */
 		if (collation != cur_ec->ec_collation)
@@ -2497,8 +2552,8 @@ reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
 		/* Ignore EC unless it contains pseudoconstants */
 		if (!cur_ec->ec_has_const)
 			continue;
-		/* Never match to a volatile EC */
-		if (cur_ec->ec_has_volatile)
+		/* Value is not identified by the expression alone */
+		if (EC_SORTREF_SPECIFIC(cur_ec))
 			continue;
 		/* It has to match the outer-join clause as to semantics, too */
 		if (collation != cur_ec->ec_collation)
@@ -2683,8 +2738,8 @@ exprs_known_equal(PlannerInfo *root, Node *item1, Node *item2, Oid opfamily)
 		bool		item2member = false;
 		ListCell   *lc2;
 
-		/* Never match to a volatile EC */
-		if (ec->ec_has_volatile)
+		/* Value is not identified by the expression alone */
+		if (EC_SORTREF_SPECIFIC(ec))
 			continue;
 
 		/*
@@ -2765,8 +2820,8 @@ match_eclasses_to_foreign_key_col(PlannerInfo *root,
 		EquivalenceMember *item2_em = NULL;
 		ListCell   *lc2;
 
-		/* Never match to a volatile EC */
-		if (ec->ec_has_volatile)
+		/* Value is not identified by the expression alone */
+		if (EC_SORTREF_SPECIFIC(ec))
 			continue;
 
 		/*
@@ -2879,11 +2934,10 @@ add_child_rel_equivalences(PlannerInfo *root,
 		EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
 
 		/*
-		 * If this EC contains a volatile expression, then generating child
-		 * EMs would be downright dangerous, so skip it.  We rely on a
-		 * volatile EC having only one EM.
+		 * Skip an EC whose value is not the expression.  It has one member,
+		 * and a child copy would not be that same value.
 		 */
-		if (cur_ec->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(cur_ec))
 			continue;
 
 		/* Sanity check eclass_indexes only contain ECs for parent_rel */
@@ -2993,11 +3047,10 @@ add_child_join_rel_equivalences(PlannerInfo *root,
 		EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
 
 		/*
-		 * If this EC contains a volatile expression, then generating child
-		 * EMs would be downright dangerous, so skip it.  We rely on a
-		 * volatile EC having only one EM.
+		 * Skip an EC whose value is not the expression.  It has one member,
+		 * and a child copy would not be that same value.
 		 */
-		if (cur_ec->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(cur_ec))
 			continue;
 
 		/* Sanity check on get_eclass_indexes_for_relids result */
@@ -3109,7 +3162,7 @@ add_child_rel_pathkey_equivalences(PlannerInfo *root, RelOptInfo *child_rel,
 	{
 		EquivalenceClass *ec = lfirst_node(PathKey, lc)->pk_eclass;
 
-		if (ec->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(ec))
 			continue;
 
 		foreach_node(EquivalenceMember, cur_em, ec->ec_members)
diff --git a/src/backend/optimizer/path/indxpath.c b/src/backend/optimizer/path/indxpath.c
index 3f5d4fa3182..a1b950111ea 100644
--- a/src/backend/optimizer/path/indxpath.c
+++ b/src/backend/optimizer/path/indxpath.c
@@ -3737,8 +3737,12 @@ match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
 		if (pathkey->pk_cmptype != COMPARE_LT || pathkey->pk_nulls_first)
 			return;
 
-		/* If eclass is volatile, no hope of using an indexscan */
-		if (pathkey->pk_eclass->ec_has_volatile)
+		/*
+		 * No index order matches an EC whose value is not the expression.
+		 * That is a volatile key, or a grouping-set output that only some
+		 * sets null.
+		 */
+		if (EC_SORTREF_SPECIFIC(pathkey->pk_eclass))
 			return;
 
 		/*
diff --git a/src/backend/optimizer/path/pathkeys.c b/src/backend/optimizer/path/pathkeys.c
index 50651813a11..70736f9aaac 100644
--- a/src/backend/optimizer/path/pathkeys.c
+++ b/src/backend/optimizer/path/pathkeys.c
@@ -193,6 +193,9 @@ pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys)
  * create_it is true if we should create any missing EquivalenceClass
  * needed to represent the sort key.  If it's false, we return NULL if the
  * sort key isn't already present in any EquivalenceClass.
+ *
+ * below_grouping is true when expr is a grouping input whose grouping
+ * nulling bit has been removed.  See get_eclass_for_sort_expr.
  */
 static PathKey *
 make_pathkey_from_sortinfo(PlannerInfo *root,
@@ -204,7 +207,8 @@ make_pathkey_from_sortinfo(PlannerInfo *root,
 						   bool nulls_first,
 						   Index sortref,
 						   Relids rel,
-						   bool create_it)
+						   bool create_it,
+						   bool below_grouping)
 {
 	CompareType cmptype;
 	Oid			equality_op;
@@ -234,7 +238,8 @@ make_pathkey_from_sortinfo(PlannerInfo *root,
 	/* Now find or (optionally) create a matching EquivalenceClass */
 	eclass = get_eclass_for_sort_expr(root, expr,
 									  opfamilies, opcintype, collation,
-									  sortref, rel, create_it);
+									  sortref, rel, create_it,
+									  below_grouping);
 
 	/* Fail if no EC and !create_it */
 	if (!eclass)
@@ -259,7 +264,8 @@ make_pathkey_from_sortop(PlannerInfo *root,
 						 bool reverse_sort,
 						 bool nulls_first,
 						 Index sortref,
-						 bool create_it)
+						 bool create_it,
+						 bool below_grouping)
 {
 	Oid			opfamily,
 				opcintype,
@@ -284,7 +290,8 @@ make_pathkey_from_sortop(PlannerInfo *root,
 									  nulls_first,
 									  sortref,
 									  NULL,
-									  create_it);
+									  create_it,
+									  below_grouping);
 }
 
 
@@ -790,6 +797,7 @@ build_index_pathkeys(PlannerInfo *root,
 											  nulls_first,
 											  0,
 											  index->rel->relids,
+											  false,
 											  false);
 
 		if (cpathkey)
@@ -949,6 +957,7 @@ build_partition_pathkeys(PlannerInfo *root, RelOptInfo *partrel,
 											  ScanDirectionIsBackward(scandir),
 											  0,
 											  partrel->relids,
+											  false,
 											  false);
 
 
@@ -1024,7 +1033,8 @@ build_expression_pathkey(PlannerInfo *root,
 										  (cmptype == COMPARE_GT),
 										  0,
 										  rel,
-										  create_it);
+										  create_it,
+										  false);
 
 	if (cpathkey)
 		pathkeys = list_make1(cpathkey);
@@ -1066,18 +1076,19 @@ convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel,
 		EquivalenceClass *sub_eclass = sub_pathkey->pk_eclass;
 		PathKey    *best_pathkey = NULL;
 
-		if (sub_eclass->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(sub_eclass))
 		{
 			/*
-			 * If the sub_pathkey's EquivalenceClass is volatile, then it must
-			 * have come from an ORDER BY clause, and we have to match it to
-			 * that same targetlist entry.
+			 * The sub_pathkey's EquivalenceClass does not identify a value by
+			 * expression alone.  Match it to the sortref's targetlist entry.
+			 * Volatile ORDER BY keys are one case.  A grouping-set output
+			 * that only some sets null is the other.
 			 */
 			TargetEntry *tle;
 			Var		   *outer_var;
 
 			if (sub_eclass->ec_sortref == 0)	/* can't happen */
-				elog(ERROR, "volatile EquivalenceClass has no sortref");
+				elog(ERROR, "sortref-specific EquivalenceClass has no sortref");
 			tle = get_sortgroupref_tle(sub_eclass->ec_sortref, subquery_tlist);
 			Assert(tle);
 			/* Is TLE actually available to the outer query? */
@@ -1107,6 +1118,7 @@ convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel,
 											 sub_eclass->ec_collation,
 											 0,
 											 rel->relids,
+											 false,
 											 false);
 
 				/*
@@ -1189,6 +1201,7 @@ convert_subquery_pathkeys(PlannerInfo *root, RelOptInfo *rel,
 														sub_expr_coll,
 														0,
 														rel->relids,
+														false,
 														false);
 
 					/*
@@ -1424,7 +1437,8 @@ make_pathkeys_for_sortclauses_extended(PlannerInfo *root,
 										   sortcl->reverse_sort,
 										   sortcl->nulls_first,
 										   sortcl->tleSortGroupRef,
-										   true);
+										   true,
+										   remove_group_rtindex);
 		if (pathkey->pk_eclass->ec_sortref == 0 && set_ec_sortref)
 		{
 			/*
@@ -1492,7 +1506,8 @@ initialize_mergeclause_eclasses(PlannerInfo *root, RestrictInfo *restrictinfo)
 								 ((OpExpr *) clause)->inputcollid,
 								 0,
 								 NULL,
-								 true);
+								 true,
+								 false);
 	restrictinfo->right_ec =
 		get_eclass_for_sort_expr(root,
 								 (Expr *) get_rightop(clause),
@@ -1501,7 +1516,8 @@ initialize_mergeclause_eclasses(PlannerInfo *root, RestrictInfo *restrictinfo)
 								 ((OpExpr *) clause)->inputcollid,
 								 0,
 								 NULL,
-								 true);
+								 true,
+								 false);
 }
 
 /*
diff --git a/src/backend/optimizer/plan/createplan.c b/src/backend/optimizer/plan/createplan.c
index 9c1a93f19fb..66e94bb3793 100644
--- a/src/backend/optimizer/plan/createplan.c
+++ b/src/backend/optimizer/plan/createplan.c
@@ -6288,15 +6288,16 @@ prepare_sort_from_pathkeys(PlannerInfo *root, Plan *lefttree, List *pathkeys,
 		Oid			sortop;
 		ListCell   *j;
 
-		if (ec->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(ec))
 		{
 			/*
-			 * If the pathkey's EquivalenceClass is volatile, then it must
-			 * have come from an ORDER BY clause, and we have to match it to
-			 * that same targetlist entry.
+			 * The pathkey's EquivalenceClass does not identify a value by
+			 * expression alone.  Match it to the sortref's targetlist entry.
+			 * Volatile ORDER BY keys are one case.  A grouping-set output
+			 * that only some sets null is the other.
 			 */
 			if (ec->ec_sortref == 0)	/* can't happen */
-				elog(ERROR, "volatile EquivalenceClass has no sortref");
+				elog(ERROR, "sortref-specific EquivalenceClass has no sortref");
 			tle = get_sortgroupref_tle(ec->ec_sortref, tlist);
 			Assert(tle);
 			Assert(list_length(ec->ec_members) == 1);
@@ -6833,15 +6834,16 @@ make_unique_from_pathkeys(Plan *lefttree, List *pathkeys, int numCols,
 		if (keyno >= numCols)
 			break;
 
-		if (ec->ec_has_volatile)
+		if (EC_SORTREF_SPECIFIC(ec))
 		{
 			/*
-			 * If the pathkey's EquivalenceClass is volatile, then it must
-			 * have come from an ORDER BY clause, and we have to match it to
-			 * that same targetlist entry.
+			 * The pathkey's EquivalenceClass does not identify a value by
+			 * expression alone.  Match it to the sortref's targetlist entry.
+			 * Volatile ORDER BY keys are one case.  A grouping-set output
+			 * that only some sets null is the other.
 			 */
 			if (ec->ec_sortref == 0)	/* can't happen */
-				elog(ERROR, "volatile EquivalenceClass has no sortref");
+				elog(ERROR, "sortref-specific EquivalenceClass has no sortref");
 			tle = get_sortgroupref_tle(ec->ec_sortref, plan->targetlist);
 			Assert(tle);
 			Assert(list_length(ec->ec_members) == 1);
diff --git a/src/backend/optimizer/plan/initsplan.c b/src/backend/optimizer/plan/initsplan.c
index d2dd1d68868..51f9bf123ab 100644
--- a/src/backend/optimizer/plan/initsplan.c
+++ b/src/backend/optimizer/plan/initsplan.c
@@ -1010,7 +1010,7 @@ get_eclass_for_sortgroupclause(PlannerInfo *root, SortGroupClause *sgc,
 	/* Now find a matching EquivalenceClass */
 	return get_eclass_for_sort_expr(root, expr, opfamilies, opcintype,
 									collation, sgc->tleSortGroupRef,
-									NULL, false);
+									NULL, false, false);
 }
 
 /*****************************************************************************
diff --git a/src/include/nodes/pathnodes.h b/src/include/nodes/pathnodes.h
index 2ba1dbfb67f..34358e3af35 100644
--- a/src/include/nodes/pathnodes.h
+++ b/src/include/nodes/pathnodes.h
@@ -1614,6 +1614,14 @@ typedef struct JoinDomain
  * entry: consider SELECT random() AS a, random() AS b ... ORDER BY b,a.
  * So we record the SortGroupRef of the originating sort clause.
  *
+ * Grouping sets have the same hazard.  SELECT a AS x, a AS y GROUP BY
+ * GROUPING SETS ((x), (y)) ORDER BY y puts different values in x and y,
+ * because each set nulls only one of them.  equal() does not see that.
+ * A shared EC sorts by the first target entry and can treat the aggregate
+ * output as already ordered.  A column that some sets null gets an EC with
+ * ec_sortref_specific set, matched only by ec_sortref.  Pathkeys for the
+ * grouping input are not marked.  Before nulling, those values are equal.
+ *
  * Derived equality clauses are stored in ec_derives_list. For small queries,
  * this list is scanned directly during lookup. For larger queries -- e.g.,
  * with many partitions or joins -- a hash table (ec_derives_hash) is built
@@ -1673,6 +1681,7 @@ typedef struct EquivalenceClass
 								 * for child members (see below) */
 	bool		ec_has_const;	/* any pseudoconstants in ec_members? */
 	bool		ec_has_volatile;	/* the (sole) member is a volatile expr */
+	bool		ec_sortref_specific;	/* match this EC only by ec_sortref */
 	bool		ec_broken;		/* failed to generate needed clauses? */
 	Index		ec_sortref;		/* originating sortclause label, or 0 */
 	Index		ec_min_security;	/* minimum security_level in ec_sources */
@@ -1687,6 +1696,14 @@ typedef struct EquivalenceClass
 #define EC_MUST_BE_REDUNDANT(eclass)  \
 	((eclass)->ec_has_const)
 
+/*
+ * True when the expression does not identify the value.  Match the EC to
+ * ec_sortref.  Volatile sort keys are one case.  A grouping-set output that
+ * only some sets null is the other.
+ */
+#define EC_SORTREF_SPECIFIC(eclass) \
+	((eclass)->ec_has_volatile || (eclass)->ec_sortref_specific)
+
 /*
  * EquivalenceMember - one member expression of an EquivalenceClass
  *
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.h
index 64f87da1674..addc9a7e392 100644
--- a/src/include/optimizer/paths.h
+++ b/src/include/optimizer/paths.h
@@ -144,7 +144,8 @@ extern EquivalenceClass *get_eclass_for_sort_expr(PlannerInfo *root,
 												  Oid collation,
 												  Index sortref,
 												  Relids relids,
-												  bool create_it);
+												  bool create_it,
+												  bool below_grouping);
 extern EquivalenceMember *find_ec_member_matching_expr(EquivalenceClass *ec,
 													   Expr *expr,
 													   Relids relids);
diff --git a/src/test/regress/expected/groupingsets.out b/src/test/regress/expected/groupingsets.out
index 4c4e9c887a2..bc6bf041af6 100644
--- a/src/test/regress/expected/groupingsets.out
+++ b/src/test/regress/expected/groupingsets.out
@@ -2817,4 +2817,88 @@ select i as ai1, i as ai2 from generate_series(1,3) i
      |   3
 (6 rows)
 
+-- Two outputs of one expression still compare equal when both carry the
+-- same grouping nulling bit.  ORDER BY, LIMIT and DISTINCT ON must follow
+-- the requested column.  y, x breaks ties.
+-- A sorted aggregate can treat its output as already ordered.
+create temp table gstest_dup (a int);
+insert into gstest_dup values (1), (2);
+set enable_hashagg = false;
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+ x | y 
+---+---
+   | 1
+   | 2
+ 1 |  
+ 2 |  
+(4 rows)
+
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by x, y;
+ x | y 
+---+---
+ 1 |  
+ 2 |  
+   | 1
+   | 2
+(4 rows)
+
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x limit 1;
+ x | y 
+---+---
+   | 1
+(1 row)
+
+select distinct on (y) a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+ x | y 
+---+---
+   | 1
+   | 2
+ 1 |  
+(3 rows)
+
+select a + 1 as x, a + 1 as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+ x | y 
+---+---
+   | 2
+   | 3
+ 2 |  
+ 3 |  
+(4 rows)
+
+-- Both outputs are nulled in the same sets, so the values stay equal.
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x, y), ()) order by y, x;
+ x | y 
+---+---
+ 1 | 1
+ 2 | 2
+   |  
+(3 rows)
+
+-- A constant is not a redundant sort key once a grouping set can null it.
+select 1 as x, 1 as y
+  group by grouping sets ((x), (y)) order by y, x;
+ x | y 
+---+---
+   | 1
+ 1 |  
+(2 rows)
+
+set enable_hashagg = true;
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+ x | y 
+---+---
+   | 1
+   | 2
+ 1 |  
+ 2 |  
+(4 rows)
+
+drop table gstest_dup;
 -- end
diff --git a/src/test/regress/sql/groupingsets.sql b/src/test/regress/sql/groupingsets.sql
index cb323a58a8c..535f59ef87d 100644
--- a/src/test/regress/sql/groupingsets.sql
+++ b/src/test/regress/sql/groupingsets.sql
@@ -827,4 +827,40 @@ set enable_hashagg = true;
 select i as ai1, i as ai2 from generate_series(1,3) i
   group by ai2, rollup(ai1) order by ai2, ai1;
 
+
+-- Two outputs of one expression still compare equal when both carry the
+-- same grouping nulling bit.  ORDER BY, LIMIT and DISTINCT ON must follow
+-- the requested column.  y, x breaks ties.
+-- A sorted aggregate can treat its output as already ordered.
+create temp table gstest_dup (a int);
+insert into gstest_dup values (1), (2);
+
+set enable_hashagg = false;
+
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by x, y;
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x limit 1;
+select distinct on (y) a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+select a + 1 as x, a + 1 as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+
+-- Both outputs are nulled in the same sets, so the values stay equal.
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x, y), ()) order by y, x;
+
+-- A constant is not a redundant sort key once a grouping set can null it.
+select 1 as x, 1 as y
+  group by grouping sets ((x), (y)) order by y, x;
+
+set enable_hashagg = true;
+
+select a as x, a as y from gstest_dup
+  group by grouping sets ((x), (y)) order by y, x;
+
+drop table gstest_dup;
+
 -- end
-- 
2.53.0

