Patch
Don't let a stale concurrent detach finalize a newer one
- Branch
- master
- Risk
- 38
- Base commit
- 458c77d74d2bab2014e97f01df19dc805dc7b42a
To apply it to a checkout of master at the base commit:
curl -s https://ai-annex.j-davis.com/api/v1/patches/01a232f2-8f0a-75c6-86ab-1a038e229f3a | jq -r .body | git am
From 80ac60413dbae53ff6c2cc0c8f9e9a5def696736 Mon Sep 17 00:00:00 2001
From: Claude <noreply@anthropic.com>
Date: Tue, 1 Dec 2026 10:47:29 -0800
Subject: [PATCH] Don't let a stale concurrent detach finalize a newer one
ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY marks the partition
as pending detach and commits, and then in a second transaction waits
for the transactions holding locks on the parent table before it
completes the detach. It holds no locks while it waits, and
afterwards it only verified that the partition is still marked as
pending detach. But in the meantime another session can complete the
detach with DETACH PARTITION ... FINALIZE, attach the partition to the
same parent again, and start a new concurrent detach of it. The first
session then found the partition pending detach, just as it had left
it, and completed the newer detach, even though it had not waited for
the transactions that started after the partition was attached again.
Such a transaction can still be routing tuples into the partition
according to the partition descriptor it built before the newer
detach. If the partition is then attached to a different table, or
with a different bound, a tuple that violates the new partition
constraint can be inserted into it, since routed tuples are not
checked against the partition constraint.
To fix, remember the XID of the transaction that marked the partition
as pending detach, and have the second transaction verify that the
xmin of the pg_inherits row still matches it before completing the
detach. The row is updated only when it is marked, so a different
xmin means that the pending detach belongs to some other command;
raise an error in that case, as we already do when the partition is
found not to be pending detach anymore. The newer detach is left
alone, to be completed by its own command or with FINALIZE.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---
src/backend/commands/tablecmds.c | 74 +++++++++++++++++++
.../detach-partition-concurrently-5.out | 53 +++++++++++++
src/test/isolation/isolation_schedule | 1 +
.../detach-partition-concurrently-5.spec | 58 +++++++++++++++
4 files changed, 186 insertions(+)
create mode 100644 src/test/isolation/expected/detach-partition-concurrently-5.out
create mode 100644 src/test/isolation/specs/detach-partition-concurrently-5.spec
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9755943f110..ca0ec251589 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -19261,6 +19261,64 @@ MarkInheritDetached(Relation child_rel, Relation parent_rel)
RelationGetRelationName(parent_rel))));
}
+/*
+ * CheckPendingDetachIsOurs
+ *
+ * Subroutine for the second transaction of ATExecDetachPartition in
+ * concurrent mode: verify that a pending detach of the partition is the one
+ * that was started by our own first transaction, whose XID is detach_xid.
+ *
+ * No lock was held on either relation between the two transactions, so the
+ * detach we started could have been completed by somebody else with DETACH
+ * PARTITION ... FINALIZE, after which the partition could have been attached
+ * to the same parent again and a new concurrent detach started. In that
+ * case the pg_inherits row looks exactly as we left it, but it's not ours to
+ * finalize: the transactions that the newer detach has to wait for didn't
+ * necessarily exist when we determined whom to wait for. The row is only
+ * ever updated by MarkInheritDetached, so its xmin identifies the command
+ * that marked it.
+ *
+ * If there is no such row, or it isn't marked as pending detach, we do
+ * nothing here and let RemoveInheritance complain about it.
+ */
+static void
+CheckPendingDetachIsOurs(Relation child_rel, Relation parent_rel,
+ TransactionId detach_xid)
+{
+ Relation catalogRelation;
+ SysScanDesc scan;
+ ScanKeyData key;
+ HeapTuple inheritsTuple;
+
+ catalogRelation = table_open(InheritsRelationId, AccessShareLock);
+ ScanKeyInit(&key,
+ Anum_pg_inherits_inhrelid,
+ BTEqualStrategyNumber, F_OIDEQ,
+ ObjectIdGetDatum(RelationGetRelid(child_rel)));
+ scan = systable_beginscan(catalogRelation, InheritsRelidSeqnoIndexId,
+ true, NULL, 1, &key);
+
+ while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan)))
+ {
+ Form_pg_inherits inhForm;
+
+ inhForm = (Form_pg_inherits) GETSTRUCT(inheritsTuple);
+ if (inhForm->inhparent == RelationGetRelid(parent_rel) &&
+ inhForm->inhdetachpending &&
+ !TransactionIdEquals(HeapTupleHeaderGetRawXmin(inheritsTuple->t_data),
+ detach_xid))
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("partition \"%s\" was detached concurrently",
+ RelationGetRelationName(child_rel)),
+ errdetail("The partition was attached to partitioned table \"%s\" again and is pending detach by another command.",
+ RelationGetRelationName(parent_rel)));
+ }
+
+ systable_endscan(scan);
+ table_close(catalogRelation, AccessShareLock);
+}
+
/*
* RemoveInheritance
*
@@ -22396,6 +22454,7 @@ ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
{
Oid partrelid,
parentrelid;
+ TransactionId detachxid;
LOCKTAG tag;
char *parentrelname;
char *partrelname;
@@ -22418,6 +22477,13 @@ ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
partrelname = MemoryContextStrdup(PortalContext,
RelationGetRelationName(partRel));
+ /*
+ * Also remember the XID that marked the partition as pending detach,
+ * so that the second transaction can tell whether a pending detach it
+ * finds is still this one.
+ */
+ detachxid = GetCurrentTransactionId();
+
/* Invalidate relcache entries for the parent -- must be before close */
CacheInvalidateRelcache(rel);
@@ -22466,6 +22532,14 @@ ATExecDetachPartition(List **wqueue, AlteredTableInfo *tab, Relation rel,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("partition \"%s\" was removed concurrently", partrelname)));
+ /*
+ * We held no locks while waiting, so the detach we started might have
+ * been finalized by someone else, and the partition attached again
+ * and marked as pending detach by a newer command. We haven't waited
+ * for what that one needs to wait for, so don't finalize it.
+ */
+ CheckPendingDetachIsOurs(partRel, rel, detachxid);
+
tab->rel = rel;
}
diff --git a/src/test/isolation/expected/detach-partition-concurrently-5.out b/src/test/isolation/expected/detach-partition-concurrently-5.out
new file mode 100644
index 00000000000..d2de22d6fb3
--- /dev/null
+++ b/src/test/isolation/expected/detach-partition-concurrently-5.out
@@ -0,0 +1,53 @@
+Parsed test spec with 5 sessions
+
+starting permutation: s3lock s1detach s2finalize s2attach s5lock s4insert s2detach s3commit s5attach s5unlock s5check
+step s3lock: BEGIN; LOCK TABLE ONLY d5_parent IN ACCESS SHARE MODE;
+step s1detach: ALTER TABLE d5_parent DETACH PARTITION d5_part1 CONCURRENTLY; <waiting ...>
+step s2finalize: ALTER TABLE d5_parent DETACH PARTITION d5_part1 FINALIZE;
+step s2attach: ALTER TABLE d5_parent ATTACH PARTITION d5_part1 FOR VALUES IN (1);
+step s5lock: SELECT pg_advisory_lock(5);
+pg_advisory_lock
+----------------
+
+(1 row)
+
+step s4insert:
+ INSERT INTO d5_parent
+ SELECT v FROM (VALUES (2), (1)) t(v)
+ WHERE v = 2 OR pg_advisory_xact_lock(5) IS NOT NULL
+ RETURNING tableoid::regclass, a;
+ <waiting ...>
+step s2detach: ALTER TABLE d5_parent DETACH PARTITION d5_part1 CONCURRENTLY; <waiting ...>
+step s3commit: COMMIT;
+step s1detach: <... completed>
+ERROR: partition "d5_part1" was detached concurrently
+step s5attach: ALTER TABLE d5_other ATTACH PARTITION d5_part1 FOR VALUES IN (3);
+ERROR: "d5_part1" is already a partition
+step s5unlock: SELECT pg_advisory_unlock(5);
+pg_advisory_unlock
+------------------
+t
+(1 row)
+
+step s4insert: <... completed>
+tableoid|a
+--------+-
+d5_part2|2
+d5_part1|1
+(2 rows)
+
+step s2detach: <... completed>
+step s5check:
+ SELECT inhparent::regclass, inhdetachpending FROM pg_inherits
+ WHERE inhrelid = 'd5_part1'::regclass;
+ SELECT tableoid::regclass, a FROM d5_part1;
+
+inhparent|inhdetachpending
+---------+----------------
+(0 rows)
+
+tableoid|a
+--------+-
+d5_part1|1
+(1 row)
+
diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule
index 2de19ea634f..ed1ff7fe65a 100644
--- a/src/test/isolation/isolation_schedule
+++ b/src/test/isolation/isolation_schedule
@@ -29,6 +29,7 @@ test: detach-partition-concurrently-1
test: detach-partition-concurrently-2
test: detach-partition-concurrently-3
test: detach-partition-concurrently-4
+test: detach-partition-concurrently-5
test: fk-contention
test: fk-deadlock
test: fk-deadlock2
diff --git a/src/test/isolation/specs/detach-partition-concurrently-5.spec b/src/test/isolation/specs/detach-partition-concurrently-5.spec
new file mode 100644
index 00000000000..ca650d9a153
--- /dev/null
+++ b/src/test/isolation/specs/detach-partition-concurrently-5.spec
@@ -0,0 +1,58 @@
+# Test that the second transaction of DETACH PARTITION CONCURRENTLY does
+# not complete a pending detach that was started by some other session.
+#
+# s1 starts a concurrent detach and waits for s3 in its second
+# transaction. Meanwhile s2 finalizes that detach, attaches the partition
+# again and starts a new concurrent detach, which has to wait for the
+# INSERT of s4 (which is stuck on an advisory lock held by s5). When s3
+# commits, s1 must not finish s2's detach, because it has not waited for
+# s4. If it did, the partition could be attached elsewhere while s4 can
+# still route tuples into it.
+
+setup
+{
+ CREATE TABLE d5_parent (a int) PARTITION BY LIST (a);
+ CREATE TABLE d5_part1 PARTITION OF d5_parent FOR VALUES IN (1);
+ CREATE TABLE d5_part2 PARTITION OF d5_parent FOR VALUES IN (2);
+ CREATE TABLE d5_other (a int) PARTITION BY LIST (a);
+}
+
+teardown
+{
+ DROP TABLE IF EXISTS d5_parent, d5_part1, d5_part2, d5_other;
+}
+
+session s1
+step s1detach { ALTER TABLE d5_parent DETACH PARTITION d5_part1 CONCURRENTLY; }
+
+session s2
+step s2finalize { ALTER TABLE d5_parent DETACH PARTITION d5_part1 FINALIZE; }
+step s2attach { ALTER TABLE d5_parent ATTACH PARTITION d5_part1 FOR VALUES IN (1); }
+step s2detach { ALTER TABLE d5_parent DETACH PARTITION d5_part1 CONCURRENTLY; }
+
+session s3
+step s3lock { BEGIN; LOCK TABLE ONLY d5_parent IN ACCESS SHARE MODE; }
+step s3commit { COMMIT; }
+
+session s4
+# The tuple for d5_part2 is routed first; the one for d5_part1 is routed
+# only after the advisory lock is released.
+step s4insert {
+ INSERT INTO d5_parent
+ SELECT v FROM (VALUES (2), (1)) t(v)
+ WHERE v = 2 OR pg_advisory_xact_lock(5) IS NOT NULL
+ RETURNING tableoid::regclass, a;
+}
+
+session s5
+step s5lock { SELECT pg_advisory_lock(5); }
+step s5unlock { SELECT pg_advisory_unlock(5); }
+step s5attach { ALTER TABLE d5_other ATTACH PARTITION d5_part1 FOR VALUES IN (3); }
+step s5check {
+ SELECT inhparent::regclass, inhdetachpending FROM pg_inherits
+ WHERE inhrelid = 'd5_part1'::regclass;
+ SELECT tableoid::regclass, a FROM d5_part1;
+}
+
+permutation s3lock s1detach s2finalize s2attach s5lock s4insert s2detach(s4insert)
+ s3commit s5attach s5unlock s5check
base-commit: 458c77d74d2bab2014e97f01df19dc805dc7b42a
--
2.53.0