--- a/src/backend/replication/logical/reorderbuffer.c	2024-12-12 10:21:12.962202250 +0100
+++ b/src/backend/replication/logical/reorderbuffer.c	2024-12-12 11:40:24.217634527 +0100
@@ -4567,27 +4567,35 @@
 static void
 ReorderBufferRestoreCleanup(ReorderBuffer *rb, ReorderBufferTXN *txn)
 {
-	XLogSegNo	first;
-	XLogSegNo	cur;
-	XLogSegNo	last;
+	DIR *spill_dir;
+	struct dirent *spill_de;
+	char path[MAXPGPATH];
+	char spill_path[MAXPGPATH];
+	char file_filter[MAXPGPATH];
+	int len_filter;
+ 
+	snprintf(spill_path, MAXPGPATH, "pg_replslot/%s", 
+			NameStr(MyReplicationSlot->data.name));
 
-	Assert(txn->first_lsn != InvalidXLogRecPtr);
-	Assert(txn->final_lsn != InvalidXLogRecPtr);
-
-	XLByteToSeg(txn->first_lsn, first, wal_segment_size);
-	XLByteToSeg(txn->final_lsn, last, wal_segment_size);
-
-	/* iterate over all possible filenames, and delete them */
-	for (cur = first; cur <= last; cur++)
-	{
-		char		path[MAXPGPATH];
-
-		ReorderBufferSerializedPath(path, MyReplicationSlot, txn->xid, cur);
-		if (unlink(path) != 0 && errno != ENOENT)
-			ereport(ERROR,
-					(errcode_for_file_access(),
-					 errmsg("could not remove file \"%s\": %m", path)));
-	}
+ 	snprintf(file_filter, sizeof(file_filter), "xid-%u-", txn->xid);
+	len_filter = strlen(file_filter);
+ 
+	spill_dir = AllocateDir(spill_path);
+	while ((spill_de = ReadDirExtended(spill_dir, spill_path, INFO)) != NULL)
+ 	{
+		/* only look at names that can be ours */
+		if (strncmp(spill_de->d_name, file_filter, len_filter) == 0)
+		{
+			snprintf(path, sizeof(path), "%s/%s", spill_path,
+					spill_de->d_name);
+ 
+			if (unlink(path) != 0)
+				ereport(ERROR,
+						(errcode_for_file_access(),
+						 errmsg("could not remove file \"%s\": %m", path)));
+		}
+ 	}
+	FreeDir(spill_dir);
 }
 
 /*
