Patch
Fix ATTACH PARTITION adopting an invalid descendant index.
- Branch
- REL_18_STABLE
- Risk
- –
- Base commit
- 52cb12240cd02c2a435d6aee4f778e155b1ed77a
To apply it to a checkout of REL_18_STABLE at the base commit:
curl -s https://ai-annex.j-davis.com/api/v1/patches/01a1cbeb-fc60-7ae1-a5fc-404c72cc9b99 | jq -r .body | git am
From 0d41ba1acee143c20f00270db856e06f122ae7c5 Mon Sep 17 00:00:00 2001
From: Grok <grok@x.ai>
Date: Wed, 11 Nov 2026 10:29:13 -0800
Subject: [PATCH] Fix ATTACH PARTITION adopting an invalid descendant index.
ATTACH PARTITION of a partitioned table called DefineIndex, which
attached an invalid index defined ON ONLY a subpartition and cleared
indisvalid only on the index created for the attach. The already
valid parent index stayed valid, so uniqueness was not enforced, the
planner could remove joins incorrectly, and a later ALTER INDEX
ATTACH PARTITION of the missing leaf hit an assertion in
validatePartitionedIndex.
Complete an invalid partitioned index when attaching, building the
missing child indexes, and do not adopt an invalid leaf. CREATE
INDEX still attaches an invalid partition index and marks the new
parent invalid.
---
src/backend/commands/indexcmds.c | 354 ++++++++++++++++++++++++-
src/backend/commands/tablecmds.c | 16 +-
src/include/commands/defrem.h | 11 +
src/test/regress/expected/indexing.out | 28 ++
src/test/regress/sql/indexing.sql | 19 ++
5 files changed, 411 insertions(+), 17 deletions(-)
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index 2c05fd25a6f..095db6479d9 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -28,6 +28,8 @@
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
+#include "catalog/partition.h"
+#include "partitioning/partdesc.h"
#include "catalog/pg_am.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_collation.h"
@@ -119,6 +121,24 @@ static bool ReindexRelationConcurrently(const ReindexStmt *stmt,
const ReindexParams *params);
static void update_relispartition(Oid relationId, bool newval);
static inline void set_indexsafe_procflags(void);
+static ObjectAddress DefineIndexInternal(Oid tableId,
+ IndexStmt *stmt,
+ Oid indexRelationId,
+ Oid parentIndexId,
+ Oid parentConstraintId,
+ int total_parts,
+ bool is_alter_table,
+ bool check_rights,
+ bool check_not_in_use,
+ bool skip_build,
+ bool quiet,
+ bool skip_invalid);
+static bool completePartitionedIndex(Relation idxRel, Relation heapRel,
+ LOCKMODE lockmode,
+ Oid root_userid, int root_sec_context,
+ bool is_alter_table, bool check_rights,
+ bool check_not_in_use, bool skip_build,
+ bool quiet);
/*
* callback argument type for RangeVarCallbackForReindexIndex()
@@ -502,6 +522,224 @@ WaitForOlderSnapshots(TransactionId limitXmin, bool progress)
}
+/*
+ * Finish an invalid partitioned index by creating or attaching a valid
+ * index on every partition that does not yet have one. On success the
+ * index is marked valid and true is returned. Foreign partitions are
+ * skipped for a non-unique index, matching DefineIndex; a unique index
+ * on a tree that contains a foreign partition fails, also matching
+ * DefineIndex.
+ *
+ * The caller must not reuse this index when false is returned. Partial
+ * catalog changes are left for the caller to roll back.
+ */
+static bool
+completePartitionedIndex(Relation idxRel, Relation heapRel, LOCKMODE lockmode,
+ Oid root_userid, int root_sec_context,
+ bool is_alter_table, bool check_rights,
+ bool check_not_in_use, bool skip_build, bool quiet)
+{
+ PartitionDesc partdesc;
+ int nparts;
+ Oid *part_oids;
+ Oid idxOid = RelationGetRelid(idxRel);
+ Oid constraintOid;
+ IndexInfo *parentInfo;
+ TupleDesc parentDesc;
+ bool all_valid = true;
+
+ if (idxRel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
+ return false;
+
+ /* Catalog, not the possibly stale relcache flag. */
+ if (get_index_isvalid(RelationGetRelid(idxRel)))
+ return true;
+
+ partdesc = RelationGetPartitionDesc(heapRel, true);
+ nparts = partdesc->nparts;
+ if (nparts > 0)
+ {
+ part_oids = palloc_array(Oid, nparts);
+ memcpy(part_oids, partdesc->oids, sizeof(Oid) * nparts);
+ }
+ else
+ part_oids = NULL;
+
+ constraintOid = get_relation_idx_constraint_oid(RelationGetRelid(heapRel),
+ idxOid);
+ parentInfo = BuildIndexInfo(idxRel);
+ parentDesc = RelationGetDescr(heapRel);
+
+ for (int i = 0; i < nparts; i++)
+ {
+ Oid childRelid = part_oids[i];
+ Relation childrel;
+ Oid childIdxId;
+ List *childidxs;
+ ListCell *cell;
+ AttrMap *attmap;
+ bool found = false;
+
+ childrel = table_open(childRelid, lockmode);
+
+ if (childrel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
+ {
+ if (idxRel->rd_index->indisunique)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("cannot create unique index on partitioned table \"%s\"",
+ RelationGetRelationName(heapRel)),
+ errdetail("Table \"%s\" contains partitions that are foreign tables.",
+ RelationGetRelationName(heapRel))));
+
+ table_close(childrel, NoLock);
+ continue;
+ }
+
+ childIdxId = index_get_partition(childrel, idxOid);
+ if (OidIsValid(childIdxId))
+ {
+ if (!get_index_isvalid(childIdxId))
+ {
+ Relation childIdx = index_open(childIdxId, lockmode);
+ bool ok = false;
+
+ if (childIdx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+ ok = completePartitionedIndex(childIdx, childrel, lockmode,
+ root_userid, root_sec_context,
+ is_alter_table, check_rights,
+ check_not_in_use, skip_build,
+ quiet);
+ index_close(childIdx, NoLock);
+ if (!ok)
+ all_valid = false;
+ }
+
+ table_close(childrel, NoLock);
+ if (!all_valid)
+ break;
+ continue;
+ }
+
+ childidxs = RelationGetIndexList(childrel);
+ attmap = build_attrmap_by_name(RelationGetDescr(childrel),
+ parentDesc,
+ false);
+
+ foreach(cell, childidxs)
+ {
+ Oid cldidxid = lfirst_oid(cell);
+ Relation cldidx;
+ IndexInfo *cldIdxInfo;
+ Oid cldConstrOid = InvalidOid;
+
+ if (has_superclass(cldidxid))
+ continue;
+
+ cldidx = index_open(cldidxid, lockmode);
+ cldIdxInfo = BuildIndexInfo(cldidx);
+ if (!CompareIndexInfo(cldIdxInfo, parentInfo,
+ cldidx->rd_indcollation,
+ idxRel->rd_indcollation,
+ cldidx->rd_opfamily,
+ idxRel->rd_opfamily,
+ attmap))
+ {
+ index_close(cldidx, lockmode);
+ continue;
+ }
+
+ if (OidIsValid(constraintOid))
+ {
+ cldConstrOid = get_relation_idx_constraint_oid(childRelid,
+ cldidxid);
+ if (!OidIsValid(cldConstrOid))
+ {
+ index_close(cldidx, lockmode);
+ continue;
+ }
+ }
+
+ if (!cldidx->rd_index->indisvalid)
+ {
+ bool completed = false;
+
+ if (cldidx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+ completed = completePartitionedIndex(cldidx, childrel,
+ lockmode, root_userid,
+ root_sec_context,
+ is_alter_table,
+ check_rights,
+ check_not_in_use,
+ skip_build, quiet);
+ if (!completed || !get_index_isvalid(cldidxid))
+ {
+ index_close(cldidx, lockmode);
+ continue;
+ }
+ }
+
+ IndexSetParentIndex(cldidx, idxOid);
+ if (OidIsValid(constraintOid))
+ ConstraintSetParentConstraint(cldConstrOid, constraintOid,
+ childRelid);
+ found = true;
+ index_close(cldidx, NoLock);
+ break;
+ }
+
+ list_free(childidxs);
+
+ if (!found)
+ {
+ IndexStmt *childStmt;
+ ObjectAddress childAddr;
+ Oid save_userid;
+ int save_sec_context;
+
+ childStmt = generateClonedIndexStmt(NULL, idxRel, attmap, NULL);
+
+ GetUserIdAndSecContext(&save_userid, &save_sec_context);
+ SetUserIdAndSecContext(root_userid, root_sec_context);
+ childAddr = DefineIndexInternal(childRelid, childStmt,
+ InvalidOid,
+ idxOid,
+ constraintOid,
+ -1,
+ is_alter_table, check_rights,
+ check_not_in_use,
+ skip_build, quiet,
+ true);
+ SetUserIdAndSecContext(save_userid, save_sec_context);
+
+ if (!get_index_isvalid(childAddr.objectId))
+ all_valid = false;
+ }
+
+ free_attrmap(attmap);
+ table_close(childrel, NoLock);
+
+ if (!all_valid)
+ break;
+ }
+
+ if (!all_valid)
+ return false;
+
+ /*
+ * Every non-foreign partition now has a valid index attached here.
+ * indisready is already set for an index created with ON ONLY.
+ */
+ CommandCounterIncrement();
+ if (!get_index_isvalid(idxOid))
+ {
+ index_set_state_flags(idxOid, INDEX_CREATE_SET_VALID);
+ CommandCounterIncrement();
+ }
+
+ return true;
+}
+
/*
* DefineIndex
* Creates a new index.
@@ -553,6 +791,49 @@ DefineIndex(Oid tableId,
bool check_not_in_use,
bool skip_build,
bool quiet)
+{
+ return DefineIndexInternal(tableId, stmt, indexRelationId, parentIndexId, parentConstraintId, total_parts, is_alter_table, check_rights, check_not_in_use, skip_build, quiet, false);
+}
+
+/*
+ * DefineIndex, but do not adopt an invalid index on a partition.
+ *
+ * ALTER TABLE ATTACH PARTITION uses this. The parent index already
+ * exists and is valid; attaching an invalid descendant would leave that
+ * parent valid over a subtree that does not enforce it. An invalid
+ * partitioned index is completed when its missing pieces can be built.
+ * CREATE INDEX keeps the historical behavior of attaching the invalid
+ * index and marking the new parent invalid, via DefineIndex.
+ */
+ObjectAddress
+DefineIndexSkipInvalid(Oid tableId,
+ IndexStmt *stmt,
+ Oid indexRelationId,
+ Oid parentIndexId,
+ Oid parentConstraintId,
+ int total_parts,
+ bool is_alter_table,
+ bool check_rights,
+ bool check_not_in_use,
+ bool skip_build,
+ bool quiet)
+{
+ return DefineIndexInternal(tableId, stmt, indexRelationId, parentIndexId, parentConstraintId, total_parts, is_alter_table, check_rights, check_not_in_use, skip_build, quiet, true);
+}
+
+static ObjectAddress
+DefineIndexInternal(Oid tableId,
+ IndexStmt *stmt,
+ Oid indexRelationId,
+ Oid parentIndexId,
+ Oid parentConstraintId,
+ int total_parts,
+ bool is_alter_table,
+ bool check_rights,
+ bool check_not_in_use,
+ bool skip_build,
+ bool quiet,
+ bool skip_invalid)
{
bool concurrent;
char *indexRelationName;
@@ -1475,6 +1756,42 @@ DefineIndex(Oid tableId,
}
}
+ /*
+ * CREATE INDEX attaches an invalid match and clears
+ * indisvalid on the index being built. That is wrong
+ * for ATTACH PARTITION (skip_invalid): the parent
+ * index already exists and would stay valid over an
+ * incomplete subtree. Finish an invalid partitioned
+ * index when its missing pieces can be built;
+ * otherwise ignore it and build a new one.
+ */
+ if (!get_index_isvalid(cldidxid))
+ {
+ bool completed = false;
+
+ if (skip_invalid &&
+ cldidx->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
+ completed = completePartitionedIndex(cldidx,
+ childrel,
+ lockmode,
+ root_save_userid,
+ root_save_sec_context,
+ is_alter_table,
+ check_rights,
+ check_not_in_use,
+ skip_build,
+ quiet);
+
+ if (skip_invalid && !completed)
+ {
+ index_close(cldidx, lockmode);
+ continue;
+ }
+
+ if (!skip_invalid)
+ invalidate_parent = true;
+ }
+
/* Attach index to parent and we're done. */
IndexSetParentIndex(cldidx, indexRelationId);
if (createdConstraintId != InvalidOid)
@@ -1482,9 +1799,6 @@ DefineIndex(Oid tableId,
createdConstraintId,
childRelid);
- if (!cldidx->rd_index->indisvalid)
- invalidate_parent = true;
-
found = true;
/*
@@ -1540,14 +1854,15 @@ DefineIndex(Oid tableId,
SetUserIdAndSecContext(root_save_userid,
root_save_sec_context);
childAddr =
- DefineIndex(childRelid, childStmt,
- InvalidOid, /* no predefined OID */
- indexRelationId, /* this is our child */
- createdConstraintId,
- -1,
- is_alter_table, check_rights,
- check_not_in_use,
- skip_build, quiet);
+ DefineIndexInternal(childRelid, childStmt,
+ InvalidOid, /* no predefined OID */
+ indexRelationId, /* this is our child */
+ createdConstraintId,
+ -1,
+ is_alter_table, check_rights,
+ check_not_in_use,
+ skip_build, quiet,
+ skip_invalid);
SetUserIdAndSecContext(child_save_userid,
child_save_sec_context);
@@ -1572,10 +1887,25 @@ DefineIndex(Oid tableId,
*/
if (invalidate_parent)
{
- Relation pg_index = table_open(IndexRelationId, RowExclusiveLock);
+ Relation pg_index;
HeapTuple tup,
newtup;
+ /*
+ * ATTACH PARTITION must not record an invalid index under a
+ * parent that is already valid. Fail instead of clearing
+ * indisvalid only on the index created for the attach.
+ */
+ if (skip_invalid)
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+ errmsg("cannot build a valid index on partitioned table \"%s\"",
+ RelationGetRelationName(rel)),
+ errdetail("A partition index is invalid, and no valid replacement could be built."),
+ errhint("Repair or drop invalid indexes on the partitions, then retry.")));
+
+ pg_index = table_open(IndexRelationId, RowExclusiveLock);
+
tup = SearchSysCache1(INDEXRELID,
ObjectIdGetDatum(indexRelationId));
if (!HeapTupleIsValid(tup))
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index fe5982e1600..1be163d9d86 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -21478,11 +21478,17 @@ AttachPartitionEnsureIndexes(List **wqueue, Relation rel, Relation attachrel)
stmt = generateClonedIndexStmt(NULL,
idxRel, attmap,
&conOid);
- DefineIndex(RelationGetRelid(attachrel), stmt, InvalidOid,
- RelationGetRelid(idxRel),
- conOid,
- -1,
- true, false, false, false, false);
+
+ /*
+ * Do not reuse an invalid index on a subpartition. DefineIndex
+ * would attach it and clear indisvalid only on the index created
+ * here, leaving this parent index valid over an incomplete tree.
+ */
+ DefineIndexSkipInvalid(RelationGetRelid(attachrel), stmt, InvalidOid,
+ RelationGetRelid(idxRel),
+ conOid,
+ -1,
+ true, false, false, false, false);
}
index_close(idxRel, AccessShareLock);
diff --git a/src/include/commands/defrem.h b/src/include/commands/defrem.h
index fff772a720d..a3fe0ae778d 100644
--- a/src/include/commands/defrem.h
+++ b/src/include/commands/defrem.h
@@ -36,6 +36,17 @@ extern ObjectAddress DefineIndex(Oid tableId,
bool check_not_in_use,
bool skip_build,
bool quiet);
+extern ObjectAddress DefineIndexSkipInvalid(Oid tableId,
+ IndexStmt *stmt,
+ Oid indexRelationId,
+ Oid parentIndexId,
+ Oid parentConstraintId,
+ int total_parts,
+ bool is_alter_table,
+ bool check_rights,
+ bool check_not_in_use,
+ bool skip_build,
+ bool quiet);
extern void ExecReindex(ParseState *pstate, const ReindexStmt *stmt, bool isTopLevel);
extern char *makeObjectName(const char *name1, const char *name2,
const char *label);
diff --git a/src/test/regress/expected/indexing.out b/src/test/regress/expected/indexing.out
index 3e1bbfb74af..88fc749ed95 100644
--- a/src/test/regress/expected/indexing.out
+++ b/src/test/regress/expected/indexing.out
@@ -1661,6 +1661,34 @@ select indexrelid::regclass, indisvalid,
(5 rows)
drop table parted_inval_tab;
+-- An invalid index on a subpartition must not leave the parent's index
+-- valid. Completing that index builds the missing leaf index.
+create table inval_sub_tab (a int primary key) partition by list (a);
+create table inval_sub_tab_1 (a int not null) partition by list (a);
+create table inval_sub_tab_11 partition of inval_sub_tab_1 for values in (1)
+ partition by list (a);
+create table inval_sub_tab_111 partition of inval_sub_tab_11 for values in (1);
+alter table only inval_sub_tab_11 add primary key (a);
+alter table inval_sub_tab attach partition inval_sub_tab_1 for values in (1);
+select indexrelid::regclass, indisvalid,
+ indrelid::regclass, inhparent::regclass
+ from pg_index idx left join
+ pg_inherits inh on (idx.indexrelid = inh.inhrelid)
+ where indexrelid::regclass::text like 'inval_sub%'
+ order by indexrelid::regclass::text collate "C";
+ indexrelid | indisvalid | indrelid | inhparent
+------------------------+------------+-------------------+-----------------------
+ inval_sub_tab_111_pkey | t | inval_sub_tab_111 | inval_sub_tab_11_pkey
+ inval_sub_tab_11_pkey | t | inval_sub_tab_11 | inval_sub_tab_1_pkey
+ inval_sub_tab_1_pkey | t | inval_sub_tab_1 | inval_sub_tab_pkey
+ inval_sub_tab_pkey | t | inval_sub_tab |
+(4 rows)
+
+insert into inval_sub_tab values (1);
+insert into inval_sub_tab values (1);
+ERROR: duplicate key value violates unique constraint "inval_sub_tab_111_pkey"
+DETAIL: Key (a)=(1) already exists.
+drop table inval_sub_tab;
-- Check setup of indisvalid across a complex partition tree on index
-- creation. If one index in a partition index is invalid, so should its
-- partitioned index.
diff --git a/src/test/regress/sql/indexing.sql b/src/test/regress/sql/indexing.sql
index 0f302f07a3f..7aba9429c02 100644
--- a/src/test/regress/sql/indexing.sql
+++ b/src/test/regress/sql/indexing.sql
@@ -909,6 +909,25 @@ select indexrelid::regclass, indisvalid,
order by indexrelid::regclass::text collate "C";
drop table parted_inval_tab;
+-- An invalid index on a subpartition must not leave the parent's index
+-- valid. Completing that index builds the missing leaf index.
+create table inval_sub_tab (a int primary key) partition by list (a);
+create table inval_sub_tab_1 (a int not null) partition by list (a);
+create table inval_sub_tab_11 partition of inval_sub_tab_1 for values in (1)
+ partition by list (a);
+create table inval_sub_tab_111 partition of inval_sub_tab_11 for values in (1);
+alter table only inval_sub_tab_11 add primary key (a);
+alter table inval_sub_tab attach partition inval_sub_tab_1 for values in (1);
+select indexrelid::regclass, indisvalid,
+ indrelid::regclass, inhparent::regclass
+ from pg_index idx left join
+ pg_inherits inh on (idx.indexrelid = inh.inhrelid)
+ where indexrelid::regclass::text like 'inval_sub%'
+ order by indexrelid::regclass::text collate "C";
+insert into inval_sub_tab values (1);
+insert into inval_sub_tab values (1);
+drop table inval_sub_tab;
+
-- Check setup of indisvalid across a complex partition tree on index
-- creation. If one index in a partition index is invalid, so should its
-- partitioned index.
base-commit: 52cb12240cd02c2a435d6aee4f778e155b1ed77a
--
2.53.0