[PATCH] Fix sequence value may rollback after CREATE DATABASE TEMPLATE with WAL_LOG strategy

Started by Daisuke Higuchi6 months ago3 messageshackers

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1Daisuke Higuchi
higuchi.daisuke11@gmail.com

Hi

I found that "CREATE DATABASE ... TEMPLATE" with WAL_LOG strategy can
cause sequence values to rollback after a streaming replication failover.

When creating a new database with "CREATE DATABASE ... TEMPLATE" from
a template database that has sequences, calling nextval() on those
sequences in the new database causes the primary to have a higher
last_value than the standby temporarily.
When a failover occurs and the standby is promoted in this state, the
sequence value appears to have rollbacked on the new primary.
I found this issue in PostgreSQL version 15, but I've confirmed that it also
happens on the master branch.

I show the example as follows.
After creating a database with "CREATE DATABASE ... TEMPLATE",
the sequence initially has last_value = 5:

-- Initial state on both Primary and Standby:
=====
test_db=# SELECT last_value, log_cnt, is_called FROM test_seq;
last_value | log_cnt | is_called
------------+---------+-----------
5 | 28 | t
(1 row)
=====

When I run nextval() 5 times, the values of primary and standby are
as follows. The values in the standby are not changed.

-- Primary:
=====
test_db=# SELECT last_value, log_cnt, is_called FROM test_seq;
last_value | log_cnt | is_called
------------+---------+-----------
10 | 23 | t
(1 row)
=====

-- Standby:
=====
test_db=# SELECT last_value, log_cnt, is_called FROM test_seq;
last_value | log_cnt | is_called
------------+---------+-----------
5 | 28 | t
(1 row)
=====

When I run nextval() in this state, it returns 6 even though 6 - 10
were already returned on the previous primary. It means that the
sequence rollback after a failover.
I understand that sequences cannot be used to obtain "gapless", but I
think it is an unintended behavior that sequence values rollback.
I attached the script to reproduce this issue and the patch to fix.

In the attached patch, during "CREATE DATABASE ... TEMPLATE" with
WAL_LOG strategy, the sequence's log_cnt is reset to 0 so that
SEQ_LOG_VALS (32) values are fetched in advance on the next nextval()
call. This ensures that the standby's last_value is greater than or
equal to the primary's last_value.
And, this patch opens sequence page using readBufferWithoutRelcache()
without relying on relcache entries and resets log_cnt. This follows
the same approach as ScanSourceDatabasePGClass().
Note that this issue does not occur with FILE_COPY strategy because
this performs a checkpoint internally and a WAL record to fetch
SEQ_LOG_VALS in advance is always emitted on the next nextval() call.
However, I could not apply the same approach because I understand the
WAL_LOG strategy is designed to avoid checkpoints.

Regards,
Daisuke, Higuchi

Attachments:

