Subject: Fix publisher-side sequence permission reporting

From: Fujii Masao <[email-masked]>
Date: Fri, 19 Jun 2026 00:36:06 +0900

Hi,

While testing logical replication sequence synchronization, I found
that a publisher-side permission problem can be reported as a
misleading "missing sequence on publisher" warning.

The issue can be reproduced as follows:

1. On the publisher:

   CREATE SEQUENCE myseq;
   CREATE PUBLICATION mypub FOR ALL SEQUENCES;
   CREATE ROLE foo LOGIN REPLICATION NOSUPERUSER;

2. On the subscriber:

   CREATE SEQUENCE myseq;
   CREATE SUBSCRIPTION mysub
     CONNECTION 'user=foo dbname=postgres ...'
     PUBLICATION mypub;

The subscriber currently emits:

   WARNING:  missing sequence on publisher ("public.myseq")

even though the sequence still exists on the publisher. The real
problem is that the replication connection lacks SELECT privilege to
read the sequence data.

The cause is that; sequence synchronization obtains sequence data using
pg_get_sequence_data(). When the user lacks SELECT privilege on
the sequence, pg_get_sequence_data() returns a row containing all NULL
values. Sequence synchronization currently treats that the same as
a missing sequence, so publisher-side permission failures and
genuinely missing sequences are not distinguished, leading to
the misleading warning.

Patch 0001 fixes this by distinguishing the two cases during sequence
synchronization. It checks whether the replication connection has the
required privilege for each published sequence and reports
publisher-side permission failures separately.

While working on this, I also noticed that the documented privilege
requirement for pg_get_sequence_data() does not match the
implementation. The documentation says that USAGE or SELECT privilege
is sufficient, but the implementation requires SELECT.

Patch 0002 updates the documentation to match the current behavior.

I chose to update the documentation rather than broaden the
implementation for two reasons.

First, commit c8b06bb969b, which introduced the predecessor of
pg_get_sequence_data(), described it as a substitute for SELECT
from a sequence, and its implementation has always required
SELECT privilege.

Second, the logical replication documentation already states that
replicating sequence data requires SELECT privilege.

Patches attached.

Regards,

-- 
Fujii Masao

---

From: "Tristan Partin" <[email-masked]>
Date: Thu, 18 Jun 2026 23:11:48 +0000

Hi Masao-san,

The patch looks good to me! I had one suggestion:

>  ##########
>  # Ensure that insufficient privileges on the publisher for a sequence do not
> -# disrupt the subscriber. The subscriber should log a warning and continue
> -# retrying.
> +# get misreported as a missing sequence. The subscriber should log a warning
> +# and continue retrying.
>  ##########

I think a better comment might be:

	Ensure that insufficient privileges on the publisher for a sequence 
	are reported correctly...

My reasoning for suggesting that is because your comment would to 
indicate that any warning is accurate as long as it isn't related to 
a missing sequence.

The API for pg_get_sequence_data() is very _interesting_. Overloading 
the NULLs row to mean many things is a bit strange. I'm not sure what 
a better solution would be. Just thought I would mention that.

> replicating sequence data requires SELECT privilege.

Your reasoning for updating the documentation makes sense, and the patch 
you submitted achieves the stated goal.

