agora inbox for [email protected]  
help / color / mirror / Atom feed
[PATCH v49 7/7] WIP add max_repack_replication_slots
63+ messages / 1 participants
[nested] [flat]

* [PATCH v49 7/7] WIP add max_repack_replication_slots
@ 2026-04-01 17:54  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-01 17:54 UTC (permalink / raw)

---
 src/backend/commands/repack_worker.c          |  4 +-
 src/backend/replication/logical/launcher.c    |  2 +-
 src/backend/replication/logical/slotsync.c    |  5 +-
 src/backend/replication/slot.c                | 77 +++++++++++--------
 src/backend/replication/slotfuncs.c           |  8 +-
 src/backend/replication/walsender.c           |  4 +-
 src/backend/utils/misc/guc_parameters.dat     |  8 ++
 src/backend/utils/misc/postgresql.conf.sample |  2 +
 src/include/replication/slot.h                |  6 +-
 9 files changed, 74 insertions(+), 42 deletions(-)

diff --git a/src/backend/commands/repack_worker.c b/src/backend/commands/repack_worker.c
index 106b2b60441..00b21ede481 100644
--- a/src/backend/commands/repack_worker.c
+++ b/src/backend/commands/repack_worker.c
@@ -228,8 +228,8 @@ repack_setup_logical_decoding(Oid relid)
 	 * RS_TEMPORARY so that the slot gets cleaned up on ERROR.
 	 */
 	snprintf(NameStr(slotname), NAMEDATALEN, "repack_%d", MyProcPid);
-	ReplicationSlotCreate(NameStr(slotname), true, RS_TEMPORARY, false, false,
-						  false);
+	ReplicationSlotCreate(NameStr(slotname), true, RS_TEMPORARY, false, true,
+						  false, false);
 
 	EnsureLogicalDecodingEnabled();
 
diff --git a/src/backend/replication/logical/launcher.c b/src/backend/replication/logical/launcher.c
index 09964198550..d83125afd0d 100644
--- a/src/backend/replication/logical/launcher.c
+++ b/src/backend/replication/logical/launcher.c
@@ -1575,7 +1575,7 @@ CreateConflictDetectionSlot(void)
 			errmsg("creating replication conflict detection slot"));
 
 	ReplicationSlotCreate(CONFLICT_DETECTION_SLOT, false, RS_PERSISTENT, false,
-						  false, false);
+						  false, false, false);
 
 	init_conflict_slot_xmin();
 }
diff --git a/src/backend/replication/logical/slotsync.c b/src/backend/replication/logical/slotsync.c
index e75db69e3f6..1bc7f3f600d 100644
--- a/src/backend/replication/logical/slotsync.c
+++ b/src/backend/replication/logical/slotsync.c
@@ -425,7 +425,7 @@ get_local_synced_slots(void)
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
 
-	for (int i = 0; i < max_replication_slots; i++)
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
@@ -814,6 +814,7 @@ synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid,
 		 */
 		ReplicationSlotCreate(remote_slot->name, true, RS_TEMPORARY,
 							  remote_slot->two_phase,
+							  false,
 							  remote_slot->failover,
 							  true);
 
@@ -1691,7 +1692,7 @@ update_synced_slots_inactive_since(void)
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
 
-	for (int i = 0; i < max_replication_slots; i++)
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c
index a9092fc2382..fe6bfeba25e 100644
--- a/src/backend/replication/slot.c
+++ b/src/backend/replication/slot.c
@@ -151,6 +151,9 @@ ReplicationSlot *MyReplicationSlot = NULL;
 /* GUC variables */
 int			max_replication_slots = 10; /* the maximum number of replication
 										 * slots */