reproduce_script_sequence_rollback_issue.shapplication/x-sh; name=reproduce_script_sequence_rollback_issue.shDownload
v1_0002_fix_sequence_rollback_by_WAL_LOG_test.patchapplication/x-patch; name=v1_0002_fix_sequence_rollback_by_WAL_LOG_test.patchDownload+82-0
v1_0001_fix_sequence_rollback_by_WAL_LOG.patchapplication/x-patch; name=v1_0001_fix_sequence_rollback_by_WAL_LOG.patchDownload+61-0
#2Bharath Rupireddy
bharath.rupireddyforpostgres@gmail.com
In reply to: Daisuke Higuchi (#1)
Re: [PATCH] Fix sequence value may rollback after CREATE DATABASE TEMPLATE with WAL_LOG strategy

Hi,

On Mon, Jun 15, 2026 at 9:02 PM Daisuke Higuchi
<higuchi.daisuke11@gmail.com> wrote:

I found that "CREATE DATABASE ... TEMPLATE" with WAL_LOG strategy can
cause sequence values to rollback after a streaming replication failover.

When creating a new database with "CREATE DATABASE ... TEMPLATE" from
a template database that has sequences, calling nextval() on those
sequences in the new database causes the primary to have a higher
last_value than the standby temporarily.
When a failover occurs and the standby is promoted in this state, the
sequence value appears to have rollbacked on the new primary.
I found this issue in PostgreSQL version 15, but I've confirmed that it also
happens on the master branch.

Nice catch!

Thanks for reporting!

I show the example as follows.

In the attached patch, during "CREATE DATABASE ... TEMPLATE" with
WAL_LOG strategy, the sequence's log_cnt is reset to 0 so that
SEQ_LOG_VALS (32) values are fetched in advance on the next nextval()
call. This ensures that the standby's last_value is greater than or
equal to the primary's last_value.
And, this patch opens sequence page using readBufferWithoutRelcache()
without relying on relcache entries and resets log_cnt. This follows
the same approach as ScanSourceDatabasePGClass().
Note that this issue does not occur with FILE_COPY strategy because
this performs a checkpoint internally and a WAL record to fetch
SEQ_LOG_VALS in advance is always emitted on the next nextval() call.
However, I could not apply the same approach because I understand the
WAL_LOG strategy is designed to avoid checkpoints.

Some comments on the patch:

1/
@@ -218,6 +222,10 @@ CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid,
/* Copy relation storage from source to the destination. */
CreateAndCopyRelationData(srcrlocator, dstrlocator, relinfo->permanent);

+ /* Reset log_cnt for sequences to ensure WAL on first nextval() */
+ if (relinfo->relkind == RELKIND_SEQUENCE)
+ ResetSequenceLogCnt(dstrlocator, relinfo->permanent);

What happens if we reset the log_cnt for some sequences and the CREATE
DATABASE then fails (say, while copying other remaining relations'
data pages)? We would have written reset WAL records, but the CREATE
DATABASE failed - and those WAL records now not only need to be
replayed for crash recovery but also flow through to standbys and
logical replication clients.

2/ Don't we need to gate the WAL logging in ResetSequenceLogCnt with
RelationNeedsWAL(rel)?

3/ WAL logging in ResetSequenceLogCnt and other sequence.c look mostly
similar - try to dedup it with a similar one there?

4/ Why not move ResetSequenceLogCnt closer to its friends in sequence.c?

5/ Do we need any special handling for temporary sequences?

6/ Instead of a new file, why not add the test case to existing
src/test/recovery/t/034_create_database.pl?

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

#3Daisuke Higuchi
higuchi.daisuke11@gmail.com
In reply to: Bharath Rupireddy (#2)
Re: [PATCH] Fix sequence value may rollback after CREATE DATABASE TEMPLATE with WAL_LOG strategy

Hi, thank you for your review and comments!

1/ What happens if we reset the log_cnt for some sequences and
the CREATE DATABASE then fails (say, while copying other
remaining relations' data pages)? We would have written reset
WAL records, but the CREATE DATABASE failed - and those WAL
records now not only need to be replayed for crash recovery but
also flow through to standbys and logical replication clients.

If the CREATE DATABASE fails in the middle of process, all
relations including sequences are properly cleaned up with
createdb_failure_callback. In my patch, WAL records are output
for sequences additionally, but note that WAL_LOG strategy already
writes WAL for every copied block and the sequence reset WAL is
just one more record in the same category.
Also, resetting the log_cnt is performed on the newly copied
database. Therefore, even if CREATE DATABASE fails in the middle
of process, the sequence of the source database is not affected.
And, in logical replication, sequences are not replicated. Even in
PostgreSQL 19, instead of decoding WAL, ALTER SUBSCRIPTION
REFRESH connects to publisher and gets the value and replicates
to subscribers. Therefore, I think any special considerations
for logical replication are not necessary.

https://www.postgresql.org/docs/19/logical-replication-sequences.html
https://github.com/postgres/postgres/blob/master/src/include/access/rmgrlist.h

2/ Don't we need to gate the WAL logging in
ResetSequenceLogCnt with RelationNeedsWAL(rel)?

The current patch uses "if (permanent)". This is similar to
RelationNeedsWAL(rel).
The "permanent" field of CreateDBRelInfo contains the information
about whether the relation is permanent. ResetSequenceLogCnt uses
the information in this field to decide whether to write a WAL
record. This logic is from RelationCopyStorageUsingBuffer.

3/ WAL logging in ResetSequenceLogCnt and other sequence.c look
mostly similar - try to dedup it with a similar one there?

Certainly, the existing code has similar WAL logging processing
in the three functions of sequence.c.
I think it is possible to dedup the WAL logging process and
create a shared function, and to call that new function from
three existing functions and ResetSequenceLogCnt function.
However, I think this is a bit of refactoring. With this bug
fix, should I refactor as well? (I did not include it in this
reply now, but I can provide the refactored patch.)

4/ Why not move ResetSequenceLogCnt closer to its friends in
sequence.c?

I certainly thought it would be better to move it to sequence.c,
so I fixed it.

5/ Do we need any special handling for temporary sequences?

It's unnecessary. Temporary relations do not need to be
replicated to the standby with streaming replication.
Also, temporary relations are not appended to the rlocatorlist.
This is determined by ScanSourceDatabasePgClassTuple.

===
if (classForm->reltablespace == GLOBALTABLESPACE_OID ||
!RELKIND_HAS_STORAGE(classForm->relkind) ||
classForm->relpersistence == RELPERSISTENCE_TEMP)
return NULL;
===

6/ Instead of a new file, why not add the test case to existing
src/test/recovery/t/034_create_database.pl?

Adding to the existing test file makes sense for me too. Updated.

I attached the updated v2 patch set.

Regards,

Attachments:

t248552_3
v2-0002-test-Reset-sequence-log_cnt-during-WAL_LOG-copy.patchapplication/octet-stream; name=v2-0002-test-Reset-sequence-log_cnt-during-WAL_LOG-copy.patchDownload+74-0
v2-0001-fix-Reset-sequence-log_cnt-during-WAL_LOG-copy.patchapplication/octet-stream; name=v2-0001-fix-Reset-sequence-log_cnt-during-WAL_LOG-copy.patchDownload+63-0