From 58e3692d65807c111bd053e4d5c5c1d94db2f382 Mon Sep 17 00:00:00 2001
From: Manu <manuelreyesbravo@gmail.com>
Date: Sun, 6 Dec 2026 01:35:45 -0300
Subject: [PATCH v4 1/3] Rebuild partition descriptors from the previous one

Every ATTACH, DETACH, CREATE ... PARTITION OF or DROP of a partition
invalidates the parent's relcache entry, and the next use of the table
in every backend rebuilds its partition descriptor from scratch: it
reads the relpartbound of every partition from pg_class, converts it
from its text form and sorts all the bounds.  A dump restore of N
partitions thus does O(N^2) work, and every other session using the
table pays O(N) after each such command.

Keep, per backend, a record of the last descriptor built for each
partitioned table: its partitions and a copy of its bound info.  A
change of a partition's bounds or of its membership updates its
pg_class row, which sends a relcache invalidation for the partition;
a callback marks it dirty in the records that have it.  A rebuild
still reads pg_inherits, takes the partitions listed there that are
not dirty from the record, with their bounds and without catalog
access, and reads and converts only the others.  A descriptor built
while invalidations arrived is not recorded.

The callback is a relcache one, registered the first time a record
is kept: a syscache callback on pg_class gets only a hash value, not
the partition's OID.  It takes one of the MAX_RELCACHE_CALLBACKS
slots; a regular backend registers at most three others in core.

The record is a private copy, never handed out, so the relcache's
descriptor is built and freed exactly as before.  That descriptor is
not updated in place: a PartitionDirectory or a running query can
still hold it when the invalidation arrives, so doing so would need
reference counting.  The copy costs 1.24 to 1.26 times the memory of
the descriptor: 461,544 against 371,400 bytes for 10,000 range
partitions on an int column, and 49,544 against 39,400 bytes for
1,000.

The record of a table is released when the table is dropped.  The
table's own relcache invalidation, which also comes with every ATTACH
or DETACH, flags the record, and before the backend's next commit
PreCommit_PartitionDescRecords() looks the table up in pg_class and
releases the record if the table is gone, or if a global invalidation
made it unusable.  In a backend that held the records of 200 tables
that another session then dropped, nothing is left after its next
statement: no record, and no memory context for them.

There is no limit on the records of tables that still exist: a
backend keeps one per partitioned table it has used, since that is
what makes the next rebuild cheap, and a limit would bring back the
full rebuild for the tables that fall out.

Add an isolation test where another session's descriptor is rebuilt
after a concurrent ATTACH and after a partition is moved to other
bounds, and where a session's record survives another session's
DETACH and ATTACH and is released once the table is dropped; and a
regression test for re-attaching a partition with different bounds.
---
 src/backend/access/transam/xact.c             |   7 +
 src/backend/partitioning/partbounds.c         | 212 +++++++++-
 src/backend/partitioning/partdesc.c           | 390 +++++++++++++++++-
 src/include/partitioning/partbounds.h         |  15 +
 src/include/partitioning/partdesc.h           |   1 +
 .../expected/partition-desc-rebuild.out       | 131 ++++++
 src/test/isolation/isolation_schedule         |   1 +
 .../specs/partition-desc-rebuild.spec         | 109 +++++
 src/test/regress/expected/partition_info.out  |  24 ++
 src/test/regress/sql/partition_info.sql       |  17 +
 src/tools/pgindent/typedefs.list              |   2 +
 11 files changed, 893 insertions(+), 16 deletions(-)
 create mode 100644 src/test/isolation/expected/partition-desc-rebuild.out
 create mode 100644 src/test/isolation/specs/partition-desc-rebuild.spec

diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index b55b770c2ba..a12b3507e54 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -44,6 +44,7 @@
 #include "libpq/be-fsstubs.h"
 #include "libpq/pqsignal.h"
 #include "miscadmin.h"
+#include "partitioning/partdesc.h"
 #include "pg_trace.h"
 #include "pgstat.h"
 #include "replication/logical.h"
@@ -2367,6 +2368,12 @@ CommitTransaction(void)
 	 */
 	PreCommit_on_commit_actions();
 
+	/*
+	 * Release the partition descriptor records of dropped tables.  This reads
+	 * the catalog, so it must happen before commit.
+	 */
+	PreCommit_PartitionDescRecords();
+
 	/*
 	 * Synchronize files that are created and not WAL-logged during this
 	 * transaction. This must happen before AtEOXact_RelationMap(), so that we
diff --git a/src/backend/partitioning/partbounds.c b/src/backend/partitioning/partbounds.c
index 9da8d0000bb..a386b117738 100644
--- a/src/backend/partitioning/partbounds.c
+++ b/src/backend/partitioning/partbounds.c
@@ -67,6 +67,7 @@ typedef struct PartitionRangeBound
 	Datum	   *datums;			/* range bound datums */
 	PartitionRangeDatumKind *kind;	/* the kind of each datum */
 	bool		lower;			/* this is the lower (vs upper) bound */
+	bool		from_prev;		/* taken from a previous bound info */
 } PartitionRangeBound;
 
 /*
@@ -97,11 +98,15 @@ static int32 qsort_partition_list_value_cmp(const void *a, const void *b,
 static int32 qsort_partition_rbound_cmp(const void *a, const void *b,
 										void *arg);
 static PartitionBoundInfo create_hash_bounds(PartitionBoundSpec **boundspecs,
-											 int nparts, PartitionKey key, int **mapping);
+											 int nparts, PartitionBoundsHint *hint,
+											 PartitionKey key, int **mapping);
 static PartitionBoundInfo create_list_bounds(PartitionBoundSpec **boundspecs,
-											 int nparts, PartitionKey key, int **mapping);
+											 int nparts, PartitionBoundsHint *hint,
+											 PartitionKey key, int **mapping);
 static PartitionBoundInfo create_range_bounds(PartitionBoundSpec **boundspecs,
-											  int nparts, PartitionKey key, int **mapping);
+											  int nparts, PartitionBoundsHint *hint,
+											  PartitionKey key, int **mapping);
+static int *hint_new_index(PartitionBoundsHint *hint, int *size);
 static PartitionBoundInfo merge_list_bounds(FmgrInfo *partsupfunc,
 											Oid *partcollation,
 											RelOptInfo *outer_rel,
@@ -298,6 +303,27 @@ get_qual_from_partbound(Relation parent, PartitionBoundSpec *spec)
 PartitionBoundInfo
 partition_bounds_create(PartitionBoundSpec **boundspecs, int nparts,
 						PartitionKey key, int **mapping)
+{
+	return partition_bounds_create_hinted(boundspecs, nparts, key, mapping,
+										  NULL);
+}
+
+/*
+ * partition_bounds_create_hinted
+ *		Like partition_bounds_create, but the bounds of some partitions can be
+ *		taken from an earlier PartitionBoundInfo of the same table.
+ *
+ * If hint is not NULL, the first hint->nprev entries of boundspecs are NULL:
+ * those partitions have the same bounds as the partitions with canonical
+ * indexes hint->prev_index[0..nprev-1] (in ascending order) had in
+ * hint->prev.  Their bounds are taken from there, already sorted relative to
+ * each other, so that only the bounds of the remaining partitions need to be
+ * converted from their parser node representation and sorted in.
+ */
+PartitionBoundInfo
+partition_bounds_create_hinted(PartitionBoundSpec **boundspecs, int nparts,
+							   PartitionKey key, int **mapping,
+							   PartitionBoundsHint *hint)
 {
 	int			i;
 
@@ -326,13 +352,13 @@ partition_bounds_create(PartitionBoundSpec **boundspecs, int nparts,
 	switch (key->strategy)
 	{
 		case PARTITION_STRATEGY_HASH:
-			return create_hash_bounds(boundspecs, nparts, key, mapping);
+			return create_hash_bounds(boundspecs, nparts, hint, key, mapping);
 
 		case PARTITION_STRATEGY_LIST:
-			return create_list_bounds(boundspecs, nparts, key, mapping);
+			return create_list_bounds(boundspecs, nparts, hint, key, mapping);
 
 		case PARTITION_STRATEGY_RANGE:
-			return create_range_bounds(boundspecs, nparts, key, mapping);
+			return create_range_bounds(boundspecs, nparts, hint, key, mapping);
 	}
 
 	Assert(false);
@@ -345,7 +371,8 @@ partition_bounds_create(PartitionBoundSpec **boundspecs, int nparts,
  */
 static PartitionBoundInfo
 create_hash_bounds(PartitionBoundSpec **boundspecs, int nparts,
-				   PartitionKey key, int **mapping)
+				   PartitionBoundsHint *hint, PartitionKey key,
+				   int **mapping)
 {
 	PartitionBoundInfo boundinfo;
 	PartitionHashBound *hbounds;
@@ -366,6 +393,16 @@ create_hash_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	{
 		PartitionBoundSpec *spec = boundspecs[i];
 
+		if (hint != NULL && i < hint->nprev)
+		{
+			Datum	   *datum = hint->prev->datums[hint->prev_index[i]];
+
+			hbounds[i].modulus = DatumGetInt32(datum[0]);
+			hbounds[i].remainder = DatumGetInt32(datum[1]);
+			hbounds[i].index = i;
+			continue;
+		}
+
 		if (spec->strategy != PARTITION_STRATEGY_HASH)
 			elog(ERROR, "invalid strategy in partition bound spec");
 
@@ -458,7 +495,8 @@ get_non_null_list_datum_count(PartitionBoundSpec **boundspecs, int nparts)
  */
 static PartitionBoundInfo
 create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
-				   PartitionKey key, int **mapping)
+				   PartitionBoundsHint *hint, PartitionKey key,
+				   int **mapping)
 {
 	PartitionBoundInfo boundinfo;
 	PartitionListValue *all_values;
@@ -469,6 +507,10 @@ create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	int			default_index = -1;
 	int			null_index = -1;
 	Datum	   *boundDatums;
+	int			nprev = hint ? hint->nprev : 0;
+	int		   *newidx = NULL;
+	int			nnewidx = 0;
+	int			nfromprev = 0;
 
 	boundinfo = palloc0_object(PartitionBoundInfoData);
 	boundinfo->strategy = key->strategy;
@@ -476,11 +518,55 @@ create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	boundinfo->null_index = -1;
 	boundinfo->default_index = -1;
 
-	ndatums = get_non_null_list_datum_count(boundspecs, nparts);
+	/*
+	 * The values of the partitions taken from the previous bound info are
+	 * there in sorted order already; find which of them are still wanted.
+	 */
+	if (nprev > 0)
+	{
+		PartitionBoundInfo prev = hint->prev;
+
+		newidx = hint_new_index(hint, &nnewidx);
+		for (i = 0; i < prev->ndatums; i++)
+		{
+			int			c = prev->indexes[i];
+
+			if (c >= 0 && c < nnewidx && newidx[c] >= 0)
+				nfromprev++;
+		}
+		if (prev->null_index >= 0 && prev->null_index < nnewidx &&
+			newidx[prev->null_index] >= 0)
+			null_index = newidx[prev->null_index];
+		if (prev->default_index >= 0 && prev->default_index < nnewidx &&
+			newidx[prev->default_index] >= 0)
+			default_index = newidx[prev->default_index];
+	}
+
+	ndatums = nfromprev +
+		get_non_null_list_datum_count(boundspecs + nprev, nparts - nprev);
 	all_values = palloc_array(PartitionListValue, ndatums);
 
+	j = 0;
+	if (nprev > 0)
+	{
+		PartitionBoundInfo prev = hint->prev;
+
+		for (i = 0; i < prev->ndatums; i++)
+		{
+			int			c = prev->indexes[i];
+
+			if (c >= 0 && c < nnewidx && newidx[c] >= 0)
+			{
+				all_values[j].index = newidx[c];
+				all_values[j].value = prev->datums[i][0];
+				j++;
+			}
+		}
+		pfree(newidx);
+	}
+
 	/* Create a unified list of non-null values across all partitions. */
-	for (j = 0, i = 0; i < nparts; i++)
+	for (i = nprev; i < nparts; i++)
 	{
 		PartitionBoundSpec *spec = boundspecs[i];
 		ListCell   *c;
@@ -671,7 +757,8 @@ create_list_bounds(PartitionBoundSpec **boundspecs, int nparts,
  */
 static PartitionBoundInfo
 create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
-					PartitionKey key, int **mapping)
+					PartitionBoundsHint *hint, PartitionKey key,
+					int **mapping)
 {
 	PartitionBoundInfo boundinfo;
 	PartitionRangeBound **rbounds = NULL;
@@ -685,6 +772,7 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	int			next_index = 0;
 	Datum	   *boundDatums;
 	PartitionRangeDatumKind *boundKinds;
+	int			nprev = hint ? hint->nprev : 0;
 
 	boundinfo = palloc0_object(PartitionBoundInfoData);
 	boundinfo->strategy = key->strategy;
@@ -694,10 +782,72 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	boundinfo->default_index = -1;
 
 	all_bounds = palloc0_array(PartitionRangeBound *, 2 * nparts);
+	ndatums = 0;
+
+	/*
+	 * Take the bounds of the partitions known from the previous bound info
+	 * from there.  A partition's upper bound is the datum whose index entry
+	 * is the partition, and its lower bound is the datum just before that one
+	 * (which may be the upper bound of the partition before it).
+	 */
+	if (nprev > 0)
+	{
+		PartitionBoundInfo previnfo = hint->prev;
+		int		   *newidx;
+		int			nnewidx;
+		int		   *upper_at;
+		PartitionRangeBound *space;
+
+		newidx = hint_new_index(hint, &nnewidx);
+		upper_at = palloc_array(int, nnewidx);
+		for (i = 0; i < nnewidx; i++)
+			upper_at[i] = -1;
+		for (i = 0; i < previnfo->ndatums; i++)
+		{
+			int			c = previnfo->indexes[i];
+
+			if (c >= 0 && c < nnewidx)
+				upper_at[c] = i;
+		}
+		if (previnfo->default_index >= 0 && previnfo->default_index < nnewidx &&
+			newidx[previnfo->default_index] >= 0)
+			default_index = newidx[previnfo->default_index];
+
+		space = palloc_array(PartitionRangeBound, 2 * nprev);
+		for (i = 0; i < nprev; i++)
+		{
+			int			u = upper_at[hint->prev_index[i]];
+			PartitionRangeBound *lower,
+					   *upper;
+
+			if (u < 0)
+			{
+				/* the default partition */
+				Assert(default_index == i);
+				continue;
+			}
+			Assert(u > 0);
+			lower = &space[2 * i];
+			lower->index = i;
+			lower->datums = previnfo->datums[u - 1];
+			lower->kind = previnfo->kind[u - 1];
+			lower->lower = true;
+			lower->from_prev = true;
+			upper = &space[2 * i + 1];
+			upper->index = i;
+			upper->datums = previnfo->datums[u];
+			upper->kind = previnfo->kind[u];
+			upper->lower = false;
+			upper->from_prev = true;
+			all_bounds[ndatums++] = lower;
+			all_bounds[ndatums++] = upper;
+		}
+		pfree(newidx);
+		pfree(upper_at);
+	}
 
 	/* Create a unified list of range bounds across all the partitions. */
-	ndatums = 0;
-	for (i = 0; i < nparts; i++)
+	for (i = nprev; i < nparts; i++)
 	{
 		PartitionBoundSpec *spec = boundspecs[i];
 		PartitionRangeBound *lower,
@@ -740,10 +890,18 @@ create_range_bounds(PartitionBoundSpec **boundspecs, int nparts,
 	{
 		PartitionRangeBound *cur = all_bounds[i];
 		bool		is_distinct = false;
+		bool		both_prev;
 		int			j;
 
-		/* Is the current bound distinct from the previous one? */
-		for (j = 0; j < key->partnatts; j++)
+		/*
+		 * Is the current bound distinct from the previous one?  Two bounds
+		 * taken from the previous bound info are the same datum there if
+		 * equal, and distinct otherwise, since it holds distinct bounds.
+		 */
+		both_prev = (prev != NULL && prev->from_prev && cur->from_prev);
+		if (both_prev)
+			is_distinct = (cur->datums != prev->datums);
+		for (j = 0; !both_prev && j < key->partnatts; j++)
 		{
 			Datum		cmpval;
 
@@ -3772,6 +3930,30 @@ qsort_partition_hbound_cmp(const void *a, const void *b)
 								h2->modulus, h2->remainder);
 }
 
+/*
+ * hint_new_index
+ *		Map canonical indexes in hint->prev to indexes in the new boundspecs.
+ *
+ * Returns an array of *size elements, -1 for partitions not taken over.
+ */
+static int *
+hint_new_index(PartitionBoundsHint *hint, int *size)
+{
+	int		   *newidx;
+
+	Assert(hint->nprev > 0);
+	*size = hint->prev_index[hint->nprev - 1] + 1;
+	newidx = palloc_array(int, *size);
+	for (int i = 0; i < *size; i++)
+		newidx[i] = -1;
+	for (int i = 0; i < hint->nprev; i++)
+	{
+		Assert(i == 0 || hint->prev_index[i] > hint->prev_index[i - 1]);
+		newidx[hint->prev_index[i]] = i;
+	}
+	return newidx;
+}
+
 /*
  * qsort_partition_list_value_cmp
  *
diff --git a/src/backend/partitioning/partdesc.c b/src/backend/partitioning/partdesc.c
index 4399fe9a3a0..5be4cf956bf 100644
--- a/src/backend/partitioning/partdesc.c
+++ b/src/backend/partitioning/partdesc.c
@@ -46,9 +46,295 @@ typedef struct PartitionDirectoryEntry
 	PartitionDesc pd;
 } PartitionDirectoryEntry;
 
+/*
+ * Backend-local record of the last partition descriptor built for each
+ * partitioned table.
+ *
+ * Attaching, detaching, creating or dropping a partition invalidates the
+ * parent's relcache entry, and the next use of the table in every backend
+ * rebuilds its partition descriptor from scratch: it reads the relpartbound of
+ * every partition from the catalog, converts it from its text form, and sorts
+ * all the bounds.  A dump restore of N partitions thus does O(N^2) work, and
+ * every other session pays O(N) after each such command.
+ *
+ * Instead, keep the partitions and a copy of the bound info of the last
+ * descriptor built for each table, and build the next one from that plus what
+ * changed.  Every change of a partition's bounds or of its membership in the
+ * table updates the partition's pg_class row, which sends a relcache
+ * invalidation for the partition; the callback marks the partition dirty in
+ * the records that have it.  A rebuild still reads pg_inherits, but it takes
+ * the partitions found there that are not dirty from the record, with their
+ * bounds and without any catalog access, and reads only the others.
+ *
+ * The record is a copy, not the relcache's descriptor, which can be freed at
+ * any invalidation; and a new descriptor is built separately and only then
+ * replaces the record, so an error halfway leaves the old record intact.
+ *
+ * Records are released when their table is dropped.  The table's own relcache
+ * invalidation flags its record, but it also arrives on every ATTACH or
+ * DETACH, and the callback cannot look at the catalog to tell the two apart.
+ * PreCommit_PartitionDescRecords() does that at the end of the transaction,
+ * and releases the flagged records whose table no longer exists, as well as
+ * those that a global invalidation left unusable.  Otherwise, the records of
+ * tables that still exist are kept for the life of the backend.
+ */
+typedef struct PartDescRecord
+{
+	Oid			parent;			/* hash key */
+	MemoryContext cxt;			/* holds everything below */
+	bool		valid;			/* false after a full reset, or if a store
+								 * failed partway */
+	bool		recheck;		/* table invalidated: does it still exist? */
+	int			nparts;
+	Oid		   *oids;			/* canonical order */
+	bool	   *is_leaf;		/* canonical order */
+	bool	   *dirty;			/* canonical order */
+	Oid		   *sorted_oids;	/* ascending */
+	int		   *sorted_pos;		/* canonical index of sorted_oids[i] */
+	PartitionBoundInfo boundinfo;
+} PartDescRecord;
+
+static HTAB *PartDescRecords = NULL;
+static MemoryContext PartDescRecordContext = NULL;
+static int	PartDescBuildDepth = 0;
+static uint64 PartDescInvalCount = 0;
+static bool PartDescRecheckPending = false;
+
 static PartitionDesc RelationBuildPartitionDesc(Relation rel,
 												bool omit_detached);
+static PartitionDesc RelationBuildPartitionDescGuts(Relation rel,
+													bool omit_detached);
+
+/*
+ * A relcache invalidation for relid: mark it dirty wherever it is recorded.
+ * InvalidOid means that all relcache entries are being invalidated.
+ */
+static void
+PartDescRecordCallback(Datum arg, Oid relid)
+{
+	HASH_SEQ_STATUS status;
+	PartDescRecord *rec;
+
+	PartDescInvalCount++;
+	if (PartDescRecords == NULL)
+		return;
+	hash_seq_init(&status, PartDescRecords);
+	while ((rec = hash_seq_search(&status)) != NULL)
+	{
+		int			lo = 0,
+					hi = rec->nparts;
+
+		/* the table may be gone: see PreCommit_PartitionDescRecords() */
+		if (!OidIsValid(relid) || rec->parent == relid)
+		{
+			rec->recheck = true;
+			PartDescRecheckPending = true;
+		}
+		if (!rec->valid)
+			continue;
+		if (!OidIsValid(relid))
+		{
+			rec->valid = false;
+			continue;
+		}
+		while (lo < hi)
+		{
+			int			mid = lo + (hi - lo) / 2;
+
+			if (rec->sorted_oids[mid] < relid)
+				lo = mid + 1;
+			else
+				hi = mid;
+		}
+		if (lo < rec->nparts && rec->sorted_oids[lo] == relid)
+			rec->dirty[rec->sorted_pos[lo]] = true;
+	}
+}
+
+static void
+PartDescRecordInit(void)
+{
+	static bool registered = false;
+	HASHCTL		ctl;
+
+	if (PartDescRecords != NULL)
+		return;
+	PartDescRecordContext = AllocSetContextCreate(CacheMemoryContext,
+												  "partition descriptor records",
+												  ALLOCSET_SMALL_SIZES);
+	ctl.keysize = sizeof(Oid);
+	ctl.entrysize = sizeof(PartDescRecord);
+	ctl.hcxt = PartDescRecordContext;
+	PartDescRecords = hash_create("partition descriptor records", 16, &ctl,
+								  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
+	if (!registered)
+	{
+		CacheRegisterRelcacheCallback(PartDescRecordCallback, (Datum) 0);
+		registered = true;
+	}
+}
+
+/*
+ * PreCommit_PartitionDescRecords
+ *		Release the records of partitioned tables that were dropped, and those
+ *		that a global invalidation left unusable.
+ *
+ * Called when a top-level transaction commits, before the commit itself, so
+ * that the catalog can still be read.  The records to check are those that
+ * PartDescRecordCallback() flagged; no descriptor is being built here, so
+ * none of them is in use.  If the table was dropped by this transaction, the
+ * catalog lookup no longer finds it either.  A table dropped by a transaction
+ * that then aborted is found, and keeps its record.
+ */
+void
+PreCommit_PartitionDescRecords(void)
+{
+	HASH_SEQ_STATUS status;
+	PartDescRecord *rec;
+	Oid		   *parents;
+	int			n = 0;
+
+	if (!PartDescRecheckPending)
+		return;
+	PartDescRecheckPending = false;
+	Assert(PartDescBuildDepth == 0);
+
+	parents = palloc_array(Oid, hash_get_num_entries(PartDescRecords));
+	hash_seq_init(&status, PartDescRecords);
+	while ((rec = hash_seq_search(&status)) != NULL)
+		if (rec->recheck)
+			parents[n++] = rec->parent;
+
+	for (int i = 0; i < n; i++)
+	{
+		rec = hash_search(PartDescRecords, &parents[i], HASH_FIND, NULL);
+		Assert(rec != NULL);
+
+		/* an invalidation that arrives during the lookup flags it again */
+		rec->recheck = false;
+		if (rec->valid &&
+			SearchSysCacheExists1(RELOID, ObjectIdGetDatum(parents[i])))
+			continue;
+		MemoryContextDelete(rec->cxt);
+		hash_search(PartDescRecords, &parents[i], HASH_REMOVE, NULL);
+	}
+	pfree(parents);
 
+	/*
+	 * Nothing left: give back the hash table as well.  An invalidation that
+	 * arrived during the lookups may have set PartDescRecheckPending again,
+	 * but there is no record left to check.
+	 */
+	if (hash_get_num_entries(PartDescRecords) == 0)
+	{
+		MemoryContextDelete(PartDescRecordContext);
+		PartDescRecords = NULL;
+		PartDescRecordContext = NULL;
+		PartDescRecheckPending = false;
+	}
+}
+
+/*
+ * Replace the record of parent with the descriptor just built.  The input
+ * arrays are in build order; mapping gives each one's canonical index, and
+ * order (if not NULL) its index in the list pg_inherits returned, which is
+ * sorted by OID.
+ */
+static void
+PartDescRecordStore(Oid parent, Oid *oids, bool *is_leaf, int *mapping,
+					int *order, int nparts, PartitionBoundInfo boundinfo,
+					PartitionKey key)
+{
+	PartDescRecord *rec;
+	bool		found;
+	MemoryContext oldcxt;
+
+	rec = hash_search(PartDescRecords, &parent, HASH_ENTER, &found);
+	if (!found)
+	{
+		rec->cxt = AllocSetContextCreate(PartDescRecordContext,
+										 "partition descriptor record",
+										 ALLOCSET_SMALL_SIZES);
+		rec->recheck = false;
+	}
+	rec->valid = false;
+	rec->nparts = 0;
+	MemoryContextReset(rec->cxt);
+	if (nparts == 0)
+		return;
+
+	oldcxt = MemoryContextSwitchTo(rec->cxt);
+	rec->oids = palloc_array(Oid, nparts);
+	rec->is_leaf = palloc_array(bool, nparts);
+	rec->dirty = palloc0_array(bool, nparts);
+	rec->sorted_oids = palloc_array(Oid, nparts);
+	rec->sorted_pos = palloc_array(int, nparts);
+	rec->boundinfo = partition_bounds_copy(boundinfo, key);
+	MemoryContextSwitchTo(oldcxt);
+
+	for (int i = 0; i < nparts; i++)
+	{
+		int			k = order ? order[i] : i;
+
+		rec->oids[mapping[i]] = oids[i];
+		rec->is_leaf[mapping[i]] = is_leaf[i];
+		rec->sorted_oids[k] = oids[i];
+		rec->sorted_pos[k] = mapping[i];
+	}
+	rec->nparts = nparts;
+	rec->valid = true;
+}
+
+/*
+ * Put the partitions taken from the record first, in their canonical order
+ * there, followed by the others in their original order.  prevpos[] holds
+ * each one's canonical index in the record (-1 if not taken from it), all
+ * below maxpos.  Returns the permutation applied (new index -> original
+ * index).
+ */
+static int *
+PartDescReorder(Oid *oids, bool *is_leaf, PartitionBoundSpec **boundspecs,
+				int *prevpos, int nparts, int maxpos)
+{
+	int		   *slot = palloc_array(int, maxpos);
+	int		   *order = palloc_array(int, nparts);
+	Oid		   *oids2 = palloc_array(Oid, nparts);
+	bool	   *is_leaf2 = palloc_array(bool, nparts);
+	PartitionBoundSpec **specs2 = palloc_array(PartitionBoundSpec *, nparts);
+	int		   *prevpos2 = palloc_array(int, nparts);
+	int			n = 0;
+
+	for (int p = 0; p < maxpos; p++)
+		slot[p] = -1;
+	for (int i = 0; i < nparts; i++)
+		if (prevpos[i] >= 0)
+			slot[prevpos[i]] = i;
+	for (int p = 0; p < maxpos; p++)
+		if (slot[p] >= 0)
+			order[n++] = slot[p];
+	for (int i = 0; i < nparts; i++)
+		if (prevpos[i] < 0)
+			order[n++] = i;
+	Assert(n == nparts);
+
+	for (int i = 0; i < nparts; i++)
+	{
+		oids2[i] = oids[order[i]];
+		is_leaf2[i] = is_leaf[order[i]];
+		specs2[i] = boundspecs[order[i]];
+		prevpos2[i] = prevpos[order[i]];
+	}
+	memcpy(oids, oids2, sizeof(Oid) * nparts);
+	memcpy(is_leaf, is_leaf2, sizeof(bool) * nparts);
+	memcpy(boundspecs, specs2, sizeof(PartitionBoundSpec *) * nparts);
+	memcpy(prevpos, prevpos2, sizeof(int) * nparts);
+	pfree(slot);
+	pfree(oids2);
+	pfree(is_leaf2);
+	pfree(specs2);
+	pfree(prevpos2);
+	return order;
+}
 
 /*
  * RelationGetPartitionDesc -- get partition descriptor, if relation is partitioned
@@ -132,6 +418,35 @@ RelationGetPartitionDesc(Relation rel, bool omit_detached)
  */
 static PartitionDesc
 RelationBuildPartitionDesc(Relation rel, bool omit_detached)
+{
+	PartitionDesc partdesc;
+
+	/*
+	 * A build nested inside another one (which could happen if a support
+	 * function of the partition key used the table) must not replace a record
+	 * that the outer build may be using.
+	 */
+	PartDescRecordInit();
+	PartDescBuildDepth++;
+	PG_TRY();
+	{
+		partdesc = RelationBuildPartitionDescGuts(rel, omit_detached);
+	}
+	PG_FINALLY();
+	{
+		PartDescBuildDepth--;
+	}
+	PG_END_TRY();
+
+	return partdesc;
+}
+
+/*
+ * RelationBuildPartitionDescGuts
+ *		Workhorse of RelationBuildPartitionDesc
+ */
+static PartitionDesc
+RelationBuildPartitionDescGuts(Relation rel, bool omit_detached)
 {
 	PartitionDesc partdesc;
 	PartitionBoundInfo boundinfo = NULL;
@@ -150,6 +465,12 @@ RelationBuildPartitionDesc(Relation rel, bool omit_detached)
 	MemoryContext new_pdcxt;
 	MemoryContext oldcxt;
 	int		   *mapping;
+	PartDescRecord *rec;
+	int			recidx;
+	int		   *prevpos = NULL;
+	int			nreused;
+	int		   *order = NULL;
+	uint64		inval_count = PartDescInvalCount;
 
 retry:
 
@@ -174,6 +495,24 @@ retry:
 		oids = palloc_array(Oid, nparts);
 		is_leaf = palloc_array(bool, nparts);
 		boundspecs = palloc_array(PartitionBoundSpec *, nparts);
+		prevpos = palloc_array(int, nparts);
+	}
+
+	/*
+	 * If the last descriptor built for this table is recorded, the partitions
+	 * that are still listed in pg_inherits (which returns them sorted by OID)
+	 * and are not dirty can be taken from the record.
+	 */
+	rec = NULL;
+	recidx = 0;
+	nreused = 0;
+	if (nparts > 0)
+	{
+		Oid			relid = RelationGetRelid(rel);
+
+		rec = hash_search(PartDescRecords, &relid, HASH_FIND, NULL);
+		if (rec != NULL && (!rec->valid || rec->nparts == 0))
+			rec = NULL;
 	}
 
 	/* Collect bound spec nodes for each partition. */
@@ -184,6 +523,31 @@ retry:
 		HeapTuple	tuple;
 		PartitionBoundSpec *boundspec = NULL;
 
+		prevpos[i] = -1;
+		if (rec != NULL)
+		{
+			while (recidx < rec->nparts && rec->sorted_oids[recidx] < inhrelid)
+				recidx++;
+			if (recidx < rec->nparts && rec->sorted_oids[recidx] == inhrelid &&
+				!rec->dirty[rec->sorted_pos[recidx]])
+			{
+				int			pos = rec->sorted_pos[recidx];
+
+				/* see the check on partdefid below */
+				if (rec->boundinfo->default_index == pos &&
+					get_default_partition_oid(RelationGetRelid(rel)) != inhrelid)
+					elog(ERROR, "expected partdefid %u, but got %u", inhrelid,
+						 get_default_partition_oid(RelationGetRelid(rel)));
+				oids[i] = inhrelid;
+				is_leaf[i] = rec->is_leaf[pos];
+				boundspecs[i] = NULL;
+				prevpos[i] = pos;
+				nreused++;
+				++i;
+				continue;
+			}
+		}
+
 		/* Try fetching the tuple from the catcache, for speed. */
 		tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(inhrelid));
 		if (HeapTupleIsValid(tuple))
@@ -307,9 +671,33 @@ retry:
 	 * Create PartitionBoundInfo and mapping, working in the caller's context.
 	 * This could fail, but we haven't done any damage if so.
 	 */
-	if (nparts > 0)
+	if (nparts > 0 && nreused > 0)
+	{
+		PartitionBoundsHint hint;
+
+		order = PartDescReorder(oids, is_leaf, boundspecs, prevpos, nparts,
+								rec->nparts);
+		hint.prev = rec->boundinfo;
+		hint.nprev = nreused;
+		hint.prev_index = prevpos;
+		boundinfo = partition_bounds_create_hinted(boundspecs, nparts, partkey,
+												   &mapping, &hint);
+	}
+	else if (nparts > 0)
 		boundinfo = partition_bounds_create(boundspecs, nparts, partkey, &mapping);
 
+	/*
+	 * Record this descriptor for the next rebuild, unless this build is
+	 * nested in another one, or the descriptor omits partitions being
+	 * detached, or invalidations arrived meanwhile: then the descriptor may
+	 * already be out of date, while the existing record still has its dirty
+	 * marks.
+	 */
+	if (PartDescBuildDepth == 1 && !(omit_detached && detached_exist) &&
+		inval_count == PartDescInvalCount)
+		PartDescRecordStore(RelationGetRelid(rel), oids, is_leaf, mapping,
+							order, nparts, boundinfo, partkey);
+
 	/*
 	 * Now build the actual relcache partition descriptor, copying all the
 	 * data into a new, small context.  As per above comment, we don't make
diff --git a/src/include/partitioning/partbounds.h b/src/include/partitioning/partbounds.h
index d66918f89c1..4ba715b5325 100644
--- a/src/include/partitioning/partbounds.h
+++ b/src/include/partitioning/partbounds.h
@@ -95,6 +95,17 @@ typedef struct PartitionBoundInfoData
 								 * isn't one */
 } PartitionBoundInfoData;
 
+/*
+ * Bounds of partitions known from an earlier PartitionBoundInfo of the same
+ * table; see partition_bounds_create_hinted().
+ */
+typedef struct PartitionBoundsHint
+{
+	PartitionBoundInfo prev;	/* the earlier bound info */
+	int			nprev;			/* leading boundspecs taken from it */
+	int		   *prev_index;		/* their canonical indexes in prev */
+} PartitionBoundsHint;
+
 #define partition_bound_accepts_nulls(bi) ((bi)->null_index != -1)
 #define partition_bound_has_default(bi) ((bi)->default_index != -1)
 
@@ -106,6 +117,10 @@ extern List *get_qual_from_partbound(Relation parent,
 									 PartitionBoundSpec *spec);
 extern PartitionBoundInfo partition_bounds_create(PartitionBoundSpec **boundspecs,
 												  int nparts, PartitionKey key, int **mapping);
+extern PartitionBoundInfo partition_bounds_create_hinted(PartitionBoundSpec **boundspecs,
+														 int nparts, PartitionKey key,
+														 int **mapping,
+														 PartitionBoundsHint *hint);
 extern bool partition_bounds_equal(int partnatts, int16 *parttyplen,
 								   bool *parttypbyval, PartitionBoundInfo b1,
 								   PartitionBoundInfo b2);
diff --git a/src/include/partitioning/partdesc.h b/src/include/partitioning/partdesc.h
index f8698e87455..b086e1defab 100644
--- a/src/include/partitioning/partdesc.h
+++ b/src/include/partitioning/partdesc.h
@@ -59,6 +59,7 @@ typedef struct PartitionDescData
 
 
 extern PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached);
+extern void PreCommit_PartitionDescRecords(void);
 
 extern PartitionDirectory CreatePartitionDirectory(MemoryContext mcxt, bool omit_detached);
 extern PartitionDesc PartitionDirectoryLookup(PartitionDirectory, Relation);
diff --git a/src/test/isolation/expected/partition-desc-rebuild.out b/src/test/isolation/expected/partition-desc-rebuild.out
new file mode 100644
index 00000000000..036bff30180
--- /dev/null
+++ b/src/test/isolation/expected/partition-desc-rebuild.out
@@ -0,0 +1,131 @@
+Parsed test spec with 2 sessions
+
+starting permutation: s1build s2add s1route
+step s1build: 
+  INSERT INTO pdr_range VALUES (5);
+  INSERT INTO pdr_list VALUES (5);
+  SELECT count(*) FROM pdr_hash;
+
+count
+-----
+    0
+(1 row)
+
+step s2add: 
+  CREATE TABLE pdr_range_x1 PARTITION OF pdr_range FOR VALUES FROM (900) TO (1000);
+  CREATE TABLE pdr_range_x2 PARTITION OF pdr_range FOR VALUES FROM (700) TO (800);
+  CREATE TABLE pdr_range_x3 PARTITION OF pdr_range FOR VALUES FROM (500) TO (600);
+  CREATE TABLE pdr_list_x1 PARTITION OF pdr_list FOR VALUES IN (90);
+  CREATE TABLE pdr_list_x2 PARTITION OF pdr_list FOR VALUES IN (70);
+  CREATE TABLE pdr_list_x3 PARTITION OF pdr_list FOR VALUES IN (50);
+  CREATE TABLE pdr_hash_x31 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 31);
+  CREATE TABLE pdr_hash_x27 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 27);
+  CREATE TABLE pdr_hash_x23 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 23);
+
+step s1route: 
+  INSERT INTO pdr_range VALUES (950), (750), (550), (195);
+  INSERT INTO pdr_list VALUES (90), (70), (50), (19);
+  INSERT INTO pdr_hash SELECT g FROM generate_series(1, 200) g;
+  SELECT tableoid::regclass, a FROM pdr_range WHERE a >= 195 ORDER BY a;
+  SELECT tableoid::regclass, a FROM pdr_list WHERE a >= 19 ORDER BY a;
+  SELECT count(*) FROM pdr_hash;
+  SELECT count(*) FROM pdr_hash WHERE satisfies_hash_partition('pdr_hash'::regclass, 32, 23, a) <> (tableoid = 'pdr_hash_x23'::regclass);
+
+tableoid    |  a
+------------+---
+pdr_range_19|195
+pdr_range_x3|550
+pdr_range_x2|750
+pdr_range_x1|950
+(4 rows)
+
+tableoid   | a
+-----------+--
+pdr_list_19|19
+pdr_list_x3|50
+pdr_list_x2|70
+pdr_list_x1|90
+(4 rows)
+
+count
+-----
+  200
+(1 row)
+
+count
+-----
+    0
+(1 row)
+
+
+starting permutation: s1build s2move s1moved s1movedold s1movedcheck
+step s1build: 
+  INSERT INTO pdr_range VALUES (5);
+  INSERT INTO pdr_list VALUES (5);
+  SELECT count(*) FROM pdr_hash;
+
+count
+-----
+    0
+(1 row)
+
+step s2move: 
+  ALTER TABLE pdr_range DETACH PARTITION pdr_range_1;
+  ALTER TABLE pdr_range ATTACH PARTITION pdr_range_1 FOR VALUES FROM (2000) TO (3000);
+
+step s1moved: INSERT INTO pdr_range VALUES (2500);
+step s1movedold: INSERT INTO pdr_range VALUES (15);
+ERROR:  no partition of relation "pdr_range" found for row
+step s1movedcheck: 
+  SELECT tableoid::regclass, a FROM pdr_range WHERE a IN (15, 2500) ORDER BY a;
+
+tableoid   |   a
+-----------+----
+pdr_range_1|2500
+(1 row)
+
+
+starting permutation: s1record s1save s2move s1moved s1kept s2drop s1trivial s1released
+step s1record: SELECT count(*) FROM pdr_range;
+count
+-----
+    0
+(1 row)
+
+step s1save: 
+  CREATE TEMP TABLE pdr_records AS
+    SELECT count(*) AS n FROM pg_backend_memory_contexts
+    WHERE name = 'partition descriptor record';
+
+step s2move: 
+  ALTER TABLE pdr_range DETACH PARTITION pdr_range_1;
+  ALTER TABLE pdr_range ATTACH PARTITION pdr_range_1 FOR VALUES FROM (2000) TO (3000);
+
+step s1moved: INSERT INTO pdr_range VALUES (2500);
+step s1kept: 
+  SELECT count(*) = (SELECT n FROM pdr_records) AS kept
+  FROM pg_backend_memory_contexts
+  WHERE name = 'partition descriptor record';
+
+kept
+----
+t   
+(1 row)
+
+step s2drop: DROP TABLE pdr_range;
+step s1trivial: SELECT 1;
+?column?
+--------
+       1
+(1 row)
+
+step s1released: 
+  SELECT count(*) AS records FROM pg_backend_memory_contexts
+  WHERE name = 'partition descriptor record';
+  DROP TABLE pdr_records;
+
+records
+-------
+      0
+(1 row)
+
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index 2de19ea634f..7483f637dcc 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -120,6 +120,7 @@ test: predicate-hash
 test: predicate-gist
 test: predicate-gin
 test: partition-concurrent-attach
+test: partition-desc-rebuild
 test: partition-drop-index-locking
 test: partition-index-attach
 test: partition-key-update-1
diff --git a/src/test/isolation/specs/partition-desc-rebuild.spec b/src/test/isolation/specs/partition-desc-rebuild.spec
new file mode 100644
index 00000000000..53a0edc9dc5
--- /dev/null
+++ b/src/test/isolation/specs/partition-desc-rebuild.spec
@@ -0,0 +1,109 @@
+# A partition descriptor rebuilt after another session added partitions
+#
+# The partition bound cache hands the bounds of the previous descriptor to
+# partition_bounds_create() in their canonical order, followed by the new
+# ones.  Here the new partitions have increasing OIDs but decreasing bounds,
+# so they arrive out of order and must be sorted and merged in.
+#
+# Then another session moves a partition to another bound while the first
+# session keeps its descriptor: the next rebuild must not reuse the old bound.
+#
+# Last, the first session's record of a table survives the move, and is
+# released after another session drops the table, once the first session
+# has committed one more transaction.  A build that sees invalidations
+# arrive is not recorded (as with debug_discard_caches), so that case only
+# compares counts.
+
+setup
+{
+  CREATE TABLE pdr_range (a int) PARTITION BY RANGE (a);
+  CREATE TABLE pdr_list (a int) PARTITION BY LIST (a);
+  CREATE TABLE pdr_hash (a int) PARTITION BY HASH (a);
+  DO $$
+  BEGIN
+    FOR i IN 0..19 LOOP
+      EXECUTE format('CREATE TABLE pdr_range_%s PARTITION OF pdr_range FOR VALUES FROM (%s) TO (%s)', i, i * 10, i * 10 + 10);
+      EXECUTE format('CREATE TABLE pdr_list_%s PARTITION OF pdr_list FOR VALUES IN (%s)', i, i);
+    END LOOP;
+    FOR i IN 0..31 LOOP
+      IF i NOT IN (23, 27, 31) THEN
+        EXECUTE format('CREATE TABLE pdr_hash_%s PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER %s)', i, i);
+      END IF;
+    END LOOP;
+  END
+  $$;
+}
+
+teardown
+{
+  DROP TABLE IF EXISTS pdr_range, pdr_list, pdr_hash;
+}
+
+session s1
+step s1build
+{
+  INSERT INTO pdr_range VALUES (5);
+  INSERT INTO pdr_list VALUES (5);
+  SELECT count(*) FROM pdr_hash;
+}
+step s1route
+{
+  INSERT INTO pdr_range VALUES (950), (750), (550), (195);
+  INSERT INTO pdr_list VALUES (90), (70), (50), (19);
+  INSERT INTO pdr_hash SELECT g FROM generate_series(1, 200) g;
+  SELECT tableoid::regclass, a FROM pdr_range WHERE a >= 195 ORDER BY a;
+  SELECT tableoid::regclass, a FROM pdr_list WHERE a >= 19 ORDER BY a;
+  SELECT count(*) FROM pdr_hash;
+  SELECT count(*) FROM pdr_hash WHERE satisfies_hash_partition('pdr_hash'::regclass, 32, 23, a) <> (tableoid = 'pdr_hash_x23'::regclass);
+}
+
+step s1moved		{ INSERT INTO pdr_range VALUES (2500); }
+step s1movedold		{ INSERT INTO pdr_range VALUES (15); }
+step s1movedcheck
+{
+  SELECT tableoid::regclass, a FROM pdr_range WHERE a IN (15, 2500) ORDER BY a;
+}
+step s1record		{ SELECT count(*) FROM pdr_range; }
+step s1save
+{
+  CREATE TEMP TABLE pdr_records AS
+    SELECT count(*) AS n FROM pg_backend_memory_contexts
+    WHERE name = 'partition descriptor record';
+}
+step s1kept
+{
+  SELECT count(*) = (SELECT n FROM pdr_records) AS kept
+  FROM pg_backend_memory_contexts
+  WHERE name = 'partition descriptor record';
+}
+step s1trivial		{ SELECT 1; }
+step s1released
+{
+  SELECT count(*) AS records FROM pg_backend_memory_contexts
+  WHERE name = 'partition descriptor record';
+  DROP TABLE pdr_records;
+}
+
+session s2
+step s2move
+{
+  ALTER TABLE pdr_range DETACH PARTITION pdr_range_1;
+  ALTER TABLE pdr_range ATTACH PARTITION pdr_range_1 FOR VALUES FROM (2000) TO (3000);
+}
+step s2drop		{ DROP TABLE pdr_range; }
+step s2add
+{
+  CREATE TABLE pdr_range_x1 PARTITION OF pdr_range FOR VALUES FROM (900) TO (1000);
+  CREATE TABLE pdr_range_x2 PARTITION OF pdr_range FOR VALUES FROM (700) TO (800);
+  CREATE TABLE pdr_range_x3 PARTITION OF pdr_range FOR VALUES FROM (500) TO (600);
+  CREATE TABLE pdr_list_x1 PARTITION OF pdr_list FOR VALUES IN (90);
+  CREATE TABLE pdr_list_x2 PARTITION OF pdr_list FOR VALUES IN (70);
+  CREATE TABLE pdr_list_x3 PARTITION OF pdr_list FOR VALUES IN (50);
+  CREATE TABLE pdr_hash_x31 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 31);
+  CREATE TABLE pdr_hash_x27 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 27);
+  CREATE TABLE pdr_hash_x23 PARTITION OF pdr_hash FOR VALUES WITH (MODULUS 32, REMAINDER 23);
+}
+
+permutation s1build s2add s1route
+permutation s1build s2move s1moved s1movedold s1movedcheck
+permutation s1record s1save s2move s1moved s1kept s2drop s1trivial s1released
diff --git a/src/test/regress/expected/partition_info.out b/src/test/regress/expected/partition_info.out
index 4defa66e5b3..cf72f135a72 100644
--- a/src/test/regress/expected/partition_info.out
+++ b/src/test/regress/expected/partition_info.out
@@ -356,3 +356,27 @@ CREATE TABLE p1 PARTITION OF pt FOR VALUES FROM (1) to (2) PARTITION BY RANGE (a
 CREATE TABLE p1_1 PARTITION OF p1 FOR VALUES FROM (1) TO (2);
 CREATE UNIQUE INDEX ON ONLY p1 (a);
 INSERT INTO p1 VALUES (1) ON CONFLICT (a) DO NOTHING;
+--
+-- A partition re-attached with another bound in the same session must be
+-- routed by its new bound (partition bounds are cached across rebuilds of the
+-- partition descriptor)
+--
+create table ptif_rebound (a int) partition by range (a);
+create table ptif_rebound1 partition of ptif_rebound for values from (0) to (10);
+create table ptif_rebound2 partition of ptif_rebound for values from (10) to (20);
+insert into ptif_rebound values (5), (15);
+alter table ptif_rebound detach partition ptif_rebound2;
+delete from ptif_rebound2;
+alter table ptif_rebound attach partition ptif_rebound2 for values from (100) to (200);
+insert into ptif_rebound values (150);
+insert into ptif_rebound values (15);  -- error
+ERROR:  no partition of relation "ptif_rebound" found for row
+DETAIL:  Partition key of the failing row contains (a) = (15).
+select tableoid::regclass, a from ptif_rebound order by a;
+   tableoid    |  a  
+---------------+-----
+ ptif_rebound1 |   5
+ ptif_rebound2 | 150
+(2 rows)
+
+drop table ptif_rebound;
diff --git a/src/test/regress/sql/partition_info.sql b/src/test/regress/sql/partition_info.sql
index 2ef65292bab..b189d5c1950 100644
--- a/src/test/regress/sql/partition_info.sql
+++ b/src/test/regress/sql/partition_info.sql
@@ -135,3 +135,20 @@ CREATE TABLE p1 PARTITION OF pt FOR VALUES FROM (1) to (2) PARTITION BY RANGE (a
 CREATE TABLE p1_1 PARTITION OF p1 FOR VALUES FROM (1) TO (2);
 CREATE UNIQUE INDEX ON ONLY p1 (a);
 INSERT INTO p1 VALUES (1) ON CONFLICT (a) DO NOTHING;
+
+--
+-- A partition re-attached with another bound in the same session must be
+-- routed by its new bound (partition bounds are cached across rebuilds of the
+-- partition descriptor)
+--
+create table ptif_rebound (a int) partition by range (a);
+create table ptif_rebound1 partition of ptif_rebound for values from (0) to (10);
+create table ptif_rebound2 partition of ptif_rebound for values from (10) to (20);
+insert into ptif_rebound values (5), (15);
+alter table ptif_rebound detach partition ptif_rebound2;
+delete from ptif_rebound2;
+alter table ptif_rebound attach partition ptif_rebound2 for values from (100) to (200);
+insert into ptif_rebound values (150);
+insert into ptif_rebound values (15);  -- error
+select tableoid::regclass, a from ptif_rebound order by a;
+drop table ptif_rebound;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194b..ab5f5b45442 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2184,10 +2184,12 @@ ParserState
 PartClauseInfo
 PartClauseMatchStatus
 PartClauseTarget
+PartDescRecord
 PartialFileSetState
 PartitionBoundInfo
 PartitionBoundInfoData
 PartitionBoundSpec
+PartitionBoundsHint
 PartitionCmd
 PartitionDesc
 PartitionDescData

base-commit: 8d90516d76dc0e0ab570096936f0b7083cf76346
-- 
2.56.1