+int			max_repack_replication_slots = 1;	/* the maximum number of slots
+												 * for REPACK */
+int			TotalMaxReplicationSlots = 0;	/* sum of both */
 
 /*
  * Invalidate replication slots that have remained idle longer than this
@@ -190,12 +193,14 @@ ReplicationSlotsShmemSize(void)
 {
 	Size		size = 0;
 
-	if (max_replication_slots == 0)
+	TotalMaxReplicationSlots = max_replication_slots + max_repack_replication_slots;
+
+	if (TotalMaxReplicationSlots == 0)
 		return size;
 
 	size = offsetof(ReplicationSlotCtlData, replication_slots);
 	size = add_size(size,
-					mul_size(max_replication_slots, sizeof(ReplicationSlot)));
+					mul_size(TotalMaxReplicationSlots, sizeof(ReplicationSlot)));
 
 	return size;
 }
@@ -208,7 +213,7 @@ ReplicationSlotsShmemInit(void)
 {
 	bool		found;
 
-	if (max_replication_slots == 0)
+	if (TotalMaxReplicationSlots == 0)
 		return;
 
 	ReplicationSlotCtl = (ReplicationSlotCtlData *)
@@ -222,7 +227,7 @@ ReplicationSlotsShmemInit(void)
 		/* First time through, so initialize */
 		MemSet(ReplicationSlotCtl, 0, ReplicationSlotsShmemSize());
 
