diff --git a/src/backend/optimizer/path/equivclass.c b/src/backend/optimizer/path/equivclass.c
index b68a5a0ec7..8507cc8ef4 100644
--- a/src/backend/optimizer/path/equivclass.c
+++ b/src/backend/optimizer/path/equivclass.c
@@ -138,6 +138,8 @@ process_equivalence(PlannerInfo *root,
 			   *em2;
 	ListCell   *lc1;
 
+	Assert(CurrentMemoryContext == root->planner_cxt);
+
 	/* Should not already be marked as having generated an eclass */
 	Assert(restrictinfo->left_ec == NULL);
 	Assert(restrictinfo->right_ec == NULL);
@@ -2253,6 +2255,8 @@ add_child_rel_equivalences(PlannerInfo *root,
 	Relids		child_relids = child_rel->relids;
 	int			i;
 
+	Assert(CurrentMemoryContext == root->planner_cxt);
+
 	/*
 	 * EC merging should be complete already, so we can use the parent rel's
 	 * eclass_indexes to avoid searching all of root->eq_classes.
@@ -2380,6 +2384,7 @@ add_child_join_rel_equivalences(PlannerInfo *root,
 	Relids		top_parent_relids = child_joinrel->top_parent_relids;
 	Relids		child_relids = child_joinrel->relids;
 	Bitmapset  *matching_ecs;
+	MemoryContext oldcontext;
 	int			i;
 
 	Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
@@ -2387,6 +2392,8 @@ add_child_join_rel_equivalences(PlannerInfo *root,
 	/* We need consider only ECs that mention the parent joinrel */
 	matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
 
+	oldcontext = MemoryContextSwitchTo(root->planner_cxt);
+
 	i = -1;
 	while ((i = bms_next_member(matching_ecs, i)) >= 0)
 	{
@@ -2486,6 +2493,8 @@ add_child_join_rel_equivalences(PlannerInfo *root,
 			}
 		}
 	}
+
+	MemoryContextSwitchTo(oldcontext);
 }
 
 