-- 
Tristan Partin
PostgreSQL Contributors Team
AWS (https://aws.amazon.com)

---

From: Fujii Masao <[email-masked]>
Date: Fri, 19 Jun 2026 23:15:52 +0900

> indicate that any warning is accurate as long as it isn't related to

Thanks for the review! I've updated the patch as suggested.

Updated patches attached.

Regards,

-- 
Fujii Masao

---

From: "Tristan Partin" <[email-masked]>
Date: Fri, 19 Jun 2026 16:38:27 +0000

> Updated patches attached.

Looks great! Thanks for fixing this.

---

From: Fujii Masao <[email-masked]>
Date: Sat, 20 Jun 2026 18:24:07 +0900

> Looks great! Thanks for fixing this.

Thanks for the review! I've pushed the patches.

Regards,

-- 
Fujii Masao

---

From: Amit Kapila <[email-masked]>
Date: Sat, 20 Jun 2026 15:50:58 +0530

> Thanks for the review! I've pushed the patches.

You seem to have forgotten to update the following comment in
pg_get_sequence_data(): "Return all NULLs for missing sequences,
sequences for which we lack
privileges, other sessions' temporary sequences, ...". BTW, if we go
by the logic of your proposal, shouldn't one also distinguish other
cases as mentioned in the comment quoted by me?

Also, we might want to consider additional errhint as follows:
errhint("Grant UPDATE on the sequence to the subscription/sequence
owner on the subscriber.")
errhint("Grant SELECT on the sequence to the replication role on the
publisher.")

-- 
With Regards,
Amit Kapila.

---

From: Fujii Masao <[email-masked]>
Date: Sat, 20 Jun 2026 21:43:59 +0900

On Sat, Jun 20, 2026 at 7:21 PM Amit Kapila <[email-masked]> wrote:
> privileges, other sessions' temporary sequences, ...".

Do you mean that the documentation for pg_get_sequence_data() should
also mention other sessions' temporary sequences and unlogged sequences
on standbys, as the comment does? If I've misunderstood your point,
could you clarify?

> BTW, if we go

Do you mean that sequencesync.c should also distinguish other
sessions' temporary sequences and unlogged sequences on standbys, and
report separate warnings for those cases?

> Also, we might want to consider additional errhint as follows:

Sounds good.

> owner on the subscriber.")

Wouldn't it be better to drop "sequence" from "subscription/sequence
owner"? The sequence owner should already have UPDATE privilege on
the sequence. How about:

    errhint("Grant UPDATE on the sequence to the subscription owner on
the subscriber.")

> errhint("Grant SELECT on the sequence to the replication role on the

How about making this a bit more precise?

    errhint("Grant SELECT on the sequence to the role used for the
replication connection on the publisher.")

Regards,

-- 
Fujii Masao

---

From: Amit Kapila <[email-masked]>
Date: Mon, 22 Jun 2026 09:33:44 +0530

> on standbys, as the comment does? If I've misunderstood your point,

It is better to update docs for all cases. Sorry, I was wrong in
saying that code comments need an update.

> report separate warnings for those cases?

Right. I mean to ask if we want to distinguish the lack of privilege
as a separate case then why not others? My opinion on this point is
that improving all these cases (including lack of privileges) together
could be considered as an enhancement for the next version but if you
think this is sort of a must to distinguish one or more cases then we
can do it now as well. However, the reason for doing it now is not
clear to me.

>     errhint("Grant UPDATE on the sequence to the subscription owner on

makes sense.

> replication connection on the publisher.")

makes sense.

-- 
With Regards,
Amit Kapila.

---

From: Fujii Masao <[email-masked]>
Date: Wed, 24 Jun 2026 09:41:16 +0900

> saying that code comments need an update.

Understood.

BTW, isn't the current documentation a bit misleading? It says:

    This function returns a row of NULL values if the sequence does not exist.

But if the specified object does not exist, pg_get_sequence_data()
raises an error rather than returning a row of NULL values. On the
other hand, it does return a row of NULL values if the specified
object exists but is not a sequence. Is my understanding correct? If
so, how about something like:

---------------------
This function returns a row of NULL values if the specified object
exists but is not a sequence, if the current user lacks privileges on
the sequence, if the sequence is another session's temporary
sequence, or if it is an unlogged sequence on a standby server.
---------------------

> can do it now as well. However, the reason for doing it now is not

I think the lack-of-privilege case should be checked first, since it is
likely to be the most common one.

As for another session's temporary sequences, I don't think a sequence
sync worker can actually encounter one. To do so, it would have to
specify another session's temporary namespace when executing the query
below. However, the namespace comes from the publication, and temporary
sequences are never published, so that doesn't seem possible.

appendStringInfo(&cmd,
"SELECT s.seqidx, has_sequence_privilege(c.oid, 'SELECT'),\n"
"       ps.*, seq.seqtypid,\n"
"       seq.seqstart, seq.seqincrement, seq.seqmin,\n"
"       seq.seqmax, seq.seqcycle\n"
"FROM ( VALUES %s ) AS s (schname, seqname, seqidx)\n"
"JOIN pg_namespace n ON n.nspname = s.schname\n"
"JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = s.seqname\n"
"JOIN pg_sequence seq ON seq.seqrelid = c.oid\n"
"JOIN LATERAL pg_get_sequence_data(seq.seqrelid) AS ps ON true\n",
seqstr.data);

An unlogged sequence on a standby seems theoretically possible, but
only under unlikely sequence of events:

1. The sequence sync worker fetches the sequence information from the
publication.
2. The sequence is dropped on the primary.
3. An unlogged sequence with the same name is created.
4. The schema change is replicated to the standby.
5. The sequence sync worker executes the above query with the fetched info.

So I think this case is possible, but unlikely.

> > replication connection on the publisher.")

The attached patch adds those HINT messages. It also updates the
related documentation.

Regards,

-- 
Fujii Masao

---

From: Bharath Rupireddy <[email-masked]>
Date: Tue, 23 Jun 2026 22:40:44 -0700

Hi,

> so, how about something like:

When the provided relation oid doesn't exist, returns NULL:
postgres=# select pg_get_sequence_data(99999999);
 pg_get_sequence_data
----------------------
 (,,)
(1 row)

When the provided relation oid (pg_statistic) exists but not a
sequence, returns NULL:
postgres=# select pg_get_sequence_data(2619);
 pg_get_sequence_data
----------------------
 (,,)
(1 row)

When the provided relation oid exists and is a sequence, returns sequence data:
postgres=# select pg_get_sequence_data(16388);
 pg_get_sequence_data
----------------------
 (1,f,0/017DD9A0)
(1 row)

> sequences are never published, so that doesn't seem possible.

Ideally, all these checks (except seqrel being NULL when
try_relation_open detects a concurrent drop) should report an ERROR if
not met, instead of silently emitting NULLs, so the subscriber catches
these early and reports "could not fetch sequence information from the
publisher:" But I understand that on the subscriber side it would
require error message parsing to distinguish the exact cause, which is
not ideal.

However, instead of pg_get_sequence_data emitting just 3 columns, it
could emit additional columns such as:

"last_value", "is_called", "page_lsn", "has_privileges",
"is_sequence", "is_temp_relation", "is_recovery_in_progress"

When any of the new flag columns are true, the first three values
would be NULLs.

This keeps the subscriber-side query simple and leaves the existing
error-handling code as-is.

> The attached patch adds those HINT messages. It also updates the

Nice! This looks more explicit and clarifying. The patch LGTM.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

---

From: Amit Kapila <[email-masked]>
Date: Wed, 24 Jun 2026 13:10:11 +0530

> so, how about something like:

Assume a case where the primary fails and the system promotes standby
as a new primary. Then the subscriber starts sync from the new
primary, there it can lead to an unlogged sequence sync scenario?

-- 
With Regards,
Amit Kapila.

---

From: Fujii Masao <[email-masked]>
Date: Wed, 24 Jun 2026 17:50:17 +0900

> primary, there it can lead to an unlogged sequence sync scenario?

When I tested pg_get_sequence_data() with an unlogged sequence on
new primary after promotion, I hit an assertion failure...

---------------------
1. Create an unlogged sequence on the primary:

=# CREATE UNLOGGED SEQUENCE myseq;
CREATE SEQUENCE

2. Confirm that pg_get_sequence_data() returns NULL values on the standby:

=# SELECT * FROM pg_get_sequence_data('myseq');
 last_value | is_called | page_lsn
------------+-----------+----------
     (null) | (null)    | (null)
(1 row)

3. Promote the standby, then call pg_get_sequence_data() on the new primary:

=# SELECT * FROM pg_get_sequence_data('myseq');

This results in the following assertion failure:

TRAP: failed Assert("((const PageHeaderData *) page)->pd_special >=
SizeOfPageHeaderData"), File:
"../../../src/include/storage/bufpage.h", Line: 357, PID: 96253
0   postgres                            0x000000010d8d1412
ExceptionalCondition + 178
1   postgres                            0x000000010d316970
PageValidateSpecialPointer + 128
2   postgres                            0x000000010d3142df read_seq_tuple + 79
3   postgres                            0x000000010d31635e
pg_get_sequence_data + 382
4   postgres                            0x000000010d3bc42e
ExecMakeTableFunctionResult + 702
5   postgres                            0x000000010d3da6cf FunctionNext + 175
6   postgres                            0x000000010d3bde92 ExecScanFetch + 626
7   postgres                            0x000000010d3bd88f ExecScanExtended + 95
8   postgres                            0x000000010d3bd81f ExecScan + 95
9   postgres                            0x000000010d3da2c5 ExecFunctionScan + 53
10  postgres                            0x000000010d3b8a2b
ExecProcNodeFirst + 75
11  postgres                            0x000000010d3affee ExecProcNode + 46
12  postgres                            0x000000010d3ab507 ExecutePlan + 199
13  postgres                            0x000000010d3ab3e0
standard_ExecutorRun + 368
14  postgres                            0x000000010d3ab263 ExecutorRun + 67
15  postgres                            0x000000010d6c2710 PortalRunSelect + 256
16  postgres                            0x000000010d6c2170 PortalRun + 672
17  postgres                            0x000000010d6bd53c
exec_simple_query + 1292
18  postgres                            0x000000010d6bc6e5 PostgresMain + 2981
19  postgres                            0x000000010d6b5228 BackendMain + 168
20  postgres                            0x000000010d5a2269
postmaster_child_launch + 377
21  postgres                            0x000000010d5a8775 BackendStartup + 277
22  postgres                            0x000000010d5a6d85 ServerLoop + 341
23  postgres                            0x000000010d5a5b84 PostmasterMain + 5748
24  postgres                            0x000000010d43e533 main + 771
25  dyld                                0x00007ff80fc71530 start + 3056
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.

Regards,

-- 
Fujii Masao

---

From: Fujii Masao <[email-masked]>
Date: Wed, 24 Jun 2026 19:30:09 +0900

> new primary after promotion, I hit an assertion failure...

The assertion failure seems to be caused by seq_redo() not flushing
the init fork buffer from shared buffers. As a result, the init fork of
an unlogged sequence can remain invalid. During promotion,
ResetUnloggedRelations() creates the main fork by copying the init
fork from disk, so the main fork also becomes invalid. When
pg_get_sequence_data() later reads the invalid page, it hits the
assertion failure.

The attached patch adds a common function to flush an init fork buffer
and updates seq_redo() to use it. It also updates hash_xlog.c to
reuse the same function to simplify the code.

Thought?

Regards,

-- 
Fujii Masao

---

From: vignesh C <[email-masked]>
Date: Wed, 24 Jun 2026 16:19:25 +0530

> reuse the same function to simplify the code.

Thanks for the patch. I verified that it fixes the issue with reading
unlogged sequences on a promoted standby.
Do you think it would be worthwhile to add a test for this scenario,
or do you feel the additional test is not necessary in this case?

Regards,
Vignesh

---

From: Fujii Masao <[email-masked]>
Date: Fri, 26 Jun 2026 16:04:21 +0900

> unlogged sequences on a promoted standby.

Thanks for testing!

> or do you feel the additional test is not necessary in this case?

I think it's worth adding a test for this scenario, so I've added one to
the patch. The test uses nextval() to read the unlogged sequence
instead of pg_get_sequence_data(), since this patch needs to be
backpatched to v15, while pg_get_sequence_data() was introduced in
v19.

Attached are updated patches for master and the stable branches.

Regards,

-- 
Fujii Masao
From 653b98b2418abaf015168955392a550401f519cf Mon Sep 17 00:00:00 2001
From: Fujii Masao <[email-masked]>
Date: Fri, 26 Jun 2026 11:53:24 +0900
Subject: [PATCH v2] Fix unlogged sequence corruption after standby promotion

Previously, if an unlogged sequence was created on the primary and
replicated to a standby, reading the sequence after promoting the
standby (for example, with nextval()) could trigger the following
assertion failure:

    TRAP: failed Assert("((const PageHeaderData *) page)->pd_special >= SizeOfPageHeaderData")

The problem was that seq_redo() updated the init fork page in shared
buffers but did not flush it to disk. During promotion,
ResetUnloggedRelations() recreates the main fork of unlogged
relations by copying the init fork from disk, bypassing shared
buffers. As a result, the main fork could be recreated from a stale
init fork instead of the WAL-replayed page.

Fix this by introducing a helper to flush init fork buffers
immediately, and make seq_redo() use it. As a result, the main fork
of an unlogged sequence is recreated from the up-to-date init fork on
disk, allowing the unlogged sequence to be read successfully after
standby promotion.

Backpatch to v15, where unlogged sequences were introduced.
---
 src/backend/access/hash/hash_xlog.c           | 29 ++-------------
 src/backend/access/transam/xlogutils.c        | 26 +++++++++++++-
 src/backend/commands/sequence.c               |  1 +
 src/include/access/xlogutils.h                |  2 ++
 .../t/054_unlogged_sequence_promotion.pl      | 36 +++++++++++++++++++
 5 files changed, 67 insertions(+), 27 deletions(-)
 create mode 100644 src/test/recovery/t/054_unlogged_sequence_promotion.pl

diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 6fe1c2f7951..e541ce81ce6 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -32,7 +32,6 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	XLogRecPtr	lsn = record->EndRecPtr;
 	Page		page;
 	Buffer		metabuf;
-	ForkNumber	forknum;
 
 	xl_hash_init_meta_page *xlrec = (xl_hash_init_meta_page *) XLogRecGetData(record);
 
@@ -44,16 +43,7 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	page = (Page) BufferGetPage(metabuf);
 	PageSetLSN(page, lsn);
 	MarkBufferDirty(metabuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(metabuf);
+	XLogFlushBufferForRedoIfInit(record, 0, metabuf);
 
 	/* all done */
 	UnlockReleaseBuffer(metabuf);
@@ -71,7 +61,6 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	Page		page;
 	HashMetaPage metap;
 	uint32		num_buckets;
-	ForkNumber	forknum;
 
 	xl_hash_init_bitmap_page *xlrec = (xl_hash_init_bitmap_page *) XLogRecGetData(record);
 
@@ -82,16 +71,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	_hash_initbitmapbuffer(bitmapbuf, xlrec->bmsize, true);
 	PageSetLSN(BufferGetPage(bitmapbuf), lsn);
 	MarkBufferDirty(bitmapbuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(bitmapbuf);
+	XLogFlushBufferForRedoIfInit(record, 0, bitmapbuf);
 	UnlockReleaseBuffer(bitmapbuf);
 
 	/* add the new bitmap page to the metapage's list of bitmaps */
@@ -112,10 +92,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 
 		PageSetLSN(page, lsn);
 		MarkBufferDirty(metabuf);
-
-		XLogRecGetBlockTag(record, 1, NULL, &forknum, NULL);
-		if (forknum == INIT_FORKNUM)
-			FlushOneBuffer(metabuf);
+		XLogFlushBufferForRedoIfInit(record, 1, metabuf);
 	}
 	if (BufferIsValid(metabuf))
 		UnlockReleaseBuffer(metabuf);
diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index 702c8c14e12..72844504b64 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -334,6 +334,28 @@ XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
 	return buf;
 }
 
+/*
+ * If a redo routine modified an init fork, flush the buffer immediately.
+ *
+ * At the end of crash recovery the init forks of unlogged relations are
+ * copied to the main fork directly from disk, without going through shared
+ * buffers. Therefore, redo routines that update init forks without
+ * restoring a full-page image must call this after setting the page LSN and
+ * marking the buffer dirty.
+ */
+void
+XLogFlushBufferForRedoIfInit(XLogReaderState *record, uint8 block_id,
+							 Buffer buffer)
+{
+	ForkNumber	forknum;
+
+	Assert(BufferIsValid(buffer));
+
+	XLogRecGetBlockTag(record, block_id, NULL, &forknum, NULL);
+	if (forknum == INIT_FORKNUM)
+		FlushOneBuffer(buffer);
+}
+
 /*
  * XLogReadBufferForRedoExtended
  *		Like XLogReadBufferForRedo, but with extra options.
@@ -411,7 +433,9 @@ XLogReadBufferForRedoExtended(XLogReaderState *record,
 		 * At the end of crash recovery the init forks of unlogged relations
 		 * are copied, without going through shared buffers. So we need to
 		 * force the on-disk state of init forks to always be in sync with the
-		 * state in shared buffers.
+		 * state in shared buffers. Use XLogFlushBufferForRedoIfInit() for
+		 * redo routines that dirty init-fork buffers without restoring a
+		 * full-page image.
 		 */
 		if (forknum == INIT_FORKNUM)
 			FlushOneBuffer(*buf);
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index fbcfcddb59e..9ef47b64274 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -1908,6 +1908,7 @@ seq_redo(XLogReaderState *record)
 
 	memcpy(page, localpage, BufferGetPageSize(buffer));
 	MarkBufferDirty(buffer);
+	XLogFlushBufferForRedoIfInit(record, 0, buffer);
 	UnlockReleaseBuffer(buffer);
 
 	pfree(localpage);
diff --git a/src/include/access/xlogutils.h b/src/include/access/xlogutils.h
index c9d0b75a01b..e91d1d99ec5 100644
--- a/src/include/access/xlogutils.h
+++ b/src/include/access/xlogutils.h
@@ -84,6 +84,8 @@ typedef struct ReadLocalXLogPageNoWaitPrivate
 extern XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record,
 											uint8 buffer_id, Buffer *buf);
 extern Buffer XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id);
+extern void XLogFlushBufferForRedoIfInit(XLogReaderState *record,
+										 uint8 block_id, Buffer buffer);
 extern XLogRedoAction XLogReadBufferForRedoExtended(XLogReaderState *record,
 													uint8 buffer_id,
 													ReadBufferMode mode, bool get_cleanup_lock,
diff --git a/src/test/recovery/t/054_unlogged_sequence_promotion.pl b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
new file mode 100644
index 00000000000..7e030c60eee
--- /dev/null
+++ b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
@@ -0,0 +1,36 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that unlogged sequences created on a primary can be read after
+# promotion of a standby that replayed their init fork.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->start;
+
+my $backup_name = 'my_backup';
+$node_primary->backup($backup_name);
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, $backup_name,
+	has_streaming => 1);
+$node_standby->start;
+
+# Create the unlogged sequence after the standby has started, so its init fork
+# is generated by WAL replay on the standby.
+$node_primary->safe_psql('postgres', "CREATE UNLOGGED SEQUENCE ulseq");
+$node_primary->wait_for_catchup($node_standby);
+
+$node_standby->promote;
+$node_standby->poll_query_until('postgres', "SELECT NOT pg_is_in_recovery()")
+	or die "Timed out waiting for promotion";
+
+is($node_standby->safe_psql('postgres', "SELECT nextval('ulseq')"),
+	1, 'unlogged sequence can be read after standby promotion');
+
+done_testing();
-- 
2.53.0

From dc7b84386209c745427d98586b7f100b6a8e122c Mon Sep 17 00:00:00 2001
From: Fujii Masao <[email-masked]>
Date: Fri, 26 Jun 2026 11:53:24 +0900
Subject: [PATCH v2] Fix unlogged sequence corruption after standby promotion

Previously, if an unlogged sequence was created on the primary and
replicated to a standby, reading the sequence after promoting the
standby (for example, with nextval()) could trigger the following
assertion failure:

    TRAP: failed Assert("((const PageHeaderData *) page)->pd_special >= SizeOfPageHeaderData")

The problem was that seq_redo() updated the init fork page in shared
buffers but did not flush it to disk. During promotion,
ResetUnloggedRelations() recreates the main fork of unlogged
relations by copying the init fork from disk, bypassing shared
buffers. As a result, the main fork could be recreated from a stale
init fork instead of the WAL-replayed page.

Fix this by introducing a helper to flush init fork buffers
immediately, and make seq_redo() use it. As a result, the main fork
of an unlogged sequence is recreated from the up-to-date init fork on
disk, allowing the unlogged sequence to be read successfully after
standby promotion.

Backpatch to v15, where unlogged sequences were introduced.
---
 src/backend/access/hash/hash_xlog.c           | 29 ++--------------
 src/backend/access/transam/xlogutils.c        | 26 +++++++++++++-
 src/backend/commands/sequence.c               |  1 +
 src/include/access/xlogutils.h                |  2 ++
 src/test/recovery/meson.build                 |  1 +
 .../t/054_unlogged_sequence_promotion.pl      | 34 +++++++++++++++++++
 6 files changed, 66 insertions(+), 27 deletions(-)
 create mode 100644 src/test/recovery/t/054_unlogged_sequence_promotion.pl

diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 8d97067fe54..d4cb6246b48 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -29,7 +29,6 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	XLogRecPtr	lsn = record->EndRecPtr;
 	Page		page;
 	Buffer		metabuf;
-	ForkNumber	forknum;
 
 	xl_hash_init_meta_page *xlrec = (xl_hash_init_meta_page *) XLogRecGetData(record);
 
@@ -41,16 +40,7 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	page = (Page) BufferGetPage(metabuf);
 	PageSetLSN(page, lsn);
 	MarkBufferDirty(metabuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(metabuf);
+	XLogFlushBufferForRedoIfInit(record, 0, metabuf);
 
 	/* all done */
 	UnlockReleaseBuffer(metabuf);
@@ -68,7 +58,6 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	Page		page;
 	HashMetaPage metap;
 	uint32		num_buckets;
-	ForkNumber	forknum;
 
 	xl_hash_init_bitmap_page *xlrec = (xl_hash_init_bitmap_page *) XLogRecGetData(record);
 
@@ -79,16 +68,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	_hash_initbitmapbuffer(bitmapbuf, xlrec->bmsize, true);
 	PageSetLSN(BufferGetPage(bitmapbuf), lsn);
 	MarkBufferDirty(bitmapbuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(bitmapbuf);
+	XLogFlushBufferForRedoIfInit(record, 0, bitmapbuf);
 	UnlockReleaseBuffer(bitmapbuf);
 
 	/* add the new bitmap page to the metapage's list of bitmaps */
@@ -109,10 +89,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 
 		PageSetLSN(page, lsn);
 		MarkBufferDirty(metabuf);
-
-		XLogRecGetBlockTag(record, 1, NULL, &forknum, NULL);
-		if (forknum == INIT_FORKNUM)
-			FlushOneBuffer(metabuf);
+		XLogFlushBufferForRedoIfInit(record, 1, metabuf);
 	}
 	if (BufferIsValid(metabuf))
 		UnlockReleaseBuffer(metabuf);
diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index db5a314edf8..0d67f256afe 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -321,6 +321,28 @@ XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
 	return buf;
 }
 
+/*
+ * If a redo routine modified an init fork, flush the buffer immediately.
+ *
+ * At the end of crash recovery the init forks of unlogged relations are
+ * copied to the main fork directly from disk, without going through shared
+ * buffers. Therefore, redo routines that update init forks without
+ * restoring a full-page image must call this after setting the page LSN and
+ * marking the buffer dirty.
+ */
+void
+XLogFlushBufferForRedoIfInit(XLogReaderState *record, uint8 block_id,
+							 Buffer buffer)
+{
+	ForkNumber	forknum;
+
+	Assert(BufferIsValid(buffer));
+
+	XLogRecGetBlockTag(record, block_id, NULL, &forknum, NULL);
+	if (forknum == INIT_FORKNUM)
+		FlushOneBuffer(buffer);
+}
+
 /*
  * XLogReadBufferForRedoExtended
  *		Like XLogReadBufferForRedo, but with extra options.
@@ -398,7 +420,9 @@ XLogReadBufferForRedoExtended(XLogReaderState *record,
 		 * At the end of crash recovery the init forks of unlogged relations
 		 * are copied, without going through shared buffers. So we need to
 		 * force the on-disk state of init forks to always be in sync with the
-		 * state in shared buffers.
+		 * state in shared buffers. Use XLogFlushBufferForRedoIfInit() for
+		 * redo routines that dirty init-fork buffers without restoring a
+		 * full-page image.
 		 */
 		if (forknum == INIT_FORKNUM)
 			FlushOneBuffer(*buf);
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index a79ef0651a9..c1ad656397a 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -1933,6 +1933,7 @@ seq_redo(XLogReaderState *record)
 
 	memcpy(page, localpage, BufferGetPageSize(buffer));
 	MarkBufferDirty(buffer);
+	XLogFlushBufferForRedoIfInit(record, 0, buffer);
 	UnlockReleaseBuffer(buffer);
 
 	pfree(localpage);
diff --git a/src/include/access/xlogutils.h b/src/include/access/xlogutils.h
index a1870d8e5aa..7639bd523e1 100644
--- a/src/include/access/xlogutils.h
+++ b/src/include/access/xlogutils.h
@@ -87,6 +87,8 @@ typedef struct ReadLocalXLogPageNoWaitPrivate
 extern XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record,
 											uint8 block_id, Buffer *buf);
 extern Buffer XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id);
+extern void XLogFlushBufferForRedoIfInit(XLogReaderState *record,
+										 uint8 block_id, Buffer buffer);
 extern XLogRedoAction XLogReadBufferForRedoExtended(XLogReaderState *record,
 													uint8 block_id,
 													ReadBufferMode mode, bool get_cleanup_lock,
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 5245fdde43c..38e1e43e041 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -58,6 +58,7 @@ tests += {
       't/047_checkpoint_physical_slot.pl',
       't/048_vacuum_horizon_floor.pl',
       't/053_standby_login_event_trigger.pl',
+      't/054_unlogged_sequence_promotion.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/054_unlogged_sequence_promotion.pl b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
new file mode 100644
index 00000000000..96d1e4bf18b
--- /dev/null
+++ b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
@@ -0,0 +1,34 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that unlogged sequences created on a primary can be read after
+# promotion of a standby that replayed their init fork.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->start;
+
+my $backup_name = 'my_backup';
+$node_primary->backup($backup_name);
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, $backup_name,
+	has_streaming => 1);
+$node_standby->start;
+
+# Create the unlogged sequence after the standby has started, so its init fork
+# is generated by WAL replay on the standby.
+$node_primary->safe_psql('postgres', "CREATE UNLOGGED SEQUENCE ulseq");
+$node_primary->wait_for_replay_catchup($node_standby);
+
+$node_standby->promote;
+
+is($node_standby->safe_psql('postgres', "SELECT nextval('ulseq')"),
+	1, 'unlogged sequence can be read after standby promotion');
+
+done_testing();
-- 
2.53.0

From 90b5a189df90c263648f66bbc3edc7ce5dc12f9a Mon Sep 17 00:00:00 2001
From: Fujii Masao <[email-masked]>
Date: Fri, 26 Jun 2026 11:53:24 +0900
Subject: [PATCH v2] Fix unlogged sequence corruption after standby promotion

Previously, if an unlogged sequence was created on the primary and
replicated to a standby, reading the sequence after promoting the
standby (for example, with nextval()) could trigger the following
assertion failure:

    TRAP: failed Assert("((const PageHeaderData *) page)->pd_special >= SizeOfPageHeaderData")

The problem was that seq_redo() updated the init fork page in shared
buffers but did not flush it to disk. During promotion,
ResetUnloggedRelations() recreates the main fork of unlogged
relations by copying the init fork from disk, bypassing shared
buffers. As a result, the main fork could be recreated from a stale
init fork instead of the WAL-replayed page.

Fix this by introducing a helper to flush init fork buffers
immediately, and make seq_redo() use it. As a result, the main fork
of an unlogged sequence is recreated from the up-to-date init fork on
disk, allowing the unlogged sequence to be read successfully after
standby promotion.

Backpatch to v15, where unlogged sequences were introduced.
---
 src/backend/access/hash/hash_xlog.c           | 29 ++--------------
 src/backend/access/transam/xlogutils.c        | 26 +++++++++++++-
 src/backend/commands/sequence.c               |  1 +
 src/include/access/xlogutils.h                |  2 ++
 src/test/recovery/meson.build                 |  1 +
 .../t/054_unlogged_sequence_promotion.pl      | 34 +++++++++++++++++++
 6 files changed, 66 insertions(+), 27 deletions(-)
 create mode 100644 src/test/recovery/t/054_unlogged_sequence_promotion.pl

diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e8e06c62a95..cd9617533c2 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -32,7 +32,6 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	XLogRecPtr	lsn = record->EndRecPtr;
 	Page		page;
 	Buffer		metabuf;
-	ForkNumber	forknum;
 
 	xl_hash_init_meta_page *xlrec = (xl_hash_init_meta_page *) XLogRecGetData(record);
 
@@ -44,16 +43,7 @@ hash_xlog_init_meta_page(XLogReaderState *record)
 	page = (Page) BufferGetPage(metabuf);
 	PageSetLSN(page, lsn);
 	MarkBufferDirty(metabuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(metabuf);
+	XLogFlushBufferForRedoIfInit(record, 0, metabuf);
 
 	/* all done */
 	UnlockReleaseBuffer(metabuf);
@@ -71,7 +61,6 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	Page		page;
 	HashMetaPage metap;
 	uint32		num_buckets;
-	ForkNumber	forknum;
 
 	xl_hash_init_bitmap_page *xlrec = (xl_hash_init_bitmap_page *) XLogRecGetData(record);
 
@@ -82,16 +71,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 	_hash_initbitmapbuffer(bitmapbuf, xlrec->bmsize, true);
 	PageSetLSN(BufferGetPage(bitmapbuf), lsn);
 	MarkBufferDirty(bitmapbuf);
-
-	/*
-	 * Force the on-disk state of init forks to always be in sync with the
-	 * state in shared buffers.  See XLogReadBufferForRedoExtended.  We need
-	 * special handling for init forks as create index operations don't log a
-	 * full page image of the metapage.
-	 */
-	XLogRecGetBlockTag(record, 0, NULL, &forknum, NULL);
-	if (forknum == INIT_FORKNUM)
-		FlushOneBuffer(bitmapbuf);
+	XLogFlushBufferForRedoIfInit(record, 0, bitmapbuf);
 	UnlockReleaseBuffer(bitmapbuf);
 
 	/* add the new bitmap page to the metapage's list of bitmaps */
@@ -112,10 +92,7 @@ hash_xlog_init_bitmap_page(XLogReaderState *record)
 
 		PageSetLSN(page, lsn);
 		MarkBufferDirty(metabuf);
-
-		XLogRecGetBlockTag(record, 1, NULL, &forknum, NULL);
-		if (forknum == INIT_FORKNUM)
-			FlushOneBuffer(metabuf);
+		XLogFlushBufferForRedoIfInit(record, 1, metabuf);
 	}
 	if (BufferIsValid(metabuf))
 		UnlockReleaseBuffer(metabuf);
diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index d63364fd506..2352dcd607e 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -335,6 +335,28 @@ XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id)
 	return buf;
 }
 
+/*
+ * If a redo routine modified an init fork, flush the buffer immediately.
+ *
+ * At the end of crash recovery the init forks of unlogged relations are
+ * copied to the main fork directly from disk, without going through shared
+ * buffers. Therefore, redo routines that update init forks without
+ * restoring a full-page image must call this after setting the page LSN and
+ * marking the buffer dirty.
+ */
+void
+XLogFlushBufferForRedoIfInit(XLogReaderState *record, uint8 block_id,
+							 Buffer buffer)
+{
+	ForkNumber	forknum;
+
+	Assert(BufferIsValid(buffer));
+
+	XLogRecGetBlockTag(record, block_id, NULL, &forknum, NULL);
+	if (forknum == INIT_FORKNUM)
+		FlushOneBuffer(buffer);
+}
+
 /*
  * XLogReadBufferForRedoExtended
  *		Like XLogReadBufferForRedo, but with extra options.
@@ -412,7 +434,9 @@ XLogReadBufferForRedoExtended(XLogReaderState *record,
 		 * At the end of crash recovery the init forks of unlogged relations
 		 * are copied, without going through shared buffers. So we need to
 		 * force the on-disk state of init forks to always be in sync with the
-		 * state in shared buffers.
+		 * state in shared buffers. Use XLogFlushBufferForRedoIfInit() for
+		 * redo routines that dirty init-fork buffers without restoring a
+		 * full-page image.
 		 */
 		if (forknum == INIT_FORKNUM)
 			FlushOneBuffer(*buf);
diff --git a/src/backend/commands/sequence.c b/src/backend/commands/sequence.c
index e0af32075d1..5eda26df455 100644
--- a/src/backend/commands/sequence.c
+++ b/src/backend/commands/sequence.c
@@ -1893,6 +1893,7 @@ seq_redo(XLogReaderState *record)
 
 	memcpy(page, localpage, BufferGetPageSize(buffer));
 	MarkBufferDirty(buffer);
+	XLogFlushBufferForRedoIfInit(record, 0, buffer);
 	UnlockReleaseBuffer(buffer);
 
 	pfree(localpage);
diff --git a/src/include/access/xlogutils.h b/src/include/access/xlogutils.h
index 5b77b11f508..d0545248abf 100644
--- a/src/include/access/xlogutils.h
+++ b/src/include/access/xlogutils.h
@@ -84,6 +84,8 @@ typedef struct ReadLocalXLogPageNoWaitPrivate
 extern XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record,
 											uint8 block_id, Buffer *buf);
 extern Buffer XLogInitBufferForRedo(XLogReaderState *record, uint8 block_id);
+extern void XLogFlushBufferForRedoIfInit(XLogReaderState *record,
+										 uint8 block_id, Buffer buffer);
 extern XLogRedoAction XLogReadBufferForRedoExtended(XLogReaderState *record,
 													uint8 block_id,
 													ReadBufferMode mode, bool get_cleanup_lock,
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 42059801ce2..5453e1aa6fa 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -47,6 +47,7 @@ tests += {
       't/043_vacuum_horizon_floor.pl',
       't/043_no_contrecord_switch.pl',
       't/045_archive_restartpoint.pl',
+      't/054_unlogged_sequence_promotion.pl',
     ],
   },
 }
diff --git a/src/test/recovery/t/054_unlogged_sequence_promotion.pl b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
new file mode 100644
index 00000000000..96d1e4bf18b
--- /dev/null
+++ b/src/test/recovery/t/054_unlogged_sequence_promotion.pl
@@ -0,0 +1,34 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that unlogged sequences created on a primary can be read after
+# promotion of a standby that replayed their init fork.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node_primary = PostgreSQL::Test::Cluster->new('primary');
+$node_primary->init(allows_streaming => 1);
+$node_primary->start;
+
+my $backup_name = 'my_backup';
+$node_primary->backup($backup_name);
+
+my $node_standby = PostgreSQL::Test::Cluster->new('standby');
+$node_standby->init_from_backup($node_primary, $backup_name,
+	has_streaming => 1);
+$node_standby->start;
+
+# Create the unlogged sequence after the standby has started, so its init fork
+# is generated by WAL replay on the standby.
+$node_primary->safe_psql('postgres', "CREATE UNLOGGED SEQUENCE ulseq");
+$node_primary->wait_for_replay_catchup($node_standby);
+
+$node_standby->promote;
+
+is($node_standby->safe_psql('postgres', "SELECT nextval('ulseq')"),
+	1, 'unlogged sequence can be read after standby promotion');
+
+done_testing();
-- 
2.53.0

---

From: vignesh C <[email-masked]>
Date: Mon, 29 Jun 2026 21:31:14 +0530

> backpatched to v15, while pg_get_sequence_data() was introduced in

Thanks for the updated patches.  I verified that the issue occurs with
nextval() on all supported branches up to v15, where unlogged
sequences are available. The corresponding back patches apply cleanly
to their respective branches and fix the issue.  I also checked other
unlogged objects but couldn't reproduce a similar issue with them.

Overall, the patches look good to me.

Regards,
Vignesh

---

From: Fujii Masao <[email-masked]>
Date: Tue, 30 Jun 2026 08:55:57 +0900

> Overall, the patches look good to me.

Thanks for the review! I've pushed the patch.

Regards,

-- 
Fujii Masao

---

From: Fujii Masao <[email-masked]>
Date: Thu, 2 Jul 2026 01:08:44 +0900

> postgres=# select pg_get_sequence_data(99999999);

Yes. If the specified OID does not exist, the function returns a row of
NULL values. However, if the object is specified by name and it does
not exist, an error is raised because the argument has type regclass.

That's why I find the current wording "This function returns a row of
NULL values if the sequence does not exist." a bit misleading.

How about something like this instead?

    This function returns a row of NULL values if the specified relation
    OID does not exist, if it is not a sequence, if the current user lacks
    <literal>SELECT</literal> privilege on the sequence, if the sequence
    is another session's temporary sequence, or if it is an unlogged
    sequence on a standby server.

> Nice! This looks more explicit and clarifying. The patch LGTM.

Thanks for the review!

I've updated the patch furthermore. Attached.

Regards,

-- 
Fujii Masao

---

From: Amit Kapila <[email-masked]>
Date: Thu, 2 Jul 2026 15:25:13 +0530

>     sequence on a standby server.

Sounds reasonable. But after this we don't need the next para to say:
"It requires <literal>SELECT</literal> privilege on the sequence.".
See attached.

> I've updated the patch furthermore. Attached.

LGTM.

-- 
With Regards,
Amit Kapila.

---

From: Fujii Masao <[email-masked]>
Date: Wed, 8 Jul 2026 18:19:44 +0900

> "It requires <literal>SELECT</literal> privilege on the sequence.".

Thanks for the patch! I've pushed it.

> > I've updated the patch furthermore. Attached.

Thanks for the review! I've pushed this as well.

Regards,

-- 
Fujii Masao