-		for (i = 0; i < max_replication_slots; i++)
+		for (i = 0; i < TotalMaxReplicationSlots; i++)
 		{
 			ReplicationSlot *slot = &ReplicationSlotCtl->replication_slots[i];
 
@@ -372,6 +377,7 @@ IsSlotForConflictCheck(const char *name)
  * db_specific: logical decoding is db specific; if the slot is going to
  *	   be used for that pass true, otherwise false.
  * two_phase: If enabled, allows decoding of prepared transactions.
+ * repack: If true, use a slot from the pool for REPACK.
  * failover: If enabled, allows the slot to be synced to standbys so
  *     that logical replication can be resumed after failover.
  * synced: True if the slot is synchronized from the primary server.
@@ -379,10 +385,11 @@ IsSlotForConflictCheck(const char *name)
 void
 ReplicationSlotCreate(const char *name, bool db_specific,
 					  ReplicationSlotPersistency persistency,
-					  bool two_phase, bool failover, bool synced)
+					  bool two_phase, bool repack, bool failover, bool synced)
 {
 	ReplicationSlot *slot = NULL;
-	int			i;
+	int			startpoint,
+				endpoint;
 
 	Assert(MyReplicationSlot == NULL);
 
@@ -431,12 +438,16 @@ ReplicationSlotCreate(const char *name, bool db_specific,
 	LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
 
 	/*
-	 * Check for name collision, and identify an allocatable slot.  We need to
-	 * hold ReplicationSlotControlLock in shared mode for this, so that nobody
-	 * else can change the in_use flags while we're looking at them.
+	 * Check for name collision (across the whole array), and identify an
+	 * allocatable slot (in the array slice specific to our current use case:
+	 * either general, or REPACK only).  We need to hold
+	 * ReplicationSlotControlLock in shared mode for this, so that nobody else
+	 * can change the in_use flags while we're looking at them.
 	 */
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (i = 0; i < max_replication_slots; i++)
+	startpoint = repack ? max_replication_slots : 0;
+	endpoint = repack ? TotalMaxReplicationSlots : max_replication_slots;
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
@@ -444,7 +455,9 @@ ReplicationSlotCreate(const char *name, bool db_specific,
 			ereport(ERROR,
 					(errcode(ERRCODE_DUPLICATE_OBJECT),
 					 errmsg("replication slot \"%s\" already exists", name)));
-		if (!s->in_use && slot == NULL)
+
+		if (i >= startpoint && i < endpoint &&
+			!s->in_use && slot == NULL)
 			slot = s;
 	}
 	LWLockRelease(ReplicationSlotControlLock);
@@ -547,7 +560,7 @@ SearchNamedReplicationSlot(const char *name, bool need_lock)
 	if (need_lock)
 		LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
 
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
@@ -575,7 +588,7 @@ int
 ReplicationSlotIndex(ReplicationSlot *slot)
 {
 	Assert(slot >= ReplicationSlotCtl->replication_slots &&
-		   slot < ReplicationSlotCtl->replication_slots + max_replication_slots);
+		   slot < ReplicationSlotCtl->replication_slots + TotalMaxReplicationSlots);
 
 	return slot - ReplicationSlotCtl->replication_slots;
 }
@@ -869,7 +882,7 @@ ReplicationSlotCleanup(bool synced_only)
 restart:
 	found_valid_logicalslot = false;
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
@@ -1251,7 +1264,7 @@ ReplicationSlotsComputeRequiredXmin(bool already_locked)
 	if (!already_locked)
 		LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
 
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 		TransactionId effective_xmin;
@@ -1306,7 +1319,7 @@ ReplicationSlotsComputeRequiredLSN(void)
 	Assert(ReplicationSlotCtl != NULL);
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 		XLogRecPtr	restart_lsn;
@@ -1373,12 +1386,12 @@ ReplicationSlotsComputeLogicalRestartLSN(void)
 	XLogRecPtr	result = InvalidXLogRecPtr;
 	int			i;
 
-	if (max_replication_slots <= 0)
+	if (TotalMaxReplicationSlots <= 0)
 		return InvalidXLogRecPtr;
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
 
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s;
 		XLogRecPtr	restart_lsn;
@@ -1453,11 +1466,11 @@ ReplicationSlotsCountDBSlots(Oid dboid, int *nslots, int *nactive)
 
 	*nslots = *nactive = 0;
 
-	if (max_replication_slots <= 0)
+	if (TotalMaxReplicationSlots <= 0)
 		return false;
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s;
 
@@ -1514,13 +1527,13 @@ ReplicationSlotsDropDBSlots(Oid dboid)
 	bool		found_valid_logicalslot;
 	bool		dropped = false;
 
-	if (max_replication_slots <= 0)
+	if (TotalMaxReplicationSlots <= 0)
 		return;
 
 restart:
 	found_valid_logicalslot = false;
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s;
 		char	   *slotname;
@@ -1617,11 +1630,11 @@ CheckLogicalSlotExists(void)
 {
 	bool		found = false;
 
-	if (max_replication_slots <= 0)
+	if (TotalMaxReplicationSlots <= 0)
 		return false;
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (int i = 0; i < max_replication_slots; i++)
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s;
 		bool		invalidated;
@@ -1662,7 +1675,10 @@ CheckSlotRequirements(void)
 	 * needs the same check.
 	 */
 
-	if (max_replication_slots == 0)
+	/* FIXME how to relax this for repack in a way that doesn't mess everything
+	 * up?
+	 */
+	if (TotalMaxReplicationSlots == 0)
 		ereport(ERROR,
 				(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
 				 errmsg("replication slots can only be used if \"max_replication_slots\" > 0")));
@@ -2216,7 +2232,7 @@ InvalidateObsoleteReplicationSlots(uint32 possible_causes,
 	Assert(!(possible_causes & RS_INVAL_WAL_REMOVED) || oldestSegno > 0);
 	Assert(possible_causes != RS_INVAL_NONE);
 
-	if (max_replication_slots == 0)
+	if (TotalMaxReplicationSlots == 0)
 		return invalidated;
 
 	XLogSegNoOffsetToRecPtr(oldestSegno, 0, wal_segment_size, oldestLSN);
@@ -2224,7 +2240,7 @@ InvalidateObsoleteReplicationSlots(uint32 possible_causes,
 restart:
 	found_valid_logicalslot = false;
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (int i = 0; i < max_replication_slots; i++)
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 		bool		released_lock = false;
@@ -2329,7 +2345,7 @@ CheckPointReplicationSlots(bool is_shutdown)
 	 */
 	LWLockAcquire(ReplicationSlotAllocationLock, LW_SHARED);
 
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 		char		path[MAXPGPATH];
@@ -2430,7 +2446,7 @@ StartupReplicationSlots(void)
 	FreeDir(replication_dir);
 
 	/* currently no slots exist, we're done. */
-	if (max_replication_slots <= 0)
+	if (TotalMaxReplicationSlots <= 0)
 		return;
 
 	/* Now that we have recovered all the data, compute replication xmin */
@@ -2860,7 +2876,7 @@ RestoreSlotFromDisk(const char *name)
 				 errhint("Change \"wal_level\" to be \"replica\" or higher.")));
 
 	/* nothing can be active yet, don't lock anything */
-	for (i = 0; i < max_replication_slots; i++)
+	for (i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *slot;
 
@@ -2902,6 +2918,7 @@ RestoreSlotFromDisk(const char *name)
 		break;
 	}
 
+	/* XXX might be misleading if the slots previously in use were REPACK. */
 	if (!restored)
 		ereport(FATAL,
 				(errmsg("too many replication slots active before shutdown"),
diff --git a/src/backend/replication/slotfuncs.c b/src/backend/replication/slotfuncs.c
index 9f5e4f998fe..cdb4dbd87c9 100644
--- a/src/backend/replication/slotfuncs.c
+++ b/src/backend/replication/slotfuncs.c
@@ -53,7 +53,7 @@ create_physical_replication_slot(char *name, bool immediately_reserve,
 	/* acquire replication slot, this will check for conflicting names */
 	ReplicationSlotCreate(name, false,
 						  temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
-						  false, false);
+						  false, false, false);
 
 	if (immediately_reserve)
 	{
@@ -146,7 +146,7 @@ create_logical_replication_slot(char *name, char *plugin,
 	 */
 	ReplicationSlotCreate(name, true,
 						  temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
-						  failover, false);
+						  false, failover, false);
 
 	/*
 	 * Ensure the logical decoding is enabled before initializing the logical
@@ -270,7 +270,7 @@ pg_get_replication_slots(PG_FUNCTION_ARGS)
 	currlsn = GetXLogWriteRecPtr();
 
 	LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
-	for (slotno = 0; slotno < max_replication_slots; slotno++)
+	for (slotno = 0; slotno < TotalMaxReplicationSlots; slotno++)
 	{
 		ReplicationSlot *slot = &ReplicationSlotCtl->replication_slots[slotno];
 		ReplicationSlot slot_contents;
@@ -665,7 +665,7 @@ copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
 	 * managed to create the new slot, we advance the new slot's restart_lsn
 	 * to the source slot's updated restart_lsn the second time we lock it.
 	 */
-	for (int i = 0; i < max_replication_slots; i++)
+	for (int i = 0; i < TotalMaxReplicationSlots; i++)
 	{
 		ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
 
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index fbbe09135bf..caea3ed1257 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -1220,7 +1220,7 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
 	{
 		ReplicationSlotCreate(cmd->slotname, false,
 							  cmd->temporary ? RS_TEMPORARY : RS_PERSISTENT,
-							  false, false, false);
+							  false, false, false, false);
 
 		if (reserve_wal)
 		{
@@ -1251,7 +1251,7 @@ CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
 		 */
 		ReplicationSlotCreate(cmd->slotname, true,
 							  cmd->temporary ? RS_TEMPORARY : RS_EPHEMERAL,
-							  two_phase, failover, false);
+							  two_phase, false, failover, false);
 
 		/*
 		 * Do options check early so that we can bail before calling the
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 0a862693fcd..d12a3bd7bdf 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -2070,6 +2070,14 @@
   max => 'MAX_BACKENDS',
 },
 
+{ name => 'max_repack_replication_slots', type => 'int', context => 'PGC_POSTMASTER', group => 'REPLICATION_SENDING',
+  short_desc => 'Sets the maximum number of replication slots for use by REPACK.',
+  variable => 'max_repack_replication_slots',
+  boot_val => '1',
+  min => '0',
+  max => 'MAX_BACKENDS /* XXX? */',
+},
+
 /* see max_wal_senders */
 { name => 'max_replication_slots', type => 'int', context => 'PGC_POSTMASTER', group => 'REPLICATION_SENDING',
   short_desc => 'Sets the maximum number of simultaneously defined replication slots.',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index cf15597385b..15014f37753 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -348,6 +348,8 @@
                                 # (change requires restart)
 #max_replication_slots = 10     # max number of replication slots
                                 # (change requires restart)
+#max_repack_replication_slots = 1 # max number of replication slots for REPACK
+                                # (change requires restart)
 #wal_keep_size = 0              # in megabytes; 0 disables
 #max_slot_wal_keep_size = -1    # in megabytes; -1 disables
 #idle_replication_slot_timeout = 0      # in seconds; 0 disables
diff --git a/src/include/replication/slot.h b/src/include/replication/slot.h
index 4b4709f6e2c..88953576894 100644
--- a/src/include/replication/slot.h
+++ b/src/include/replication/slot.h
@@ -324,9 +324,13 @@ extern PGDLLIMPORT ReplicationSlot *MyReplicationSlot;
 
 /* GUCs */
 extern PGDLLIMPORT int max_replication_slots;
+extern PGDLLIMPORT int max_repack_replication_slots;
 extern PGDLLIMPORT char *synchronized_standby_slots;
 extern PGDLLIMPORT int idle_replication_slot_timeout_secs;
 
+/* only for slotfuncs.c, slotsync.c etc */
+extern int TotalMaxReplicationSlots;
+
 /* shmem initialization functions */
 extern Size ReplicationSlotsShmemSize(void);
 extern void ReplicationSlotsShmemInit(void);
@@ -334,7 +338,7 @@ extern void ReplicationSlotsShmemInit(void);
 /* management of individual slots */
 extern void ReplicationSlotCreate(const char *name, bool db_specific,
 								  ReplicationSlotPersistency persistency,
-								  bool two_phase, bool failover,
+								  bool two_phase, bool repack, bool failover,
 								  bool synced);
 extern void ReplicationSlotPersist(void);
 extern void ReplicationSlotDrop(const char *name, bool nowait);
-- 
2.47.3


--3n3vqr5y2jhknrqj--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread

* [PATCH 2/2] Publish list of tables being repacked in shared memory
@ 2026-04-07 20:29  Álvaro Herrera <[email protected]>
  0 siblings, 0 replies; 63+ messages in thread

From: Álvaro Herrera @ 2026-04-07 20:29 UTC (permalink / raw)

Use it in autovacuum to skip processing tables that are being repacked.
This is mostly to avoid repeated attempts to process such tables, which
would fail due to the special deadlock checker behavior for repack.

Author: Álvaro Herrera <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 src/backend/commands/repack.c                 | 195 ++++++++++++++++--
 src/backend/postmaster/autovacuum.c           |  20 ++
 .../utils/activity/wait_event_names.txt       |   1 +
 src/include/commands/repack.h                 |   2 +
 src/include/storage/lwlocklist.h              |   2 +-
 src/include/storage/subsystemlist.h           |   1 +
 src/tools/pgindent/typedefs.list              |   3 +
 7 files changed, 210 insertions(+), 14 deletions(-)

diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index a5f5df77291..ee7072dce6a 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -63,9 +63,11 @@
 #include "optimizer/optimizer.h"
 #include "pgstat.h"
 #include "storage/bufmgr.h"
+#include "storage/ipc.h"
 #include "storage/lmgr.h"
 #include "storage/predicate.h"
 #include "storage/proc.h"
+#include "storage/subsystems.h"
 #include "utils/acl.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -79,6 +81,32 @@
 #include "utils/syscache.h"
 #include "utils/wait_event_types.h"
 
+
+/* Shared memory layout for REPACK */
+typedef struct RepackWorkerInfo
+{
+	bool		ri_in_use;
+	pid_t		ri_backendpid;
+	Oid			ri_dbid;
+	Oid			ri_relid;
+	Oid			ri_toastrelid;
+} RepackWorkerInfo;
+
+typedef struct
+{
+	bool		re_useless;
+	RepackWorkerInfo re_workerinfo[FLEXIBLE_ARRAY_MEMBER];
+} RepackShmemStruct;
+
+static RepackShmemStruct *RepackShmem;
+
+typedef struct RepackCleanupContext
+{
+	bool		concurrent;
+	int			workerindex;
+} RepackCleanupContext;
+
+
 /*
  * This struct is used to pass around the information on tables to be
  * clustered. We need this so we can make a list of them when invoked without
@@ -90,6 +118,7 @@ typedef struct
 	Oid			indexOid;
 } RelToCluster;
 
+
 /*
  * The first file exported by the decoding worker must contain a snapshot, the
  * following ones contain the data changes.
@@ -166,6 +195,10 @@ static List *get_tables_to_repack_partitioned(RepackCommand cmd,
 											  MemoryContext permcxt);
 static bool repack_is_permitted_for_relation(RepackCommand cmd,
 											 Oid relid, Oid userid);
+static void RepackCleanup(RepackCleanupContext *context);
+static void RepackCleanupCb(int code, Datum arg);
+static void RepackShmemRequest(void *arg);
+static void RepackShmemInit(void *arg);
 
 static void apply_concurrent_changes(BufFile *file, ChangeContext *chgcxt);
 static void apply_concurrent_insert(Relation rel, TupleTableSlot *slot,
@@ -210,6 +243,11 @@ static void ProcessRepackMessage(StringInfo msg);
 static const char *RepackCommandAsString(RepackCommand cmd);
 
 
+const ShmemCallbacks RepackShmemCallbacks = {
+	.request_fn = RepackShmemRequest,
+	.init_fn = RepackShmemInit,
+};
+
 /*
  * The repack code allows for processing multiple tables at once. Because
  * of this, we cannot just run everything on a single transaction, or we
@@ -514,6 +552,7 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 	Oid			tableOid = RelationGetRelid(OldHeap);
 	Relation	index;
 	LOCKMODE	lmode;
+	RepackCleanupContext context;
 	Oid			save_userid;
 	int			save_sec_context;
 	int			save_nestlevel;
@@ -660,24 +699,43 @@ cluster_rel(RepackCommand cmd, Relation OldHeap, Oid indexOid,
 		TransferPredicateLocksToHeapRelation(OldHeap);
 
 	/* rebuild_relation does all the dirty work */
-	PG_TRY();
-	{
-		rebuild_relation(OldHeap, index, verbose, ident_idx);
-	}
-	PG_FINALLY();
+	context.concurrent = concurrent;
+
+	PG_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
 	{
 		if (concurrent)
 		{
-			/*
-			 * Since during normal operation the worker was already asked to
-			 * exit, stopping it explicitly is especially important on ERROR.
-			 * However it still seems a good practice to make sure that the
-			 * worker never survives the REPACK command.
-			 */
-			stop_repack_decoding_worker();
+			bool		freefound = false;
+
+			LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+			for (int i = 0; i < max_repack_replication_slots; i++)
+			{
+				RepackWorkerInfo *worker;
+
+				if (RepackShmem->re_workerinfo[i].ri_in_use)
+					continue;
+
+				freefound = true;
+				worker = &RepackShmem->re_workerinfo[i];
+				context.workerindex = i;
+
+				worker->ri_in_use = true;
+				worker->ri_backendpid = MyProcPid;
+				worker->ri_dbid = MyDatabaseId;
+				worker->ri_relid = RelationGetRelid(OldHeap);
+				worker->ri_toastrelid = OldHeap->rd_rel->reltoastrelid;
+				break;
+			}
+			if (!freefound)
+				elog(ERROR, "could not find free repack entry");
+			LWLockRelease(RepackLock);
 		}
+
+		rebuild_relation(OldHeap, index, verbose, ident_idx);
 	}
-	PG_END_TRY();
+	PG_END_ENSURE_ERROR_CLEANUP(RepackCleanupCb, PointerGetDatum(&context));
+
+	RepackCleanup(&context);
 
 	/* rebuild_relation closes OldHeap, and index if valid */
 
@@ -691,6 +749,117 @@ out:
 	pgstat_progress_end_command();
 }
 
+/*
+ * Return whether any backend is running concurrent REPACK on the given table
+ * (which could be a toast table).
+ */
+bool
+is_table_under_repack(Oid databaseId, Oid relid)
+{
+	bool		retval = false;
+
+	LWLockAcquire(RepackLock, LW_SHARED);
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		RepackWorkerInfo *rworker;
+
+		if (!RepackShmem->re_workerinfo[i].ri_in_use)
+			continue;
+
+		rworker = &RepackShmem->re_workerinfo[i];
+		if (rworker->ri_dbid == MyDatabaseId &&
+			(rworker->ri_relid == relid ||
+			 rworker->ri_toastrelid == relid))
+			retval = true;
+	}
+	LWLockRelease(RepackLock);
+
+	return retval;
+}
+
+/*
+ * Remove ourselves from the workerinfo array.
+ */
+static void
+RepackCleanup(RepackCleanupContext *context)
+{
+	if (context->concurrent)
+	{
+		RepackWorkerInfo *worker;
+
+		/*
+		 * The worker would normally terminate on its own when the work is
+		 * done, but make sure we signal it just in case.
+		 */
+		stop_repack_decoding_worker();
+
+		/*
+		 * also, make sure we stop advertising the relation we were repacking,
+		 * so that autovacuum reverts to handling it normally.
+		 */
+		LWLockAcquire(RepackLock, LW_EXCLUSIVE);
+
+		worker = &RepackShmem->re_workerinfo[context->workerindex];
+		Assert(worker->ri_backendpid == MyProcPid);
+		worker->ri_in_use = false;
+		worker->ri_backendpid = 0;
+		worker->ri_dbid = InvalidOid;
+		worker->ri_relid = InvalidOid;
+		worker->ri_toastrelid = InvalidOid;
+		LWLockRelease(RepackLock);
+	}
+}
+
+/*
+ * RepackCleanup wrapped as an on_shmem_exit callback function
+ */
+static void
+RepackCleanupCb(int code, Datum arg)
+{
+	RepackCleanup((RepackCleanupContext *) DatumGetPointer(arg));
+}
+
+/*
+ * RepackShmemRequest
+ *		Register shared memory space needed for repack
+ */
+static void
+RepackShmemRequest(void *arg)
+{
+	Size		size;
+
+	/*
+	 * Need the fixed struct and the array of RepackWorkerInfo.
+	 */
+	size = sizeof(RepackShmemStruct);
+	size = MAXALIGN(size);
+	size = add_size(size, mul_size(max_repack_replication_slots,
+								   sizeof(RepackWorkerInfo)));
+
+	ShmemRequestStruct(.name = "Repack Data",
+					   .size = size,
+					   .ptr = (void **) &RepackShmem,
+		);
+}
+
+static void
+RepackShmemInit(void *arg)
+{
+	RepackWorkerInfo *reinfo;
+
+	reinfo = (RepackWorkerInfo *) ((char *) RepackShmem +
+								   MAXALIGN(sizeof(RepackShmemStruct)));
+
+	for (int i = 0; i < max_repack_replication_slots; i++)
+	{
+		reinfo[i].ri_in_use = false;
+		reinfo[i].ri_backendpid = 0;
+		reinfo[i].ri_dbid = InvalidOid;
+		reinfo[i].ri_relid = InvalidOid;
+		reinfo[i].ri_toastrelid = InvalidOid;
+	}
+}
+
 /*
  * Check if the table (and its index) still meets the requirements of
  * cluster_rel().
diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..080c64ea3c8 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -78,6 +78,7 @@
 #include "catalog/namespace.h"
 #include "catalog/pg_database.h"
 #include "catalog/pg_namespace.h"
+#include "commands/repack.h"
 #include "commands/vacuum.h"
 #include "common/int.h"
 #include "funcapi.h"
@@ -2422,6 +2423,25 @@ do_autovacuum(void)
 			}
 		}
 		LWLockRelease(AutovacuumLock);
+
+		/*
+		 * Similarly, if the table is being processed by concurrent repack,
+		 * skip it (but make a note of that).  We wouldn't be able to acquire
+		 * its lock anyway.
+		 */
+		if (!skipit)
+		{
+			MemoryContextSwitchTo(PortalContext);
+
+			skipit = is_table_under_repack(MyDatabaseId, relid);
+			if (skipit)
+				ereport(LOG,
+						errmsg("skipping table \"%s.%s.%s\" because it's being repacked in concurrent mode",
+							   get_database_name(MyDatabaseId),
+							   get_namespace_name(get_rel_namespace(relid)),
+							   get_rel_name(relid)));
+		}
+
 		if (skipit)
 		{
 			LWLockRelease(AutovacuumScheduleLock);
diff --git a/src/backend/utils/activity/wait_event_names.txt b/src/backend/utils/activity/wait_event_names.txt
index 7bda5298558..e206304f204 100644
--- a/src/backend/utils/activity/wait_event_names.txt
+++ b/src/backend/utils/activity/wait_event_names.txt
@@ -332,6 +332,7 @@ SInvalWrite	"Waiting to add a message to the shared catalog invalidation queue."
 WALBufMapping	"Waiting to replace a page in WAL buffers."
 WALWrite	"Waiting for WAL buffers to be written to disk."
 ControlFile	"Waiting to read or update the <filename>pg_control</filename> file or create a new WAL file."
+Repack	"Waiting to read or update tables in process by concurrent repack."
 MultiXactGen	"Waiting to read or update shared multixact state."
 RelCacheInit	"Waiting to read or update a <filename>pg_internal.init</filename> relation cache initialization file."
 CheckpointerComm	"Waiting to manage fsync requests."
diff --git a/src/include/commands/repack.h b/src/include/commands/repack.h
index fd16e74b179..be7d38b5fae 100644
--- a/src/include/commands/repack.h
+++ b/src/include/commands/repack.h
@@ -42,6 +42,8 @@ extern void ExecRepack(ParseState *pstate, RepackStmt *stmt, bool isTopLevel);
 
 extern void cluster_rel(RepackCommand command, Relation OldHeap, Oid indexOid,
 						ClusterParams *params, bool isTopLevel);
+extern bool is_table_under_repack(Oid databaseId, Oid relid);
+
 extern void check_index_is_clusterable(Relation OldHeap, Oid indexOid,
 									   LOCKMODE lockmode);
 extern void mark_index_clustered(Relation rel, Oid indexOid, bool is_internal);
diff --git a/src/include/storage/lwlocklist.h b/src/include/storage/lwlocklist.h
index af8553bcb6c..3f08f4a15d4 100644
--- a/src/include/storage/lwlocklist.h
+++ b/src/include/storage/lwlocklist.h
@@ -41,7 +41,7 @@ PG_LWLOCK(6, SInvalWrite)
 PG_LWLOCK(7, WALBufMapping)
 PG_LWLOCK(8, WALWrite)
 PG_LWLOCK(9, ControlFile)
-/* 10 was CheckpointLock */
+PG_LWLOCK(10, Repack)
 /* 11 was XactSLRULock */
 /* 12 was SubtransSLRULock */
 PG_LWLOCK(13, MultiXactGen)
diff --git a/src/include/storage/subsystemlist.h b/src/include/storage/subsystemlist.h
index 9ad619080be..4e683b8b0a8 100644
--- a/src/include/storage/subsystemlist.h
+++ b/src/include/storage/subsystemlist.h
@@ -72,6 +72,7 @@ PG_SHMEM_SUBSYSTEM(WalSummarizerShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(PgArchShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(ApplyLauncherShmemCallbacks)
 PG_SHMEM_SUBSYSTEM(SlotSyncShmemCallbacks)
+PG_SHMEM_SUBSYSTEM(RepackShmemCallbacks)
 
 /* other modules that need some shared memory space */
 PG_SHMEM_SUBSYSTEM(BTreeShmemCallbacks)
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 637c669a146..d019e03aaf1 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2639,9 +2639,12 @@ ReorderBufferTupleCidEnt
 ReorderBufferTupleCidKey
 ReorderBufferUpdateProgressTxnCB
 ReorderTuple
+RepackCleanupContext
 RepackCommand
 RepackDecodingState
+RepackShmemStruct
 RepackStmt
+RepackWorkerInfo
 ReparameterizeForeignPathByChild_function
 ReplOriginId
 ReplOriginXactState
-- 
2.47.3


--kdrcpfmkbkc4lqhu--





^ permalink  raw  reply  [nested|flat] 63+ messages in thread


end of thread, other threads:[~2026-04-07 20:29 UTC | newest]

Thread overview: 63+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-04-01 17:54 [PATCH v49 7/7] WIP add max_repack_replication_slots Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>
2026-04-07 20:29 [PATCH 2/2] Publish list of tables being repacked in shared memory Álvaro Herrera <[email protected]>

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox