[PATCH] Preserve replication origin OIDs in pg_upgrade

Поиск
Список
Период
Сортировка
Искать

[PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
Hello hackers,

The idea for this patch came up during discussions in the thread [1]
on migration of the pg_commit_ts directory as part of pg_upgrade.
There was a problem raised by Sawada-san in that thread which this
patch addresses. [2]

The problem:
The pg_commit_ts directory stores commit-timestamp records for each
transaction, and each record embeds the replication origin ID
(roident) that identifies which subscription wrote that transaction.
When pg_upgrade migrates a subscriber, the pg_commit_ts directory is
copied directly from the old cluster to the new cluster. This means
those embedded roidents must remain valid in the new cluster.  When
pg_upgrade migrates a subscriber, CREATE SUBSCRIPTION on the new
cluster calls replorigin_create() which assigns fresh roidents to each
subscription's replication origin. Because subscription OIDs are not
stable across upgrades, the origin names change (e.g. pg_16392 becomes
pg_16403), and consequently the roidents can be assigned differently —
or in the worst case, swapped between subscriptions.

Consider two subscriptions subA and subB with roidents 1 and 2
respectively before upgrade. After upgrade, due to OID reassignment,
subA might get roident 2 and subB might get roident 1. The
commit-timestamp records copied from the old cluster still say roident
1 for rows written by subA, but the new cluster now thinks roident 1
belongs to subB. This causes spurious update_origin_differs conflicts
— the new cluster incorrectly thinks a row was last modified by a
different subscription than it actually was.

This patch attempts to fix this by replicating the roident of the
replication origins of each subscription on migration. This patch also
migrates all replication origins as part of pg_upgrade.

Sequence of Events During Upgrade

1. pg_dumpall dumps all non-subscription replication origins from the
old cluster with their roidents and LSN positions.
2. pg_dump dumps each subscription, but now records the old roident
alongside the subscription info.
3. During restore, pg_dumpall's output recreates non-subscription
origins on the new cluster with their original roidents via
binary_upgrade_create_replication_origin().
4. During per-database restore, CREATE SUBSCRIPTION runs but skips
origin creation.
5. binary_upgrade_set_next_replorigin_oid() creates the origin for
each subscription with the preserved roident.
6. binary_upgrade_replorigin_advance() restores the LSN position for
each subscription.
7. Subscriptions that were running before upgrade are re-enabled.

Please let me know your feedback regarding this patch

[1] - https://www.postgresql.org/message-id/flat/182311743703924%40mail.yandex.ru
[2] - https://www.postgresql.org/message-id/CAD21AoDG8zQpHHfw7OvaEy7W0ZSyP%3D_dS-hrcquJ3C_ctMDmMQ%40mail.gmail.com

regards,
Ajin Cherian
Fujitsu Australia

RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Ajin,

> Sequence of Events During Upgrade
> 
> 1. pg_dumpall dumps all non-subscription replication origins from the
> old cluster with their roidents and LSN positions.
> 2. pg_dump dumps each subscription, but now records the old roident
> alongside the subscription info.
> 3. During restore, pg_dumpall's output recreates non-subscription
> origins on the new cluster with their original roidents via
> binary_upgrade_create_replication_origin().

To confirm, why do we have to handle separately for subscription-associated
origins? I'm thinking it's not needed if the subscription's OID is preserved
during the upgrade. 

I checked the old thread to preserve it [1], but it could not be accepted because
there are no strong motivations. But I feel this is the good reason to do so now.

How do you feel?

[1]: https://www.postgresql.org/message-id/CALDaNm2Wj63VcbB0SY2NECHr1mKM1YSaV1ZydrdQVxyox2O2hg%40mail.gmail.com

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Wed, 29 Apr 2026 at 14:11, Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Ajin,
>
> > Sequence of Events During Upgrade
> >
> > 1. pg_dumpall dumps all non-subscription replication origins from the
> > old cluster with their roidents and LSN positions.
> > 2. pg_dump dumps each subscription, but now records the old roident
> > alongside the subscription info.
> > 3. During restore, pg_dumpall's output recreates non-subscription
> > origins on the new cluster with their original roidents via
> > binary_upgrade_create_replication_origin().
>
> To confirm, why do we have to handle separately for subscription-associated
> origins? I'm thinking it's not needed if the subscription's OID is preserved
> during the upgrade.

+1 to preserve the subscription OID. This should make preserving
replication origin easier.

> I checked the old thread to preserve it [1], but it could not be accepted because
> there are no strong motivations. But I feel this is the good reason to do so now.

Here is a rebased version of the patch.

Regards,
Vignesh

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Apr 29, 2026 at 2:11 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Ajin,
>
> > Sequence of Events During Upgrade
> >
> > 1. pg_dumpall dumps all non-subscription replication origins from the
> > old cluster with their roidents and LSN positions.
> > 2. pg_dump dumps each subscription, but now records the old roident
> > alongside the subscription info.
> > 3. During restore, pg_dumpall's output recreates non-subscription
> > origins on the new cluster with their original roidents via
> > binary_upgrade_create_replication_origin().
>
> To confirm, why do we have to handle separately for subscription-associated
> origins? I'm thinking it's not needed if the subscription's OID is preserved
> during the upgrade.
>

I’m not sure how preserving the subscription OID would ensure that the
origin ID is also preserved for sub-associated origins. Could you
please elaborate?

As I understand it, roident values are assigned independently during
origin creation. Even if subscription OIDs are preserved, the origin
IDs could still be reassigned differently on the new cluster. For
example, suppose we have two subscriptions, sub1 and sub2, with
roident values 2 and 3, assuming 1 was previously used and dropped.
After upgrade, origin creation may start allocating from 1 again,
resulting in roident values 1 and 2 instead. Since pg_commit_ts stores
the numeric roident, not the origin name, this mismatch could still
lead to incorrect conflict detection. Wouldn’t that result in the same
wrong conflict detection issue we are trying to avoid?
Please let me know if my understanding is wrong.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Thu, Apr 30, 2026 at 4:52 PM vignesh C  wrote:
>
> On Wed, 29 Apr 2026 at 14:11, Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > Dear Ajin,
> >
> > > Sequence of Events During Upgrade
> > >
> > > 1. pg_dumpall dumps all non-subscription replication origins from the
> > > old cluster with their roidents and LSN positions.
> > > 2. pg_dump dumps each subscription, but now records the old roident
> > > alongside the subscription info.
> > > 3. During restore, pg_dumpall's output recreates non-subscription
> > > origins on the new cluster with their original roidents via
> > > binary_upgrade_create_replication_origin().
> >
> > To confirm, why do we have to handle separately for subscription-associated
> > origins? I'm thinking it's not needed if the subscription's OID is preserved
> > during the upgrade.
>
> +1 to preserve the subscription OID. This should make preserving
> replication origin easier.
>
> > I checked the old thread to preserve it [1], but it could not be accepted because
> > there are no strong motivations. But I feel this is the good reason to do so now.
>
> Here is a rebased version of the patch.


Thanks Vignesh for the patch. I have used your patch as 0001 and
created mine on top of that as 0002. Like Kuroda-san said, with your
patch, I no longer need to have special handling of subscription
replication origins when pg_dumpall creates all replication origins on
the new cluster as now the name of origin is also guaranteed to be the
same because the replication origin name is created using the oid of
the subscription which is now the same because of the the changes in
patch 0001.
Here's v3 with the updated changes.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
On Thu, Apr 30, 2026 at 7:37 PM shveta malik  wrote:
>
>
> I’m not sure how preserving the subscription OID would ensure that the
> origin ID is also preserved for sub-associated origins. Could you
> please elaborate?
>
> As I understand it, roident values are assigned independently during
> origin creation. Even if subscription OIDs are preserved, the origin
> IDs could still be reassigned differently on the new cluster. For
> example, suppose we have two subscriptions, sub1 and sub2, with
> roident values 2 and 3, assuming 1 was previously used and dropped.
> After upgrade, origin creation may start allocating from 1 again,
> resulting in roident values 1 and 2 instead. Since pg_commit_ts stores
> the numeric roident, not the origin name, this mismatch could still
> lead to incorrect conflict detection. Wouldn’t that result in the same
> wrong conflict detection issue we are trying to avoid?
> Please let me know if my understanding is wrong.

In the first patch, the replication origins were duplicated from the
old cluster to the new with matching roidents and ronames. This
couldn't be done for subscription replication origins as subscriptions
weren't preserving OIDs on the new cluster and therefore the
corresponding roname which is derived from the subscription OIDs also
differed. Now with matching roname and roident, all the replication
origins from the old cluster can be copied over to the new cluster in
one shot.

regards,
Ajin Cherian
Fujitsu Australia


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, May 6, 2026 at 11:13 AM Ajin Cherian  wrote:
>
> On Thu, Apr 30, 2026 at 7:37 PM shveta malik  wrote:
> >
> >
> > I’m not sure how preserving the subscription OID would ensure that the
> > origin ID is also preserved for sub-associated origins. Could you
> > please elaborate?
> >
> > As I understand it, roident values are assigned independently during
> > origin creation. Even if subscription OIDs are preserved, the origin
> > IDs could still be reassigned differently on the new cluster. For
> > example, suppose we have two subscriptions, sub1 and sub2, with
> > roident values 2 and 3, assuming 1 was previously used and dropped.
> > After upgrade, origin creation may start allocating from 1 again,
> > resulting in roident values 1 and 2 instead. Since pg_commit_ts stores
> > the numeric roident, not the origin name, this mismatch could still
> > lead to incorrect conflict detection. Wouldn’t that result in the same
> > wrong conflict detection issue we are trying to avoid?
> > Please let me know if my understanding is wrong.
>
> In the first patch, the replication origins were duplicated from the
> old cluster to the new with matching roidents and ronames. This
> couldn't be done for subscription replication origins as subscriptions
> weren't preserving OIDs on the new cluster and therefore the
> corresponding roname which is derived from the subscription OIDs also
> differed.

Okay. I think you did not post the first patch you are referring to
here. V2 was posted directly. But I see your point.

> Now with matching roname and roident, all the replication
> origins from the old cluster can be copied over to the new cluster in
> one shot.

Okay.  Will review the patch.

thanks
Shveta


RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Ajin,

Thanks for updating the patch. Let me share my two high-level comments.

1.
Can you clarify the policy for backward compatibility? In other words, should we
preserve subscription OIDs and migrate replication origins from PG19- instances?
Similar commits 9a17be1 and 29d0a77 did not allow migrating objects from released
versions.

2.
I found that other objects use global variables like binary_upgrade_next_xxx to
specify the next OID. Can we follow the manner even for replication origins?
Or it's not a good approach because of some reasons?

BTW, cfbot got angry with your patch.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello!

+ appendPQExpBuffer(buf,
+   "SELECT pg_catalog.binary_upgrade_create_replication_origin('%u'::pg_catalog.oid,
'%s'::pg_catalog.name",
+   roident, roname);
+
+ if (!PQgetisnull(res, i, i_remotelsn))
+ {
+ appendPQExpBuffer(buf, ", '%s'::pg_catalog.pg_lsn",
+   PQgetvalue(res, i, i_remotelsn));
+ }
+ else

Isn't some string escaping missing from this? It doesn't seem like the
most likely SQL injection target, but could still cause surprises.
Could be even verified by a test case using
pg_replication_origin_create('O''Brien_replica')

- if (old_cluster.nsubs > max_active_replication_origins)
+ if (old_cluster.nrepl_origins > max_active_replication_origins)
  pg_fatal("\"max_active_replication_origins\" (%d) must be greater
than or equal to the number of "
  "subscriptions (%d) on the old cluster",
- max_active_replication_origins, old_cluster.nsubs);
+ max_active_replication_origins, old_cluster.nrepl_origins);

This error message could be misleading now, it's not the number of
subscriptions but the number of replication origins.

+ rel = table_open(ReplicationOriginRelationId, ExclusiveLock);

Do we need an ExclusiveLock, couldn't this instead use a
RowExclusiveLock? In the unlikely situation that another session
inserts the same record, the unique index should be able catch it?


+#include "access/xlogdefs.h"

This seems to be unnecessary?

- appendPQExpBuffer(query, ", '%s');\n", subinfo->suboriginremotelsn);
+ if (fout->remoteVersion < 190000 && subinfo->suboriginremotelsn)
+ {

subinfo->suboriginremotelsn is already checked by the outer if


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
Rebased the patch as it was no longer applying.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Mon, 18 May 2026 at 16:13, Ajin Cherian  wrote:
>
> Rebased the patch as it was no longer applying.
>
Hi Ajin,

I have started reviewing the patch. Here is my comment for v6-0002 patch:

Suppose we have a replication setup: publisher -> subscriber
and we are upgrading subscriber to subscriber_new.
And if initially 'subscriber_new' has a replication origin, upgrading
the cluster can error out.

Example:
We set up a logical replication between publisher node and subscriber node.

On subscriber node:
postgres=# SELECT * FROM pg_replication_origin;
 roident |  roname
---------+----------
       1 | pg_16393
(1 row)

And initially subscriber_new has a replication origin:
postgres=# select pg_replication_origin_create('myname');
 pg_replication_origin_create
------------------------------
                            1
(1 row)

postgres=# SELECT * FROM pg_replication_origin;
 roident | roname
---------+--------
       1 | myname
(1 row)

Now, if we run pg_upgrade to upgrade subscriber node to subscriber_new
node, we get an error:
```
SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
'pg_16393'::pg_catalog.name, '0/01743078'::pg_catalog.pg_lsn);
psql:subscriber_new/pg_upgrade_output.d/20260522T140312.807/dump/pg_upgrade_dump_globals.sql:37:
ERROR:  replication origin with ID 1 already exists
```

This error occurs in "Performing Upgrade" stage. Should we add a check
in the "Performing Consistency Checks" stage so that we don't need to
re-initdb the new cluster to perform the upgrade?
Maybe we can add a check similar to
check_new_cluster_replication_slots(), where pg_upgrade errors out if
the new cluster already contains replication origins. Thoughts?

Thanks,
Shlok Kyal


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Thu, 28 May 2026 at 08:18, Ajin Cherian  wrote:
>
> Fixed this. Added a new check for replication origins and if the new cluster has any existing replication origins, then the check will fail.
>>
>>
>> Few trivial comments:
>>
>> 1)
>>
>> +#include "access/skey.h"
>> +#include "catalog/indexing.h"
>>
>> pg_upgrade_support.c compiles without above.
>>
>
> Removed.
>
>>
>> 2)
>> + Assert(!OidIsValid(rel->rd_rel->reltoastrelid));
>>
>> Is there a reason for this sanity check? I generally do not see a
>> Null-Toast table sanity check after every table_open.
>>
>
> Removed.
>
>>
>> 3)
>>
>> +
>> + /* Dump replication origins */
>> + if (server_version >= 170000 && binary_upgrade && archDumpFormat == archNull)
>> + dumpReplicationOrigins(conn);
>>
>> why the check is for PG17 specifically?
>>
>
> In PG17, we started migrating pg_subscription_rel and the remote LSN during upgrades; prior to that, these were not migrated. Given that change, it also makes sense to migrate replication origins from them. Otherwise, when upgrading from PG17 to a later version, you could end up with a subscription where pg_subscription_rel and the remote LSN are migrated, but the corresponding replication origin is not created.
>
>
>
> On Mon, May 25, 2026 at 5:13 PM shveta malik  wrote:
>>
>>
>> One issue in 002:
>>
>> binary_upgrade_create_replication_origin() has this:
>>
>> + originname = PG_GETARG_NAME(1);
>> +
>> + roname_d = CStringGetTextDatum(NameStr(*originname));
>> +
>>
>> We are getting origin-name (text) into Name-type which can not be more
>> than 64 bytes. So if an origin has name more than 64, it will end up
>> trimming the name post-upgrade.
>>
>> I tried this:
>>
>> Old-setup:
>> postgres=# SELECT
>> pg_replication_origin_create('this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64');
>>  pg_replication_origin_create
>> ------------------------------
>>                             1
>> postgres=# select * from pg_replication_origin;
>>  roident |                                roname
>> ---------+----------------------------------------------------------------------
>>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64
>>
>>
>> Post-upgrade: name got trimmed to 64 length.
>> -------------------------
>> postgres=#  select * from pg_replication_origin;
>>  roident |                             roname
>> ---------+-----------------------------------------------------------------
>>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_li
>>
>> thanks
>> Shveta
>
>
> Fixed this. Now  binary_upgrade_create_replication_origin handles it similarly to the way pg_replication_origin_create handles the name of the origin.

Few comments:
1) pg_dumpall dumps all replication origins, not just subscription
origins and recreates every origin:
SELECT o.*, os.remote_lsn
FROM pg_replication_origin o
LEFT JOIN pg_replication_origin_status os
  ON o.roident = os.local_id

Is pg_upgrade expected to preserve user-created origins?
If so, you can mention this in the commit message

2) Should the table lock be released here, if so should we mention
comments similar to how it is mentioned in
binary_upgarde_add_sub_rel_state:
+ /* Restore the remote_lsn if provided, while still holding the lock */
+ if (!PG_ARGISNULL(2))
+ {
+ XLogRecPtr remote_commit = PG_GETARG_LSN(2);

- ReplicationSlotRelease();
+ replorigin_advance(node, remote_commit, InvalidXLogRecPtr,
+    false /* backward */,
+    false /* WAL log */);
+ }
+
+ table_close(rel, RowExclusiveLock);

3) We can use new style of ereport to exclude '(' before errcode:
3.a)
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("replication origin name is too long"),
+ errdetail("Replication origin names must be no longer than %d bytes.",
+    MAX_RONAME_LEN)));

3.b) Similarly here:
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin with ID %u already exists", node_oid)));

3.c) There are many others, you can search other ereport in the patch
and change it too.

4) Since only one column will be returned here, can we use
"PQgetvalue(res, 0, 0) and remove PQfnumber:
+ res = executeQueryOrDie(conn,
+ "SELECT count(*) AS nrepl_origins "
+ "FROM pg_catalog.pg_replication_origin");
+ i_nrepl_origins = PQfnumber(res, "nrepl_origins");
+ cluster->nrepl_origins = atoi(PQgetvalue(res, 0, i_nrepl_origins));
+ PQclear(res);

5) replorigin_create also has some duplicate code like below, will it
be possible to have a common function so that both of them can use?
/* Check for name collision */
+ ScanKeyInit(&key,
+ Anum_pg_replication_origin_roname,
+ BTEqualStrategyNumber, F_TEXTEQ,
+ roname_d);
+ scan = systable_beginscan(rel, ReplicationOriginNameIndex,
+   true /* indexOK */,
+   SnapshotSelf,
+   1, &key);
+ collides = HeapTupleIsValid(systable_getnext(scan));
+ systable_endscan(scan);
+
+ if (collides)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin \"%s\" already exists",
+ originname)));
+
+ memset(&nulls, 0, sizeof(nulls));
+ memset(&values, 0, sizeof(values));
+
+ values[Anum_pg_replication_origin_roident - 1] = ObjectIdGetDatum(node);
+ values[Anum_pg_replication_origin_roname - 1] = roname_d;
+
+ tuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
+ CatalogTupleInsert(rel, tuple);
+ heap_freetuple(tuple);
+ CommandCounterIncrement();

Regards,
Vignesh


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Thu, 28 May 2026 at 08:18, Ajin Cherian  wrote:
>
>
>
> On Fri, May 22, 2026 at 8:27 PM shveta malik  wrote:
>>
>> On Fri, May 22, 2026 at 3:16 PM Shlok Kyal  wrote:
>> >
>> > On Mon, 18 May 2026 at 16:13, Ajin Cherian  wrote:
>> > >
>> > > Rebased the patch as it was no longer applying.
>> > >
>> > Hi Ajin,
>> >
>> > I have started reviewing the patch. Here is my comment for v6-0002 patch:
>> >
>> > Suppose we have a replication setup: publisher -> subscriber
>> > and we are upgrading subscriber to subscriber_new.
>> > And if initially 'subscriber_new' has a replication origin, upgrading
>> > the cluster can error out.
>> >
>> > Example:
>> > We set up a logical replication between publisher node and subscriber node.
>> >
>> > On subscriber node:
>> > postgres=# SELECT * FROM pg_replication_origin;
>> >  roident |  roname
>> > ---------+----------
>> >        1 | pg_16393
>> > (1 row)
>> >
>> > And initially subscriber_new has a replication origin:
>> > postgres=# select pg_replication_origin_create('myname');
>> >  pg_replication_origin_create
>> > ------------------------------
>> >                             1
>> > (1 row)
>> >
>> > postgres=# SELECT * FROM pg_replication_origin;
>> >  roident | roname
>> > ---------+--------
>> >        1 | myname
>> > (1 row)
>> >
>> > Now, if we run pg_upgrade to upgrade subscriber node to subscriber_new
>> > node, we get an error:
>> > ```
>> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
>> > 'pg_16393'::pg_catalog.name, '0/01743078'::pg_catalog.pg_lsn);
>> > psql:subscriber_new/pg_upgrade_output.d/20260522T140312.807/dump/pg_upgrade_dump_globals.sql:37:
>> > ERROR:  replication origin with ID 1 already exists
>> > ```
>> >
>> > This error occurs in "Performing Upgrade" stage. Should we add a check
>> > in the "Performing Consistency Checks" stage so that we don't need to
>> > re-initdb the new cluster to perform the upgrade?
>> > Maybe we can add a check similar to
>> > check_new_cluster_replication_slots(), where pg_upgrade errors out if
>> > the new cluster already contains replication origins. Thoughts?
>>
>> +1. I had the same thought while reviewing the patch today. We should
>> have it unless there is a reason we have avoided it??
>
>
> Fixed this. Added a new check for replication origins and if the new cluster has any existing replication origins, then the check will fail.
>>
>>
>> Few trivial comments:
>>
>> 1)
>>
>> +#include "access/skey.h"
>> +#include "catalog/indexing.h"
>>
>> pg_upgrade_support.c compiles without above.
>>
>
> Removed.
>
>>
>> 2)
>> + Assert(!OidIsValid(rel->rd_rel->reltoastrelid));
>>
>> Is there a reason for this sanity check? I generally do not see a
>> Null-Toast table sanity check after every table_open.
>>
>
> Removed.
>
>>
>> 3)
>>
>> +
>> + /* Dump replication origins */
>> + if (server_version >= 170000 && binary_upgrade && archDumpFormat == archNull)
>> + dumpReplicationOrigins(conn);
>>
>> why the check is for PG17 specifically?
>>
>
> In PG17, we started migrating pg_subscription_rel and the remote LSN during upgrades; prior to that, these were not migrated. Given that change, it also makes sense to migrate replication origins from them. Otherwise, when upgrading from PG17 to a later version, you could end up with a subscription where pg_subscription_rel and the remote LSN are migrated, but the corresponding replication origin is not created.
>
>
>
> On Mon, May 25, 2026 at 5:13 PM shveta malik  wrote:
>>
>>
>> One issue in 002:
>>
>> binary_upgrade_create_replication_origin() has this:
>>
>> + originname = PG_GETARG_NAME(1);
>> +
>> + roname_d = CStringGetTextDatum(NameStr(*originname));
>> +
>>
>> We are getting origin-name (text) into Name-type which can not be more
>> than 64 bytes. So if an origin has name more than 64, it will end up
>> trimming the name post-upgrade.
>>
>> I tried this:
>>
>> Old-setup:
>> postgres=# SELECT
>> pg_replication_origin_create('this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64');
>>  pg_replication_origin_create
>> ------------------------------
>>                             1
>> postgres=# select * from pg_replication_origin;
>>  roident |                                roname
>> ---------+----------------------------------------------------------------------
>>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64
>>
>>
>> Post-upgrade: name got trimmed to 64 length.
>> -------------------------
>> postgres=#  select * from pg_replication_origin;
>>  roident |                             roname
>> ---------+-----------------------------------------------------------------
>>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_li
>>
>> thanks
>> Shveta
>
>
> Fixed this. Now  binary_upgrade_create_replication_origin handles it similarly to the way pg_replication_origin_create handles the name of the origin.
>
> Here's an updated version v7 containing these fixes.

Hi Ajin,
I have reviewed the patch and here are some comments:

1. I want to clarify, what is the expected behaviour when we upgrade
the postgres instance from version <= 16 to "HEAD + patch"?
-   ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
sizeof(originname));
-   replorigin_create(originname);
+   if (!IsBinaryUpgrade)
+   {
+       ReplicationOriginNameForLogicalRep(subid, InvalidOid,
originname, sizeof(originname));
+       replorigin_create(originname);
+   }
and
+           /* Dump replication origins */
+           if (server_version >= 170000 && binary_upgrade &&
archDumpFormat == archNull)
+               dumpReplicationOrigins(conn);

When the postgres instance with subscription is updated from PG 16 (or
less) to HEAD, the replication origin is created as we do not have "if
(!IsBinaryUpgrade)" check in HEAD,
whereas when the similar instance is upgraded to "HEAD + patch", no
replication origin is present after the upgrade.
Is this difference in the behaviour between HEAD and "HEAD + patch" expected?

2.a) Can we replace:
+   /* Check for OID collision */
+   ScanKeyInit(&key,
+               Anum_pg_replication_origin_roident,
+               BTEqualStrategyNumber, F_OIDEQ,
+               ObjectIdGetDatum(node));
+   scan = systable_beginscan(rel, ReplicationOriginIdentIndex,
+                             true /* indexOK */,
+                             SnapshotSelf,
+                             1, &key);
+   collides = HeapTupleIsValid(systable_getnext(scan));
+   systable_endscan(scan);
+
+   if (collides)
+       ereport(ERROR,
+               (errcode(ERRCODE_DUPLICATE_OBJECT),
+                errmsg("replication origin with ID %u already
exists", node_oid)));

with:
if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
        ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
                       errmsg("replication origin with ID %u already
exists", node_oid));

2.b) Similarly, Can we replace:
+   /* Check for name collision */
+   ScanKeyInit(&key,
+               Anum_pg_replication_origin_roname,
+               BTEqualStrategyNumber, F_TEXTEQ,
+               roname_d);
+   scan = systable_beginscan(rel, ReplicationOriginNameIndex,
+                             true /* indexOK */,
+                             SnapshotSelf,
+                             1, &key);
+   collides = HeapTupleIsValid(systable_getnext(scan));
+   systable_endscan(scan);
+
+   if (collides)
+       ereport(ERROR,
+               (errcode(ERRCODE_DUPLICATE_OBJECT),
+                errmsg("replication origin \"%s\" already exists",
+                       originname)));
with:
    if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
        ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
                       errmsg("replication origin \"%s\" already
exists", originname));

This will make the code smaller and easy to read. Thoughts?

Thanks,
Shlok Kyal


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, May 28, 2026 at 8:18 AM Ajin Cherian  wrote:
>
>
>
>> 3)
>>
>> +
>> + /* Dump replication origins */
>> + if (server_version >= 170000 && binary_upgrade && archDumpFormat == archNull)
>> + dumpReplicationOrigins(conn);
>>
>> why the check is for PG17 specifically?
>>
>
> In PG17, we started migrating pg_subscription_rel and the remote LSN during upgrades; prior to that, these were not migrated. Given that change, it also makes sense to migrate replication origins from them. Otherwise, when upgrading from PG17 to a later version, you could end up with a subscription where pg_subscription_rel and the remote LSN are migrated, but the corresponding replication origin is not created.
>

Okay, please add a comment in code for this.

Please find a few comments on v007:

1)

+ node = (ReplOriginId) node_oid;
+ originname = text_to_cstring(PG_GETARG_TEXT_PP(1));
+
+ if (strlen(originname) > MAX_RONAME_LEN)
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("replication origin name is too long"),
+ errdetail("Replication origin names must be no longer than %d bytes.",
+    MAX_RONAME_LEN)));
+
+ roname_d = CStringGetTextDatum(originname);

CStringGetTextDatum is:
#define CStringGetTextDatum(s) PointerGetDatum(cstring_to_text(s))
---------

We are first converting text to C-string , then Cstring to text and
then getting Datum. Double allocation and double conversion. Can we
please try this instead and verify if it works:

text *origin_text = PG_GETARG_TEXT_PP(1);
originname = text_to_cstring(origin_text);
roname_d = PointerGetDatum(origin_text);

2)
+check_new_cluster_replication_origins(void)
+{
+ PGconn     *conn;
+ PGresult   *res;
+ int         norigins;
+
+ /* Quick return if there are no replication origins to migrate. */
+ if (old_cluster.nrepl_origins == 0)
+ return;

Don't we need a version check simialr to what we have introduced in
pg_dumpall for origins? (Similar to
check_new_cluster_replication_slots as well)

3)
Since we have introduced check_new_cluster_replication_origins, do we
even need below checks in binary_upgrade_create_replication_origin()?
In which conditions will they be hit?

+ /* Check for OID collision */
+    ....
+ if (collides)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin with ID %u already exists", node_oid)));
+
+ /* Check for name collision */
+   ....
+ if (collides)
+ ereport(ERROR,
+ (errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin \"%s\" already exists",
+ originname)));


4)
Now since check_new_cluster_subscription_configuration() is purely
about checking max-origin GUC configuration, I think the name is
misleading. IMO, we should merge it to
check_new_cluster_replication_origins(). See how
check_new_cluster_replication_slots() does it: checking both
new-cluster's count and the max-configuration for slots.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Mon, Jun 8, 2026 at 10:36 PM Shlok Kyal  wrote:
>
>
> Hi Ajin,
> I have reviewed the patch and here are some comments:
>
> 1. I want to clarify, what is the expected behaviour when we upgrade
> the postgres instance from version <= 16 to "HEAD + patch"?
> -   ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
> sizeof(originname));
> -   replorigin_create(originname);
> +   if (!IsBinaryUpgrade)
> +   {
> +       ReplicationOriginNameForLogicalRep(subid, InvalidOid,
> originname, sizeof(originname));
> +       replorigin_create(originname);
> +   }
> and
> +           /* Dump replication origins */
> +           if (server_version >= 170000 && binary_upgrade &&
> archDumpFormat == archNull)
> +               dumpReplicationOrigins(conn);
>
> When the postgres instance with subscription is updated from PG 16 (or
> less) to HEAD, the replication origin is created as we do not have "if
> (!IsBinaryUpgrade)" check in HEAD,
> whereas when the similar instance is upgraded to "HEAD + patch", no
> replication origin is present after the upgrade.
> Is this difference in the behaviour between HEAD and "HEAD + patch" expected?
>

Good catch Shlok. IMO, the behaviour should be same even if we upgrade
to HEAD+patch, it should not result in the loss of origins.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Mon, 8 Jun 2026 at 22:36, Shlok Kyal  wrote:
>
> On Thu, 28 May 2026 at 08:18, Ajin Cherian  wrote:
> >
> >
> >
> > On Fri, May 22, 2026 at 8:27 PM shveta malik  wrote:
> >>
> >> On Fri, May 22, 2026 at 3:16 PM Shlok Kyal  wrote:
> >> >
> >> > On Mon, 18 May 2026 at 16:13, Ajin Cherian  wrote:
> >> > >
> >> > > Rebased the patch as it was no longer applying.
> >> > >
> >> > Hi Ajin,
> >> >
> >> > I have started reviewing the patch. Here is my comment for v6-0002 patch:
> >> >
> >> > Suppose we have a replication setup: publisher -> subscriber
> >> > and we are upgrading subscriber to subscriber_new.
> >> > And if initially 'subscriber_new' has a replication origin, upgrading
> >> > the cluster can error out.
> >> >
> >> > Example:
> >> > We set up a logical replication between publisher node and subscriber node.
> >> >
> >> > On subscriber node:
> >> > postgres=# SELECT * FROM pg_replication_origin;
> >> >  roident |  roname
> >> > ---------+----------
> >> >        1 | pg_16393
> >> > (1 row)
> >> >
> >> > And initially subscriber_new has a replication origin:
> >> > postgres=# select pg_replication_origin_create('myname');
> >> >  pg_replication_origin_create
> >> > ------------------------------
> >> >                             1
> >> > (1 row)
> >> >
> >> > postgres=# SELECT * FROM pg_replication_origin;
> >> >  roident | roname
> >> > ---------+--------
> >> >        1 | myname
> >> > (1 row)
> >> >
> >> > Now, if we run pg_upgrade to upgrade subscriber node to subscriber_new
> >> > node, we get an error:
> >> > ```
> >> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> >> > 'pg_16393'::pg_catalog.name, '0/01743078'::pg_catalog.pg_lsn);
> >> > psql:subscriber_new/pg_upgrade_output.d/20260522T140312.807/dump/pg_upgrade_dump_globals.sql:37:
> >> > ERROR:  replication origin with ID 1 already exists
> >> > ```
> >> >
> >> > This error occurs in "Performing Upgrade" stage. Should we add a check
> >> > in the "Performing Consistency Checks" stage so that we don't need to
> >> > re-initdb the new cluster to perform the upgrade?
> >> > Maybe we can add a check similar to
> >> > check_new_cluster_replication_slots(), where pg_upgrade errors out if
> >> > the new cluster already contains replication origins. Thoughts?
> >>
> >> +1. I had the same thought while reviewing the patch today. We should
> >> have it unless there is a reason we have avoided it??
> >
> >
> > Fixed this. Added a new check for replication origins and if the new cluster has any existing replication origins, then the check will fail.
> >>
> >>
> >> Few trivial comments:
> >>
> >> 1)
> >>
> >> +#include "access/skey.h"
> >> +#include "catalog/indexing.h"
> >>
> >> pg_upgrade_support.c compiles without above.
> >>
> >
> > Removed.
> >
> >>
> >> 2)
> >> + Assert(!OidIsValid(rel->rd_rel->reltoastrelid));
> >>
> >> Is there a reason for this sanity check? I generally do not see a
> >> Null-Toast table sanity check after every table_open.
> >>
> >
> > Removed.
> >
> >>
> >> 3)
> >>
> >> +
> >> + /* Dump replication origins */
> >> + if (server_version >= 170000 && binary_upgrade && archDumpFormat == archNull)
> >> + dumpReplicationOrigins(conn);
> >>
> >> why the check is for PG17 specifically?
> >>
> >
> > In PG17, we started migrating pg_subscription_rel and the remote LSN during upgrades; prior to that, these were not migrated. Given that change, it also makes sense to migrate replication origins from them. Otherwise, when upgrading from PG17 to a later version, you could end up with a subscription where pg_subscription_rel and the remote LSN are migrated, but the corresponding replication origin is not created.
> >
> >
> >
> > On Mon, May 25, 2026 at 5:13 PM shveta malik  wrote:
> >>
> >>
> >> One issue in 002:
> >>
> >> binary_upgrade_create_replication_origin() has this:
> >>
> >> + originname = PG_GETARG_NAME(1);
> >> +
> >> + roname_d = CStringGetTextDatum(NameStr(*originname));
> >> +
> >>
> >> We are getting origin-name (text) into Name-type which can not be more
> >> than 64 bytes. So if an origin has name more than 64, it will end up
> >> trimming the name post-upgrade.
> >>
> >> I tried this:
> >>
> >> Old-setup:
> >> postgres=# SELECT
> >> pg_replication_origin_create('this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64');
> >>  pg_replication_origin_create
> >> ------------------------------
> >>                             1
> >> postgres=# select * from pg_replication_origin;
> >>  roident |                                roname
> >> ---------+----------------------------------------------------------------------
> >>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_limit_of_64
> >>
> >>
> >> Post-upgrade: name got trimmed to 64 length.
> >> -------------------------
> >> postgres=#  select * from pg_replication_origin;
> >>  roident |                             roname
> >> ---------+-----------------------------------------------------------------
> >>        1 | this_is_a_very_long_replication_origin_name_that_exceeds_the_li
> >>
> >> thanks
> >> Shveta
> >
> >
> > Fixed this. Now  binary_upgrade_create_replication_origin handles it similarly to the way pg_replication_origin_create handles the name of the origin.
> >
> > Here's an updated version v7 containing these fixes.
>
> Hi Ajin,
> I have reviewed the patch and here are some comments:
>
> 1. I want to clarify, what is the expected behaviour when we upgrade
> the postgres instance from version <= 16 to "HEAD + patch"?
> -   ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
> sizeof(originname));
> -   replorigin_create(originname);
> +   if (!IsBinaryUpgrade)
> +   {
> +       ReplicationOriginNameForLogicalRep(subid, InvalidOid,
> originname, sizeof(originname));
> +       replorigin_create(originname);
> +   }
> and
> +           /* Dump replication origins */
> +           if (server_version >= 170000 && binary_upgrade &&
> archDumpFormat == archNull)
> +               dumpReplicationOrigins(conn);
>
> When the postgres instance with subscription is updated from PG 16 (or
> less) to HEAD, the replication origin is created as we do not have "if
> (!IsBinaryUpgrade)" check in HEAD,
> whereas when the similar instance is upgraded to "HEAD + patch", no
> replication origin is present after the upgrade.
> Is this difference in the behaviour between HEAD and "HEAD + patch" expected?
>
> 2.a) Can we replace:
> +   /* Check for OID collision */
> +   ScanKeyInit(&key,
> +               Anum_pg_replication_origin_roident,
> +               BTEqualStrategyNumber, F_OIDEQ,
> +               ObjectIdGetDatum(node));
> +   scan = systable_beginscan(rel, ReplicationOriginIdentIndex,
> +                             true /* indexOK */,
> +                             SnapshotSelf,
> +                             1, &key);
> +   collides = HeapTupleIsValid(systable_getnext(scan));
> +   systable_endscan(scan);
> +
> +   if (collides)
> +       ereport(ERROR,
> +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> +                errmsg("replication origin with ID %u already
> exists", node_oid)));
>
> with:
> if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
>         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
>                        errmsg("replication origin with ID %u already
> exists", node_oid));
>
> 2.b) Similarly, Can we replace:
> +   /* Check for name collision */
> +   ScanKeyInit(&key,
> +               Anum_pg_replication_origin_roname,
> +               BTEqualStrategyNumber, F_TEXTEQ,
> +               roname_d);
> +   scan = systable_beginscan(rel, ReplicationOriginNameIndex,
> +                             true /* indexOK */,
> +                             SnapshotSelf,
> +                             1, &key);
> +   collides = HeapTupleIsValid(systable_getnext(scan));
> +   systable_endscan(scan);
> +
> +   if (collides)
> +       ereport(ERROR,
> +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> +                errmsg("replication origin \"%s\" already exists",
> +                       originname)));
> with:
>     if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
>         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
>                        errmsg("replication origin \"%s\" already
> exists", originname));
>
> This will make the code smaller and easy to read. Thoughts?
>
One more comment:

3. In logical-replication.sgml, we have documentation as:
"Commit timestamps and origin data are not preserved during the upgrade."
Now since the origin related data is preserved after the upgrade,
should we update the documentation here?

Thanks,
Shlok Kyal


RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Shveta,

> No, this difference is not expected.

Yes it must be fixed.

> 2)
> Another idea could be to have a
> 'binary_upgrade_skip_subs_origin_creation' variable. We populate it
> during dumpSubscription if 'source_version >= PG17' and
> 'IsBinaryUpgrade' is true. So this will be dumped
> 
> SELECT pg_catalog.binary_upgrade_set_skip_subs_origin_creation(true);
> CREATE SUBSCRIPTION ...
> SELECT pg_catalog.binary_upgrade_set_skip_subs_origin_creation(false);
> 
> First call will set 'binary_upgrade_skip_subs_origin_creation' which
> will be used by Create Subscription to decide to skip origin. This is
> similar to how dumpACl decides whether to record priveleges into
> 'pg_init_privs' for objectes created by extensions. See
> binary_upgrade_set_record_init_privs() which sets
> binary_upgrade_record_init_privs which is then used by
> recordExtensionInitPriv().

To clarify, I prefer the 2nd idea. According to 29d0a77, which migrates
replication slots from PG17+, it does not change the behavior when the source is
PG16-. We should follow the manner.

In case of third idea, origin id can be also preserved for PG16-, but the
version was out-of-scope of our patch [1]; in that version pg_subscription_rel
cannot be migrated, thus the logical replication cannot work in the first place.

Also, if we want to keep the existing behavior, we should allow upgrading the
below case.

Source: PG16, two subscriptions and origins exist (id = 1, 2).
Target: an origin exists (id = 1)

But we must reject upgrading if we preserves the origin-id, right?

[1]: https://www.postgresql.org/message-id/CAFPTHDYqpuZ6o2-HuCJDYqJ7GY3%2BzV%2BXo-gT7PAgi4Bkz%2BoTxw%40mail.gmail.com

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, Jun 11, 2026 at 12:22 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Shveta,
>
> > No, this difference is not expected.
>
> Yes it must be fixed.
>
> > 2)
> > Another idea could be to have a
> > 'binary_upgrade_skip_subs_origin_creation' variable. We populate it
> > during dumpSubscription if 'source_version >= PG17' and
> > 'IsBinaryUpgrade' is true. So this will be dumped
> >
> > SELECT pg_catalog.binary_upgrade_set_skip_subs_origin_creation(true);
> > CREATE SUBSCRIPTION ...
> > SELECT pg_catalog.binary_upgrade_set_skip_subs_origin_creation(false);
> >
> > First call will set 'binary_upgrade_skip_subs_origin_creation' which
> > will be used by Create Subscription to decide to skip origin. This is
> > similar to how dumpACl decides whether to record priveleges into
> > 'pg_init_privs' for objectes created by extensions. See
> > binary_upgrade_set_record_init_privs() which sets
> > binary_upgrade_record_init_privs which is then used by
> > recordExtensionInitPriv().
>
> To clarify, I prefer the 2nd idea. According to 29d0a77, which migrates
> replication slots from PG17+, it does not change the behavior when the source is
> PG16-. We should follow the manner.
>
> In case of third idea, origin id can be also preserved for PG16-, but the
> version was out-of-scope of our patch [1]; in that version pg_subscription_rel
> cannot be migrated, thus the logical replication cannot work in the first place.

I agree.

> Also, if we want to keep the existing behavior, we should allow upgrading the
> below case.
>
> Source: PG16, two subscriptions and origins exist (id = 1, 2).
> Target: an origin exists (id = 1)
>
> But we must reject upgrading if we preserves the origin-id, right?

Right. That is why I commented that if we choose option3, we will need
 to implement the check (check_new_cluster_replication_origins) even
on PG16 to reject the upgrade in the case you suggested.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Fri, Jun 5, 2026 at 8:10 PM vignesh C  wrote:
>
> Few comments:
> 1) pg_dumpall dumps all replication origins, not just subscription
> origins and recreates every origin:
> SELECT o.*, os.remote_lsn
> FROM pg_replication_origin o
> LEFT JOIN pg_replication_origin_status os
>   ON o.roident = os.local_id
>
> Is pg_upgrade expected to preserve user-created origins?
> If so, you can mention this in the commit message
>

I explicitly state that all replication origins are migrated in the
commit message, nothing specific about subscription origins.

> 2) Should the table lock be released here, if so should we mention
> comments similar to how it is mentioned in
> binary_upgarde_add_sub_rel_state:
> + /* Restore the remote_lsn if provided, while still holding the lock */
> + if (!PG_ARGISNULL(2))
> + {
> + XLogRecPtr remote_commit = PG_GETARG_LSN(2);
>
> - ReplicationSlotRelease();
> + replorigin_advance(node, remote_commit, InvalidXLogRecPtr,
> +    false /* backward */,
> +    false /* WAL log */);
> + }
> +
> + table_close(rel, RowExclusiveLock);
>

Is that relevant when creating a new row? or only when updating an existing one?

> 3) We can use new style of ereport to exclude '(' before errcode:
> 3.a)
> + ereport(ERROR,
> + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> + errmsg("replication origin name is too long"),
> + errdetail("Replication origin names must be no longer than %d bytes.",
> +    MAX_RONAME_LEN)));
>
> 3.b) Similarly here:
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin with ID %u already exists", node_oid)));
>
> 3.c) There are many others, you can search other ereport in the patch
> and change it too.
>

Done.

> 4) Since only one column will be returned here, can we use
> "PQgetvalue(res, 0, 0) and remove PQfnumber:
> + res = executeQueryOrDie(conn,
> + "SELECT count(*) AS nrepl_origins "
> + "FROM pg_catalog.pg_replication_origin");
> + i_nrepl_origins = PQfnumber(res, "nrepl_origins");
> + cluster->nrepl_origins = atoi(PQgetvalue(res, 0, i_nrepl_origins));
> + PQclear(res);
>

Done.

> 5) replorigin_create also has some duplicate code like below, will it
> be possible to have a common function so that both of them can use?
> /* Check for name collision */
> + ScanKeyInit(&key,
> + Anum_pg_replication_origin_roname,
> + BTEqualStrategyNumber, F_TEXTEQ,
> + roname_d);
> + scan = systable_beginscan(rel, ReplicationOriginNameIndex,
> +   true /* indexOK */,
> +   SnapshotSelf,
> +   1, &key);
> + collides = HeapTupleIsValid(systable_getnext(scan));
> + systable_endscan(scan);
> +
> + if (collides)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin \"%s\" already exists",
> + originname)));
> +
> + memset(&nulls, 0, sizeof(nulls));
> + memset(&values, 0, sizeof(values));
> +
> + values[Anum_pg_replication_origin_roident - 1] = ObjectIdGetDatum(node);
> + values[Anum_pg_replication_origin_roname - 1] = roname_d;
> +
> + tuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
> + CatalogTupleInsert(rel, tuple);
> + heap_freetuple(tuple);
> + CommandCounterIncrement();
>

I have created a new function replorigin_create_with_id() which has
some common code and called that from both replorigin_create() and
binary_upgrade_create_replication_origin()


On Tue, Jun 9, 2026 at 3:06 AM Shlok Kyal  wrote:
>
> Hi Ajin,
> I have reviewed the patch and here are some comments:
>
> 1. I want to clarify, what is the expected behaviour when we upgrade
> the postgres instance from version <= 16 to "HEAD + patch"?
> -   ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
> sizeof(originname));
> -   replorigin_create(originname);
> +   if (!IsBinaryUpgrade)
> +   {
> +       ReplicationOriginNameForLogicalRep(subid, InvalidOid,
> originname, sizeof(originname));
> +       replorigin_create(originname);
> +   }
> and
> +           /* Dump replication origins */
> +           if (server_version >= 170000 && binary_upgrade &&
> archDumpFormat == archNull)
> +               dumpReplicationOrigins(conn);
>
> When the postgres instance with subscription is updated from PG 16 (or
> less) to HEAD, the replication origin is created as we do not have "if
> (!IsBinaryUpgrade)" check in HEAD,
> whereas when the similar instance is upgraded to "HEAD + patch", no
> replication origin is present after the upgrade.
> Is this difference in the behaviour between HEAD and "HEAD + patch" expected?
>

I have modified this as option 3 suggested by Shveta and Amit and
removed the PG17 restriction for migrating replication origins, now it
does it for all versions that have replication origins.

> 2.a) Can we replace:
> +   /* Check for OID collision */
> +   ScanKeyInit(&key,
> +               Anum_pg_replication_origin_roident,
> +               BTEqualStrategyNumber, F_OIDEQ,
> +               ObjectIdGetDatum(node));
> +   scan = systable_beginscan(rel, ReplicationOriginIdentIndex,
> +                             true /* indexOK */,
> +                             SnapshotSelf,
> +                             1, &key);
> +   collides = HeapTupleIsValid(systable_getnext(scan));
> +   systable_endscan(scan);
> +
> +   if (collides)
> +       ereport(ERROR,
> +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> +                errmsg("replication origin with ID %u already
> exists", node_oid)));
>
> with:
> if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
>         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
>                        errmsg("replication origin with ID %u already
> exists", node_oid));
>
> 2.b) Similarly, Can we replace:
> +   /* Check for name collision */
> +   ScanKeyInit(&key,
> +               Anum_pg_replication_origin_roname,
> +               BTEqualStrategyNumber, F_TEXTEQ,
> +               roname_d);
> +   scan = systable_beginscan(rel, ReplicationOriginNameIndex,
> +                             true /* indexOK */,
> +                             SnapshotSelf,
> +                             1, &key);
> +   collides = HeapTupleIsValid(systable_getnext(scan));
> +   systable_endscan(scan);
> +
> +   if (collides)
> +       ereport(ERROR,
> +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> +                errmsg("replication origin \"%s\" already exists",
> +                       originname)));
> with:
>     if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
>         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
>                        errmsg("replication origin \"%s\" already
> exists", originname));
>
> This will make the code smaller and easy to read. Thoughts?

Done


On Tue, Jun 9, 2026 at 2:13 PM shveta malik  wrote:
>
>
> Please find a few comments on v007:
>
> 1)
>
> + node = (ReplOriginId) node_oid;
> + originname = text_to_cstring(PG_GETARG_TEXT_PP(1));
> +
> + if (strlen(originname) > MAX_RONAME_LEN)
> + ereport(ERROR,
> + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> + errmsg("replication origin name is too long"),
> + errdetail("Replication origin names must be no longer than %d bytes.",
> +    MAX_RONAME_LEN)));
> +
> + roname_d = CStringGetTextDatum(originname);
>
> CStringGetTextDatum is:
> #define CStringGetTextDatum(s) PointerGetDatum(cstring_to_text(s))
> ---------
>
> We are first converting text to C-string , then Cstring to text and
> then getting Datum. Double allocation and double conversion. Can we
> please try this instead and verify if it works:
>
> text *origin_text = PG_GETARG_TEXT_PP(1);
> originname = text_to_cstring(origin_text);
> roname_d = PointerGetDatum(origin_text);
>

I've restructured the code now, its a bit tough to do this now.

> 2)
> +check_new_cluster_replication_origins(void)
> +{
> + PGconn     *conn;
> + PGresult   *res;
> + int         norigins;
> +
> + /* Quick return if there are no replication origins to migrate. */
> + if (old_cluster.nrepl_origins == 0)
> + return;
>
> Don't we need a version check simialr to what we have introduced in
> pg_dumpall for origins? (Similar to
> check_new_cluster_replication_slots as well)
>

I've removed the version check for PG17 now.

> 3)
> Since we have introduced check_new_cluster_replication_origins, do we
> even need below checks in binary_upgrade_create_replication_origin()?
> In which conditions will they be hit?
>
> + /* Check for OID collision */
> +    ....
> + if (collides)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin with ID %u already exists", node_oid)));
> +
> + /* Check for name collision */
> +   ....
> + if (collides)
> + ereport(ERROR,
> + (errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin \"%s\" already exists",
> + originname)));
>

With the restructured code, its not easy to do this now.

>
> 4)
> Now since check_new_cluster_subscription_configuration() is purely
> about checking max-origin GUC configuration, I think the name is
> misleading. IMO, we should merge it to
> check_new_cluster_replication_origins(). See how
> check_new_cluster_replication_slots() does it: checking both
> new-cluster's count and the max-configuration for slots.
>

Done.


On Tue, Jun 9, 2026 at 9:32 PM Shlok Kyal  wrote:
>
> >
> One more comment:
>
> 3. In logical-replication.sgml, we have documentation as:
> "Commit timestamps and origin data are not preserved during the upgrade."
> Now since the origin related data is preserved after the upgrade,
> should we update the documentation here?
>

Updated.

I have addressed the comments in v8 (attached). I've also now taken
out the check for PG17 on old cluster and now all clusters which have
replication origins are migrated.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Wed, Jun 17, 2026 at 2:49 PM Ajin Cherian  wrote:
>
> I have addressed the comments in v8 (attached). I've also now taken
> out the check for PG17 on old cluster and now all clusters which have
> replication origins are migrated.

Hi Ajin, Thanks for the patches.
I have started reviewing the patches. Please find a few initial
comments below (from v7 review, still applicable to v8):

1) Patch-002: pg_dump.c
+ if (dopt->binary_upgrade && subinfo->subenabled &&
fout->remoteVersion >= 170000)
  {
- if (subinfo->suboriginremotelsn)
- {
- /*
- * Preserve the remote_lsn for the subscriber's replication

I could not find any usage of subinfo[i].suboriginremotelsn anymore.
It seems to be dead code now. Can we remove it?
~~~

2) Patch-002 : binary_upgrade_create_replication_origin()
- PG_RETURN_VOID();
+ node_oid = PG_GETARG_OID(0);
+
+ if (node_oid == InvalidOid || node_oid > PG_UINT16_MAX)
+ ereport(ERROR,
+ errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("replication origin ID %u is out of range", node_oid));
+

The above range check allows PG_UINT16_MAX, but that value is not part
of the valid replication origin ID range.

In origin.h:
  #define DoNotReplicateId PG_UINT16_MAX

And we already ensure "ReplOriginId != DoNotReplicateId" everywhere
else. Would something like the below be more appropriate?
  if (node_oid == InvalidReplOriginId || node_oid >= DoNotReplicateId)
    ereport(ERROR, ...
~~~

3) I think we should add some additional details in
logical-replication.sgml, especially under Prepare for
Subscriber Upgrades.
Some suggestions:
3a) Since all replication origins are now migrated, this:
  "...greater than or equal to the number of subscriptions present in
the old cluster."
could become:
  "...greater than or equal to the number of replication origins
present in the old cluster."

3b) We should also mention:
  The new cluster must contain no replication origins.

--
Thanks,
Nisha


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jun 17, 2026 at 5:12 PM Nisha Moond  wrote:
>
> On Wed, Jun 17, 2026 at 4:29 PM Nisha Moond  wrote:
> >
> > On Wed, Jun 17, 2026 at 2:49 PM Ajin Cherian  wrote:
> > >
> > > I have addressed the comments in v8 (attached). I've also now taken
> > > out the check for PG17 on old cluster and now all clusters which have
> > > replication origins are migrated.
> >
> > Hi Ajin, Thanks for the patches.
> > I have started reviewing the patches. Please find a few initial
> > comments below (from v7 review, still applicable to v8):
>
> Please find a couple more comments for the v8-002 patch:
>
> 4) I was able to build successfully without all three new header
> inclusions below, so we may not need them.
> --- a/src/backend/utils/adt/pg_upgrade_support.c
> +++ b/src/backend/utils/adt/pg_upgrade_support.c
> @@ -11,6 +11,7 @@
> +#include "access/genam.h"
> ...
> +#include "utils/fmgroids.h"
> ...
> +#include "utils/snapmgr.h"
> ~~~
>
> 5) Race condition in origin.c: replorigin_create()
> - heap_freetuple(tuple);
> + table_close(rel, ExclusiveLock);
> +
> + replorigin_create_with_id(roident, roname, InvalidXLogRecPtr);
> +
>
> Due to the above refactoring, CREATE SUBSCRIPTION can now fail because
> of a race between two concurrent CREATE SUBSCRIPTION commands:
>
> postgres=# create subscription sub2 connection 'dbname=postgres
> host=localhost port=7733' publication pub1;
> ERROR:  replication origin with ID 2 already exists
>
> I think this happens because the table lock is released, allowing
> another session to create a pg_origin with the next available roident,
> which replorigin_create_with_id() later attempts to use.
>
> Would it make sense to call replorigin_create_with_id() before
> table_close() so the lock is still held? I tested this and it works,
> though I'm not fully sure whether self-locking could be a concern
> here, since replorigin_create_with_id() again acquires a
> RowExclusiveLock on the same table.

We can handle this race-condition by moving the table-open to callers
rather than internal call replorigin_create_with_id().  But we also
need the following changes first:

1)
replorigin_create_with_id has:

+ /*
+ * To avoid needing a TOAST table for pg_replication_origin, we limit
+ * replication origin names to 512 bytes.  This should be more than enough
+ * for all practical use.
+ */
+ if (strlen(roname) > MAX_RONAME_LEN)
+ ereport(ERROR,
+ errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("replication origin name is too long"),
+ errdetail("Replication origin names must be no longer than %d bytes.",
+   MAX_RONAME_LEN));

replorigin_create_with_id() is called by replorigin_create() and
binary_upgrade_create_replication_origin().   replorigin_create()
already has this check. We should move above check to
binary_upgrade_create_replication_origin() and get rid of it from
internal function replorigin_create_with_id().

2)

Also the checks:
+ if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(roident)))
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin with ID %u already exists",
+    (Oid) roident));
+
+ if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin \"%s\" already exists", roname));

should be moved to caller binary_upgrade_create_replication_origin().
IMO, these checks are not needed for replorigin_create(), it alread
has this, which should suffice.

                ereport(ERROR,
                                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                                 errmsg("could not find free
replication origin ID")));

~~

Once we correctly place these checks, we can move the 'table_open with
lock' to caller (before name and id collision checks) instead of
replorigin_create_with_id(), which will take care of race-conditions
reported by Nisha.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Jun 16, 2026 at 2:50 PM Ajin Cherian  wrote:
>
>
>
> On Mon, Jun 15, 2026 at 9:31 PM Amit Kapila  wrote:
>>
>>
>>
>> I'd prefer option-3 (preserve origin IDs uniformly, including upgrades
>> from PG16), for two reasons. (a) First, the new-cluster check ("reject
>> if the new cluster already has replication origins") is a restriction
>> on the target, and adding restrictions on a newer target version
>> regardless of source version is well within how pg_upgrade already
>> behaves. In practice the new cluster is a fresh initdb with no
>> origins, so the check effectively never fires; the only scenario it
>> rejects is one where the user manually created subscriptions/origins
>> on the new cluster before upgrading, which we discourage for other
>> object types anyway. So I don't think preserving existing behavior
>> here is worth much. (b) Second, option-2 reintroduces source-version
>> branching at dump time (the skip_subs_origin_creation flag gated on
>> source >= 17). Since pg_commit_ts is only copied from PG19+, the exact
>> roident value only matters from PG19; for PG16-18 the value is
>> don't-care, so preserving it everywhere is harmless where it isn't
>> needed and required where it is. That lets us keep a single
>> always-preserve path instead of branching per source version.
>>
>
> Ok.
>
>>
>> Separately, I don't think we actually need to preserve the
>> subscription OID to meet the goal here. pg_commit_ts stores the
>> numeric roident, not the origin name or the sub OID, and conflict
>> detection compares roidents. So the invariant we must keep is "each
>> subscription owns the same roident after upgrade", which doesn't
>> depend on the name being stable.
>>
>>
>
> Replication origins are global objects and are therefore dumped by pg_dumpall, while subscriptions are database-specific and are dumped by pg_dump. In pg_upgrade, pg_dumpall runs before pg_dump.
>
> The complication if subscription OID is not preserved is that subscription-associated origins derive their name from the subscription's OID. If the subscription OID is not preserved across upgrades, the origin name on the new cluster will differ from the old one, making it impossible to restore the origin independently. For these origins, creation must happen after CreateSubscription has established the new OID and not upfront in pg_dumpall.
>
> Non-subscription origins have no such dependency and continue to be created separately as before. The subscription code also cannot be left untouched: even once the subscription is created, rather than origin being created inside CreateSubscription, its associated origin must still be explicitly created via binary_upgrade_create_replication_origin to ensure the roident matches the original node, which means CreateSubscription needs to be modified anyways. So, there is an advantage of reducing code if subscription OID is preserved and all origins keep the same name as the old node.
>

IIUC, the conclusion (and what's implemented in v8) is:

1) The origin-ids are preserved on upgraded version irrespective of
source version.
2) Since origin-ids preservation requires sub-oid preservation due to
the origin-name's dependency on the sub-oid, we preserve sub-oid too
irrespective of source-version.

Let's see what Amit has to say about this.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Wed, 17 Jun 2026 at 14:49, Ajin Cherian  wrote:
>
> On Fri, Jun 5, 2026 at 8:10 PM vignesh C  wrote:
> >
> > Few comments:
> > 1) pg_dumpall dumps all replication origins, not just subscription
> > origins and recreates every origin:
> > SELECT o.*, os.remote_lsn
> > FROM pg_replication_origin o
> > LEFT JOIN pg_replication_origin_status os
> >   ON o.roident = os.local_id
> >
> > Is pg_upgrade expected to preserve user-created origins?
> > If so, you can mention this in the commit message
> >
>
> I explicitly state that all replication origins are migrated in the
> commit message, nothing specific about subscription origins.
>
> > 2) Should the table lock be released here, if so should we mention
> > comments similar to how it is mentioned in
> > binary_upgarde_add_sub_rel_state:
> > + /* Restore the remote_lsn if provided, while still holding the lock */
> > + if (!PG_ARGISNULL(2))
> > + {
> > + XLogRecPtr remote_commit = PG_GETARG_LSN(2);
> >
> > - ReplicationSlotRelease();
> > + replorigin_advance(node, remote_commit, InvalidXLogRecPtr,
> > +    false /* backward */,
> > +    false /* WAL log */);
> > + }
> > +
> > + table_close(rel, RowExclusiveLock);
> >
>
> Is that relevant when creating a new row? or only when updating an existing one?
>
> > 3) We can use new style of ereport to exclude '(' before errcode:
> > 3.a)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> > + errmsg("replication origin name is too long"),
> > + errdetail("Replication origin names must be no longer than %d bytes.",
> > +    MAX_RONAME_LEN)));
> >
> > 3.b) Similarly here:
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin with ID %u already exists", node_oid)));
> >
> > 3.c) There are many others, you can search other ereport in the patch
> > and change it too.
> >
>
> Done.
>
> > 4) Since only one column will be returned here, can we use
> > "PQgetvalue(res, 0, 0) and remove PQfnumber:
> > + res = executeQueryOrDie(conn,
> > + "SELECT count(*) AS nrepl_origins "
> > + "FROM pg_catalog.pg_replication_origin");
> > + i_nrepl_origins = PQfnumber(res, "nrepl_origins");
> > + cluster->nrepl_origins = atoi(PQgetvalue(res, 0, i_nrepl_origins));
> > + PQclear(res);
> >
>
> Done.
>
> > 5) replorigin_create also has some duplicate code like below, will it
> > be possible to have a common function so that both of them can use?
> > /* Check for name collision */
> > + ScanKeyInit(&key,
> > + Anum_pg_replication_origin_roname,
> > + BTEqualStrategyNumber, F_TEXTEQ,
> > + roname_d);
> > + scan = systable_beginscan(rel, ReplicationOriginNameIndex,
> > +   true /* indexOK */,
> > +   SnapshotSelf,
> > +   1, &key);
> > + collides = HeapTupleIsValid(systable_getnext(scan));
> > + systable_endscan(scan);
> > +
> > + if (collides)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin \"%s\" already exists",
> > + originname)));
> > +
> > + memset(&nulls, 0, sizeof(nulls));
> > + memset(&values, 0, sizeof(values));
> > +
> > + values[Anum_pg_replication_origin_roident - 1] = ObjectIdGetDatum(node);
> > + values[Anum_pg_replication_origin_roname - 1] = roname_d;
> > +
> > + tuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
> > + CatalogTupleInsert(rel, tuple);
> > + heap_freetuple(tuple);
> > + CommandCounterIncrement();
> >
>
> I have created a new function replorigin_create_with_id() which has
> some common code and called that from both replorigin_create() and
> binary_upgrade_create_replication_origin()
>
>
> On Tue, Jun 9, 2026 at 3:06 AM Shlok Kyal  wrote:
> >
> > Hi Ajin,
> > I have reviewed the patch and here are some comments:
> >
> > 1. I want to clarify, what is the expected behaviour when we upgrade
> > the postgres instance from version <= 16 to "HEAD + patch"?
> > -   ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
> > sizeof(originname));
> > -   replorigin_create(originname);
> > +   if (!IsBinaryUpgrade)
> > +   {
> > +       ReplicationOriginNameForLogicalRep(subid, InvalidOid,
> > originname, sizeof(originname));
> > +       replorigin_create(originname);
> > +   }
> > and
> > +           /* Dump replication origins */
> > +           if (server_version >= 170000 && binary_upgrade &&
> > archDumpFormat == archNull)
> > +               dumpReplicationOrigins(conn);
> >
> > When the postgres instance with subscription is updated from PG 16 (or
> > less) to HEAD, the replication origin is created as we do not have "if
> > (!IsBinaryUpgrade)" check in HEAD,
> > whereas when the similar instance is upgraded to "HEAD + patch", no
> > replication origin is present after the upgrade.
> > Is this difference in the behaviour between HEAD and "HEAD + patch" expected?
> >
>
> I have modified this as option 3 suggested by Shveta and Amit and
> removed the PG17 restriction for migrating replication origins, now it
> does it for all versions that have replication origins.
>
> > 2.a) Can we replace:
> > +   /* Check for OID collision */
> > +   ScanKeyInit(&key,
> > +               Anum_pg_replication_origin_roident,
> > +               BTEqualStrategyNumber, F_OIDEQ,
> > +               ObjectIdGetDatum(node));
> > +   scan = systable_beginscan(rel, ReplicationOriginIdentIndex,
> > +                             true /* indexOK */,
> > +                             SnapshotSelf,
> > +                             1, &key);
> > +   collides = HeapTupleIsValid(systable_getnext(scan));
> > +   systable_endscan(scan);
> > +
> > +   if (collides)
> > +       ereport(ERROR,
> > +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> > +                errmsg("replication origin with ID %u already
> > exists", node_oid)));
> >
> > with:
> > if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
> >         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
> >                        errmsg("replication origin with ID %u already
> > exists", node_oid));
> >
> > 2.b) Similarly, Can we replace:
> > +   /* Check for name collision */
> > +   ScanKeyInit(&key,
> > +               Anum_pg_replication_origin_roname,
> > +               BTEqualStrategyNumber, F_TEXTEQ,
> > +               roname_d);
> > +   scan = systable_beginscan(rel, ReplicationOriginNameIndex,
> > +                             true /* indexOK */,
> > +                             SnapshotSelf,
> > +                             1, &key);
> > +   collides = HeapTupleIsValid(systable_getnext(scan));
> > +   systable_endscan(scan);
> > +
> > +   if (collides)
> > +       ereport(ERROR,
> > +               (errcode(ERRCODE_DUPLICATE_OBJECT),
> > +                errmsg("replication origin \"%s\" already exists",
> > +                       originname)));
> > with:
> >     if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> >         ereport(ERROR, errcode(ERRCODE_DUPLICATE_OBJECT),
> >                        errmsg("replication origin \"%s\" already
> > exists", originname));
> >
> > This will make the code smaller and easy to read. Thoughts?
>
> Done
>
>
> On Tue, Jun 9, 2026 at 2:13 PM shveta malik  wrote:
> >
> >
> > Please find a few comments on v007:
> >
> > 1)
> >
> > + node = (ReplOriginId) node_oid;
> > + originname = text_to_cstring(PG_GETARG_TEXT_PP(1));
> > +
> > + if (strlen(originname) > MAX_RONAME_LEN)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> > + errmsg("replication origin name is too long"),
> > + errdetail("Replication origin names must be no longer than %d bytes.",
> > +    MAX_RONAME_LEN)));
> > +
> > + roname_d = CStringGetTextDatum(originname);
> >
> > CStringGetTextDatum is:
> > #define CStringGetTextDatum(s) PointerGetDatum(cstring_to_text(s))
> > ---------
> >
> > We are first converting text to C-string , then Cstring to text and
> > then getting Datum. Double allocation and double conversion. Can we
> > please try this instead and verify if it works:
> >
> > text *origin_text = PG_GETARG_TEXT_PP(1);
> > originname = text_to_cstring(origin_text);
> > roname_d = PointerGetDatum(origin_text);
> >
>
> I've restructured the code now, its a bit tough to do this now.
>
> > 2)
> > +check_new_cluster_replication_origins(void)
> > +{
> > + PGconn     *conn;
> > + PGresult   *res;
> > + int         norigins;
> > +
> > + /* Quick return if there are no replication origins to migrate. */
> > + if (old_cluster.nrepl_origins == 0)
> > + return;
> >
> > Don't we need a version check simialr to what we have introduced in
> > pg_dumpall for origins? (Similar to
> > check_new_cluster_replication_slots as well)
> >
>
> I've removed the version check for PG17 now.
>
> > 3)
> > Since we have introduced check_new_cluster_replication_origins, do we
> > even need below checks in binary_upgrade_create_replication_origin()?
> > In which conditions will they be hit?
> >
> > + /* Check for OID collision */
> > +    ....
> > + if (collides)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin with ID %u already exists", node_oid)));
> > +
> > + /* Check for name collision */
> > +   ....
> > + if (collides)
> > + ereport(ERROR,
> > + (errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin \"%s\" already exists",
> > + originname)));
> >
>
> With the restructured code, its not easy to do this now.
>
> >
> > 4)
> > Now since check_new_cluster_subscription_configuration() is purely
> > about checking max-origin GUC configuration, I think the name is
> > misleading. IMO, we should merge it to
> > check_new_cluster_replication_origins(). See how
> > check_new_cluster_replication_slots() does it: checking both
> > new-cluster's count and the max-configuration for slots.
> >
>
> Done.
>
>
> On Tue, Jun 9, 2026 at 9:32 PM Shlok Kyal  wrote:
> >
> > >
> > One more comment:
> >
> > 3. In logical-replication.sgml, we have documentation as:
> > "Commit timestamps and origin data are not preserved during the upgrade."
> > Now since the origin related data is preserved after the upgrade,
> > should we update the documentation here?
> >
>
> Updated.
>
> I have addressed the comments in v8 (attached). I've also now taken
> out the check for PG17 on old cluster and now all clusters which have
> replication origins are migrated.

Hi Ajin,

Thanks for providing the updated patch, I reviewed the patch and I
have some comments:

1. patch is not applying on HEAD and needs a rebase.

2. New line after 'check_new_cluster_replication_origins' is not required:
+ check_new_cluster_replication_origins();
+

3. pg_dumpall with option '--roles-only' also dumps replication origins
eg:
./pg_dumpall -p 9000 --binary-upgrade --roles-only > op.sql
output contains:
-- For binary upgrade, must preserve replication origin roident and remote_lsn
SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);

I think in this case we should not dump the replication origins as we
explicitly gave the option of '--roles-only'

4. pg_dumpall with --globals-only option also dumps replication origins.
eg:
./pg_dumpall -p 9000 --binary-upgrade --globals-only> op.sql and
output contains:
-- For binary upgrade, must preserve replication origin roident and remote_lsn
SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);

Is this behaviour intentional? Other logical replication objects
(e.g., publications and subscriptions) are not included in pg_dumpall
--globals-only, so is it okay to dump replication origin?

Thanks,
Shlok Kyal


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Hi Ajin,

Thanks for v8. A couple of comments:

1) The PG17 gating seems inconsistent between the dump and the check now.
dumpReplicationOrigins() is called unconditionally:

    if (binary_upgrade && archDumpFormat == archNull)
        dumpReplicationOrigins(conn);

but get_subscription_info(), which sets nrepl_origins, is still only
called for old clusters >= 17 in check_new_cluster():

    if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1700)
        ...
        get_subscription_info(&old_cluster);

and check_new_cluster_replication_origins() returns early on it:

    if (old_cluster.nrepl_origins == 0)
        return;

For a < 17 old cluster get_subscription_info() is never called, so
nrepl_origins stays 0 and this returns early. So when such a cluster has a
(user-created) origin, the origin still gets dumped and recreated, while
the "new cluster must have no origins" and max_active_replication_origins
checks are skipped, and the upgrade fails during restore instead of at the
check step. nrepl_origins is just a count(*) on pg_replication_origin, so
moving its collection out of the >= 1700 block should be enough.

2) 004_subscription.pl only checks subscription origins (pg_<oid>). Since
the patch migrates all origins, should we also create a user origin
(pg_replication_origin_create()) and verify its roident/remote_lsn after
the upgrade? That would also cover the case in (1).

Thanks,
Rui

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Wed, Jun 17, 2026 at 8:59 PM Nisha Moond  wrote:
>
> Hi Ajin, Thanks for the patches.
> I have started reviewing the patches. Please find a few initial
> comments below (from v7 review, still applicable to v8):
>
> 1) Patch-002: pg_dump.c
> + if (dopt->binary_upgrade && subinfo->subenabled &&
> fout->remoteVersion >= 170000)
>   {
> - if (subinfo->suboriginremotelsn)
> - {
> - /*
> - * Preserve the remote_lsn for the subscriber's replication
>
> I could not find any usage of subinfo[i].suboriginremotelsn anymore.
> It seems to be dead code now. Can we remove it?

Removed it.


> ~~~
>
> 2) Patch-002 : binary_upgrade_create_replication_origin()
> - PG_RETURN_VOID();
> + node_oid = PG_GETARG_OID(0);
> +
> + if (node_oid == InvalidOid || node_oid > PG_UINT16_MAX)
> + ereport(ERROR,
> + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> + errmsg("replication origin ID %u is out of range", node_oid));
> +
>
> The above range check allows PG_UINT16_MAX, but that value is not part
> of the valid replication origin ID range.
>
> In origin.h:
>   #define DoNotReplicateId PG_UINT16_MAX
>
> And we already ensure "ReplOriginId != DoNotReplicateId" everywhere
> else. Would something like the below be more appropriate?
>   if (node_oid == InvalidReplOriginId || node_oid >= DoNotReplicateId)
>     ereport(ERROR, ...
> ~~~

Done.


>
> 3) I think we should add some additional details in
> logical-replication.sgml, especially under Prepare for
> Subscriber Upgrades.
> Some suggestions:
> 3a) Since all replication origins are now migrated, this:
>   "...greater than or equal to the number of subscriptions present in
> the old cluster."
> could become:
>   "...greater than or equal to the number of replication origins
> present in the old cluster."
>
> 3b) We should also mention:
>   The new cluster must contain no replication origins.
>

Done.



On Wed, Jun 17, 2026 at 9:42 PM Nisha Moond  wrote:
>
> 4) I was able to build successfully without all three new header
> inclusions below, so we may not need them.
> --- a/src/backend/utils/adt/pg_upgrade_support.c
> +++ b/src/backend/utils/adt/pg_upgrade_support.c
> @@ -11,6 +11,7 @@
> +#include "access/genam.h"
> ...
> +#include "utils/fmgroids.h"
> ...
> +#include "utils/snapmgr.h"
> ~~~
>

Removed.


> 5) Race condition in origin.c: replorigin_create()
> - heap_freetuple(tuple);
> + table_close(rel, ExclusiveLock);
> +
> + replorigin_create_with_id(roident, roname, InvalidXLogRecPtr);
> +
>
> Due to the above refactoring, CREATE SUBSCRIPTION can now fail because
> of a race between two concurrent CREATE SUBSCRIPTION commands:
>
> postgres=# create subscription sub2 connection 'dbname=postgres
> host=localhost port=7733' publication pub1;
> ERROR:  replication origin with ID 2 already exists
>
> I think this happens because the table lock is released, allowing
> another session to create a pg_origin with the next available roident,
> which replorigin_create_with_id() later attempts to use.
>
> Would it make sense to call replorigin_create_with_id() before
> table_close() so the lock is still held? I tested this and it works,
> though I'm not fully sure whether self-locking could be a concern
> here, since replorigin_create_with_id() again acquires a
> RowExclusiveLock on the same table.
> ~~~
>

I have fixed this as suggested by Shveta

~~~~~~~~~~



On Thu, Jun 18, 2026 at 7:17 PM shveta malik  wrote:
>
> > I think this happens because the table lock is released, allowing
> > another session to create a pg_origin with the next available roident,
> > which replorigin_create_with_id() later attempts to use.
> >
> > Would it make sense to call replorigin_create_with_id() before
> > table_close() so the lock is still held? I tested this and it works,
> > though I'm not fully sure whether self-locking could be a concern
> > here, since replorigin_create_with_id() again acquires a
> > RowExclusiveLock on the same table.
>
> We can handle this race-condition by moving the table-open to callers
> rather than internal call replorigin_create_with_id().  But we also
> need the following changes first:
>

Yes, did it that way.


> 1)
> replorigin_create_with_id has:
>
> + /*
> + * To avoid needing a TOAST table for pg_replication_origin, we limit
> + * replication origin names to 512 bytes.  This should be more than enough
> + * for all practical use.
> + */
> + if (strlen(roname) > MAX_RONAME_LEN)
> + ereport(ERROR,
> + errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> + errmsg("replication origin name is too long"),
> + errdetail("Replication origin names must be no longer than %d bytes.",
> +   MAX_RONAME_LEN));
>
> replorigin_create_with_id() is called by replorigin_create() and
> binary_upgrade_create_replication_origin().   replorigin_create()
> already has this check. We should move above check to
> binary_upgrade_create_replication_origin() and get rid of it from
> internal function replorigin_create_with_id().

Moved.

>
> 2)
>
> Also the checks:
> + if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(roident)))
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin with ID %u already exists",
> +    (Oid) roident));
> +
> + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin \"%s\" already exists", roname));
>
> should be moved to caller binary_upgrade_create_replication_origin().
> IMO, these checks are not needed for replorigin_create(), it alread
> has this, which should suffice.
>
>                 ereport(ERROR,
>                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
>                                  errmsg("could not find free
> replication origin ID")));
>
> ~~
>
> Once we correctly place these checks, we can move the 'table_open with
> lock' to caller (before name and id collision checks) instead of
> replorigin_create_with_id(), which will take care of race-conditions
> reported by Nisha.
>

I have moved the roident check out of replorigin_create_with_id(), but
kept the roname check there as that is not there in
replorigin_create()

On Fri, Jun 19, 2026 at 5:48 PM Shlok Kyal  wrote:
> Hi Ajin,
>
> Thanks for providing the updated patch, I reviewed the patch and I
> have some comments:
>
> 1. patch is not applying on HEAD and needs a rebase.
>
> 2. New line after 'check_new_cluster_replication_origins' is not required:
> + check_new_cluster_replication_origins();
> +
>
> 3. pg_dumpall with option '--roles-only' also dumps replication origins
> eg:
> ./pg_dumpall -p 9000 --binary-upgrade --roles-only > op.sql
> output contains:
> -- For binary upgrade, must preserve replication origin roident and remote_lsn
> SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
>
> I think in this case we should not dump the replication origins as we
> explicitly gave the option of '--roles-only'
>

I have moved the dump_replication_origins under !roles_only and
!tablespaces_only checks, I think "globals only" is valid for
replication origins.


> 4. pg_dumpall with --globals-only option also dumps replication origins.
> eg:
> ./pg_dumpall -p 9000 --binary-upgrade --globals-only> op.sql and
> output contains:
> -- For binary upgrade, must preserve replication origin roident and remote_lsn
> SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
>
> Is this behaviour intentional? Other logical replication objects
> (e.g., publications and subscriptions) are not included in pg_dumpall
> --globals-only, so is it okay to dump replication origin?
>

This is expected as publications and subscriptions are database
specific and not globals, while replication origins are global.



On Mon, Jun 22, 2026 at 2:22 AM Rui Zhao  wrote:
>>
>> Hi Ajin,
>>
>> Thanks for v8. A couple of comments:
>>
>> 1) The PG17 gating seems inconsistent between the dump and the check now.
>> dumpReplicationOrigins() is called unconditionally:
>>
>>     if (binary_upgrade && archDumpFormat == archNull)
>>         dumpReplicationOrigins(conn);
>>
>> but get_subscription_info(), which sets nrepl_origins, is still only
>> called for old clusters >= 17 in check_new_cluster():
>>
>>     if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1700)
>>         ...
>>         get_subscription_info(&old_cluster);
>>
>> and check_new_cluster_replication_origins() returns early on it:
>>
>>     if (old_cluster.nrepl_origins == 0)
>>         return;
>>
>> For a < 17 old cluster get_subscription_info() is never called, so
>> nrepl_origins stays 0 and this returns early. So when such a cluster has a
>> (user-created) origin, the origin still gets dumped and recreated, while
>> the "new cluster must have no origins" and max_active_replication_origins
>> checks are skipped, and the upgrade fails during restore instead of at the
>> check step. nrepl_origins is just a count(*) on pg_replication_origin, so
>> moving its collection out of the >= 1700 block should be enough.
>>

Yes, good catch. I have separated out the replication origin speciifc
checks into a different function and moved it oustide the >= 1700
block

>> 2) 004_subscription.pl only checks subscription origins (pg_). Since
>> the patch migrates all origins, should we also create a user origin
>> (pg_replication_origin_create()) and verify its roident/remote_lsn after
>> the upgrade? That would also cover the case in (1).


Added.

All the above changes have been addressed in patch v9.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Hi Ajin,

Thanks for v9, and for addressing both my earlier comments. I also went
through the rest of v9 -- the other reviewers' comments and the
corresponding fixes (including the replorigin_create() locking rework) look
good to me; I didn't find any issues there.

A follow-up on the version gating, though: I think it now moved a bit too
far. get_replication_origin_info() is called unconditionally (outside the
>= 1700 block):

    /* Get replication origin information */
    get_replication_origin_info(&old_cluster);

and it runs "SELECT count(*) FROM pg_catalog.pg_replication_origin".
pg_dumpall's dumpReplicationOrigins() queries the same catalog with no
version guard either. But pg_replication_origin only exists from 9.5
(commit 5aa2350426), while pg_upgrade still accepts old clusters back to
9.2:

    if (GET_MAJOR_VERSION(old_cluster.major_version) < 902)
        pg_fatal("This utility can only upgrade from PostgreSQL version %s
                 and later.", "9.2");

So upgrading from 9.2/9.3/9.4 now fails: the query hits a non-existent
catalog and pg_fatal()s (and dumpReplicationOrigins would too).
It should be gated on the version where origins were introduced, e.g.

    if (GET_MAJOR_VERSION(old_cluster.major_version) >= 905)
        get_replication_origin_info(&old_cluster);

with the matching server_version >= 90500 check on the pg_dumpall side.
That keeps the < 17 case I flagged working while not breaking 9.2-9.4
(which have no origins to migrate anyway).

One nit while here: there is an extra blank line after the
check_new_cluster_replication_origins() call in check_new_cluster().

Thanks,
Rui

Ajin Cherian  于2026年6月23日周二 19:50写道:
>
> On Wed, Jun 17, 2026 at 8:59 PM Nisha Moond  wrote:
> >
> > Hi Ajin, Thanks for the patches.
> > I have started reviewing the patches. Please find a few initial
> > comments below (from v7 review, still applicable to v8):
> >
> > 1) Patch-002: pg_dump.c
> > + if (dopt->binary_upgrade && subinfo->subenabled &&
> > fout->remoteVersion >= 170000)
> >   {
> > - if (subinfo->suboriginremotelsn)
> > - {
> > - /*
> > - * Preserve the remote_lsn for the subscriber's replication
> >
> > I could not find any usage of subinfo[i].suboriginremotelsn anymore.
> > It seems to be dead code now. Can we remove it?
>
> Removed it.
>
>
> > ~~~
> >
> > 2) Patch-002 : binary_upgrade_create_replication_origin()
> > - PG_RETURN_VOID();
> > + node_oid = PG_GETARG_OID(0);
> > +
> > + if (node_oid == InvalidOid || node_oid > PG_UINT16_MAX)
> > + ereport(ERROR,
> > + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> > + errmsg("replication origin ID %u is out of range", node_oid));
> > +
> >
> > The above range check allows PG_UINT16_MAX, but that value is not part
> > of the valid replication origin ID range.
> >
> > In origin.h:
> >   #define DoNotReplicateId PG_UINT16_MAX
> >
> > And we already ensure "ReplOriginId != DoNotReplicateId" everywhere
> > else. Would something like the below be more appropriate?
> >   if (node_oid == InvalidReplOriginId || node_oid >= DoNotReplicateId)
> >     ereport(ERROR, ...
> > ~~~
>
> Done.
>
>
> >
> > 3) I think we should add some additional details in
> > logical-replication.sgml, especially under Prepare for
> > Subscriber Upgrades.
> > Some suggestions:
> > 3a) Since all replication origins are now migrated, this:
> >   "...greater than or equal to the number of subscriptions present in
> > the old cluster."
> > could become:
> >   "...greater than or equal to the number of replication origins
> > present in the old cluster."
> >
> > 3b) We should also mention:
> >   The new cluster must contain no replication origins.
> >
>
> Done.
>
>
>
> On Wed, Jun 17, 2026 at 9:42 PM Nisha Moond  wrote:
> >
> > 4) I was able to build successfully without all three new header
> > inclusions below, so we may not need them.
> > --- a/src/backend/utils/adt/pg_upgrade_support.c
> > +++ b/src/backend/utils/adt/pg_upgrade_support.c
> > @@ -11,6 +11,7 @@
> > +#include "access/genam.h"
> > ...
> > +#include "utils/fmgroids.h"
> > ...
> > +#include "utils/snapmgr.h"
> > ~~~
> >
>
> Removed.
>
>
> > 5) Race condition in origin.c: replorigin_create()
> > - heap_freetuple(tuple);
> > + table_close(rel, ExclusiveLock);
> > +
> > + replorigin_create_with_id(roident, roname, InvalidXLogRecPtr);
> > +
> >
> > Due to the above refactoring, CREATE SUBSCRIPTION can now fail because
> > of a race between two concurrent CREATE SUBSCRIPTION commands:
> >
> > postgres=# create subscription sub2 connection 'dbname=postgres
> > host=localhost port=7733' publication pub1;
> > ERROR:  replication origin with ID 2 already exists
> >
> > I think this happens because the table lock is released, allowing
> > another session to create a pg_origin with the next available roident,
> > which replorigin_create_with_id() later attempts to use.
> >
> > Would it make sense to call replorigin_create_with_id() before
> > table_close() so the lock is still held? I tested this and it works,
> > though I'm not fully sure whether self-locking could be a concern
> > here, since replorigin_create_with_id() again acquires a
> > RowExclusiveLock on the same table.
> > ~~~
> >
>
> I have fixed this as suggested by Shveta
>
> ~~~~~~~~~~
>
>
>
> On Thu, Jun 18, 2026 at 7:17 PM shveta malik  wrote:
> >
> > > I think this happens because the table lock is released, allowing
> > > another session to create a pg_origin with the next available roident,
> > > which replorigin_create_with_id() later attempts to use.
> > >
> > > Would it make sense to call replorigin_create_with_id() before
> > > table_close() so the lock is still held? I tested this and it works,
> > > though I'm not fully sure whether self-locking could be a concern
> > > here, since replorigin_create_with_id() again acquires a
> > > RowExclusiveLock on the same table.
> >
> > We can handle this race-condition by moving the table-open to callers
> > rather than internal call replorigin_create_with_id().  But we also
> > need the following changes first:
> >
>
> Yes, did it that way.
>
>
> > 1)
> > replorigin_create_with_id has:
> >
> > + /*
> > + * To avoid needing a TOAST table for pg_replication_origin, we limit
> > + * replication origin names to 512 bytes.  This should be more than enough
> > + * for all practical use.
> > + */
> > + if (strlen(roname) > MAX_RONAME_LEN)
> > + ereport(ERROR,
> > + errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> > + errmsg("replication origin name is too long"),
> > + errdetail("Replication origin names must be no longer than %d bytes.",
> > +   MAX_RONAME_LEN));
> >
> > replorigin_create_with_id() is called by replorigin_create() and
> > binary_upgrade_create_replication_origin().   replorigin_create()
> > already has this check. We should move above check to
> > binary_upgrade_create_replication_origin() and get rid of it from
> > internal function replorigin_create_with_id().
>
> Moved.
>
> >
> > 2)
> >
> > Also the checks:
> > + if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(roident)))
> > + ereport(ERROR,
> > + errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin with ID %u already exists",
> > +    (Oid) roident));
> > +
> > + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> > + ereport(ERROR,
> > + errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin \"%s\" already exists", roname));
> >
> > should be moved to caller binary_upgrade_create_replication_origin().
> > IMO, these checks are not needed for replorigin_create(), it alread
> > has this, which should suffice.
> >
> >                 ereport(ERROR,
> >                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> >                                  errmsg("could not find free
> > replication origin ID")));
> >
> > ~~
> >
> > Once we correctly place these checks, we can move the 'table_open with
> > lock' to caller (before name and id collision checks) instead of
> > replorigin_create_with_id(), which will take care of race-conditions
> > reported by Nisha.
> >
>
> I have moved the roident check out of replorigin_create_with_id(), but
> kept the roname check there as that is not there in
> replorigin_create()
>
> On Fri, Jun 19, 2026 at 5:48 PM Shlok Kyal  wrote:
> > Hi Ajin,
> >
> > Thanks for providing the updated patch, I reviewed the patch and I
> > have some comments:
> >
> > 1. patch is not applying on HEAD and needs a rebase.
> >
> > 2. New line after 'check_new_cluster_replication_origins' is not required:
> > + check_new_cluster_replication_origins();
> > +
> >
> > 3. pg_dumpall with option '--roles-only' also dumps replication origins
> > eg:
> > ./pg_dumpall -p 9000 --binary-upgrade --roles-only > op.sql
> > output contains:
> > -- For binary upgrade, must preserve replication origin roident and remote_lsn
> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> > 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
> >
> > I think in this case we should not dump the replication origins as we
> > explicitly gave the option of '--roles-only'
> >
>
> I have moved the dump_replication_origins under !roles_only and
> !tablespaces_only checks, I think "globals only" is valid for
> replication origins.
>
>
> > 4. pg_dumpall with --globals-only option also dumps replication origins.
> > eg:
> > ./pg_dumpall -p 9000 --binary-upgrade --globals-only> op.sql and
> > output contains:
> > -- For binary upgrade, must preserve replication origin roident and remote_lsn
> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> > 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
> >
> > Is this behaviour intentional? Other logical replication objects
> > (e.g., publications and subscriptions) are not included in pg_dumpall
> > --globals-only, so is it okay to dump replication origin?
> >
>
> This is expected as publications and subscriptions are database
> specific and not globals, while replication origins are global.
>
>
>
> On Mon, Jun 22, 2026 at 2:22 AM Rui Zhao  wrote:
> >>
> >> Hi Ajin,
> >>
> >> Thanks for v8. A couple of comments:
> >>
> >> 1) The PG17 gating seems inconsistent between the dump and the check now.
> >> dumpReplicationOrigins() is called unconditionally:
> >>
> >>     if (binary_upgrade && archDumpFormat == archNull)
> >>         dumpReplicationOrigins(conn);
> >>
> >> but get_subscription_info(), which sets nrepl_origins, is still only
> >> called for old clusters >= 17 in check_new_cluster():
> >>
> >>     if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1700)
> >>         ...
> >>         get_subscription_info(&old_cluster);
> >>
> >> and check_new_cluster_replication_origins() returns early on it:
> >>
> >>     if (old_cluster.nrepl_origins == 0)
> >>         return;
> >>
> >> For a < 17 old cluster get_subscription_info() is never called, so
> >> nrepl_origins stays 0 and this returns early. So when such a cluster has a
> >> (user-created) origin, the origin still gets dumped and recreated, while
> >> the "new cluster must have no origins" and max_active_replication_origins
> >> checks are skipped, and the upgrade fails during restore instead of at the
> >> check step. nrepl_origins is just a count(*) on pg_replication_origin, so
> >> moving its collection out of the >= 1700 block should be enough.
> >>
>
> Yes, good catch. I have separated out the replication origin speciifc
> checks into a different function and moved it oustide the >= 1700
> block
>
> >> 2) 004_subscription.pl only checks subscription origins (pg_). Since
> >> the patch migrates all origins, should we also create a user origin
> >> (pg_replication_origin_create()) and verify its roident/remote_lsn after
> >> the upgrade? That would also cover the case in (1).
>
>
> Added.
>
> All the above changes have been addressed in patch v9.
>
> regards,
> Ajin Cherian
> Fujitsu Australia


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Jun 23, 2026 at 5:20 PM Ajin Cherian  wrote:
>
> All the above changes have been addressed in patch v9.
>

Thanks for the patches. A few ocmments:

1)

+ * In binary-upgrade mode, skip origin creation here. This is required to
+ * preserve the roident from the old cluster for this subscription.

subscription --> subscription's origin

2)
replorigin_create_with_id():

+ if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin \"%s\" already exists", roname));

Can this ever happen? IIUC, since new-cluster should not have any
origin (as per the check introduced) and old cluster can not have
duplicate names, we should not hit this error. Do we want to keep it
as sanity check? If so, can we put a comment atop it.

3)
replorigin_create_with_id:

+ if (remote_lsn != InvalidXLogRecPtr)
+ replorigin_advance(roident, remote_lsn, InvalidXLogRecPtr,
+    false /* backward */,
+    false /* WAL log */);

We do not want to call 'advance' from regular 'replorigin_create'
flow. It is only for binary-Upgrade flow. Do you think we should have
a sanity check here?

if (remote_lsn != InvalidXLogRecPtr)
{
    Assert(IsBinaryUpgrade)
    replorigin_advance(..)
}

4)
replorigin_create:

+ found = true;

+ if (!found)
  ereport(ERROR,
  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
  errmsg("could not find free replication origin ID")));

Do you think we can make use of 'collides' itself here instead of
adding a new 'found' variable. We can move 'collides' outside of loop
and use it to emit above error.

5)
binary_upgrade_create_replication_origin:

+ node = (ReplOriginId) node_oid;
+
+ if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
+ ereport(ERROR,
+ errcode(ERRCODE_DUPLICATE_OBJECT),
+ errmsg("replication origin with ID %u already exists",
+    (Oid) node));

How can we hit this? Same comment as #2.

6)
-check_new_cluster_subscription_configuration(void)
+check_new_cluster_replication_origins(void)

- /* Quick return if there are no subscriptions to be migrated. */
- if (old_cluster.nsubs == 0)
- return;

- if (old_cluster.nsubs > max_active_replication_origins)

With these changes, do we even need to capture old-cluster's 'nsubs'
in get_subscription_info(). I do not see any other usage of nsubs. Let
me know if I am missing any case.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jun 24, 2026 at 10:39 AM shveta malik  wrote:
>
>
> 2)
> replorigin_create_with_id():
>
> + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin \"%s\" already exists", roname));
>
> Can this ever happen? IIUC, since new-cluster should not have any
> origin (as per the check introduced) and old cluster can not have
> duplicate names, we should not hit this error. Do we want to keep it
> as sanity check? If so, can we put a comment atop it.
>

Analyzed a bit more, with this change in patch002, we see an error change:

Without patch:
postgres=# SELECT pg_replication_origin_create('abcd');
 pg_replication_origin_create
------------------------------
                            1
postgres=# SELECT pg_replication_origin_create('abcd');
ERROR:  duplicate key value violates unique constraint
"pg_replication_origin_roname_index"
DETAIL:  Key (roname)=(abcd) already exists.

----

With patch:
postgres=#  SELECT pg_replication_origin_create('abcd');
 pg_replication_origin_create
------------------------------
                            1

postgres=# SELECT pg_replication_origin_create('abcd');
ERROR:  replication origin "abcd" already exists


So without the new check also, we can prevent duplicate name insertion
(even if that happens during upgrade, which I can not see  how). The
new error and the check is not wrong, but slightly redundant. Or let
me know if I am missing something.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Tue, 23 Jun 2026 at 17:20, Ajin Cherian  wrote:
>
> On Wed, Jun 17, 2026 at 8:59 PM Nisha Moond  wrote:
> >
> > Hi Ajin, Thanks for the patches.
> > I have started reviewing the patches. Please find a few initial
> > comments below (from v7 review, still applicable to v8):
> >
> > 1) Patch-002: pg_dump.c
> > + if (dopt->binary_upgrade && subinfo->subenabled &&
> > fout->remoteVersion >= 170000)
> >   {
> > - if (subinfo->suboriginremotelsn)
> > - {
> > - /*
> > - * Preserve the remote_lsn for the subscriber's replication
> >
> > I could not find any usage of subinfo[i].suboriginremotelsn anymore.
> > It seems to be dead code now. Can we remove it?
>
> Removed it.
>
>
> > ~~~
> >
> > 2) Patch-002 : binary_upgrade_create_replication_origin()
> > - PG_RETURN_VOID();
> > + node_oid = PG_GETARG_OID(0);
> > +
> > + if (node_oid == InvalidOid || node_oid > PG_UINT16_MAX)
> > + ereport(ERROR,
> > + errcode(ERRCODE_INVALID_PARAMETER_VALUE),
> > + errmsg("replication origin ID %u is out of range", node_oid));
> > +
> >
> > The above range check allows PG_UINT16_MAX, but that value is not part
> > of the valid replication origin ID range.
> >
> > In origin.h:
> >   #define DoNotReplicateId PG_UINT16_MAX
> >
> > And we already ensure "ReplOriginId != DoNotReplicateId" everywhere
> > else. Would something like the below be more appropriate?
> >   if (node_oid == InvalidReplOriginId || node_oid >= DoNotReplicateId)
> >     ereport(ERROR, ...
> > ~~~
>
> Done.
>
>
> >
> > 3) I think we should add some additional details in
> > logical-replication.sgml, especially under Prepare for
> > Subscriber Upgrades.
> > Some suggestions:
> > 3a) Since all replication origins are now migrated, this:
> >   "...greater than or equal to the number of subscriptions present in
> > the old cluster."
> > could become:
> >   "...greater than or equal to the number of replication origins
> > present in the old cluster."
> >
> > 3b) We should also mention:
> >   The new cluster must contain no replication origins.
> >
>
> Done.
>
>
>
> On Wed, Jun 17, 2026 at 9:42 PM Nisha Moond  wrote:
> >
> > 4) I was able to build successfully without all three new header
> > inclusions below, so we may not need them.
> > --- a/src/backend/utils/adt/pg_upgrade_support.c
> > +++ b/src/backend/utils/adt/pg_upgrade_support.c
> > @@ -11,6 +11,7 @@
> > +#include "access/genam.h"
> > ...
> > +#include "utils/fmgroids.h"
> > ...
> > +#include "utils/snapmgr.h"
> > ~~~
> >
>
> Removed.
>
>
> > 5) Race condition in origin.c: replorigin_create()
> > - heap_freetuple(tuple);
> > + table_close(rel, ExclusiveLock);
> > +
> > + replorigin_create_with_id(roident, roname, InvalidXLogRecPtr);
> > +
> >
> > Due to the above refactoring, CREATE SUBSCRIPTION can now fail because
> > of a race between two concurrent CREATE SUBSCRIPTION commands:
> >
> > postgres=# create subscription sub2 connection 'dbname=postgres
> > host=localhost port=7733' publication pub1;
> > ERROR:  replication origin with ID 2 already exists
> >
> > I think this happens because the table lock is released, allowing
> > another session to create a pg_origin with the next available roident,
> > which replorigin_create_with_id() later attempts to use.
> >
> > Would it make sense to call replorigin_create_with_id() before
> > table_close() so the lock is still held? I tested this and it works,
> > though I'm not fully sure whether self-locking could be a concern
> > here, since replorigin_create_with_id() again acquires a
> > RowExclusiveLock on the same table.
> > ~~~
> >
>
> I have fixed this as suggested by Shveta
>
> ~~~~~~~~~~
>
>
>
> On Thu, Jun 18, 2026 at 7:17 PM shveta malik  wrote:
> >
> > > I think this happens because the table lock is released, allowing
> > > another session to create a pg_origin with the next available roident,
> > > which replorigin_create_with_id() later attempts to use.
> > >
> > > Would it make sense to call replorigin_create_with_id() before
> > > table_close() so the lock is still held? I tested this and it works,
> > > though I'm not fully sure whether self-locking could be a concern
> > > here, since replorigin_create_with_id() again acquires a
> > > RowExclusiveLock on the same table.
> >
> > We can handle this race-condition by moving the table-open to callers
> > rather than internal call replorigin_create_with_id().  But we also
> > need the following changes first:
> >
>
> Yes, did it that way.
>
>
> > 1)
> > replorigin_create_with_id has:
> >
> > + /*
> > + * To avoid needing a TOAST table for pg_replication_origin, we limit
> > + * replication origin names to 512 bytes.  This should be more than enough
> > + * for all practical use.
> > + */
> > + if (strlen(roname) > MAX_RONAME_LEN)
> > + ereport(ERROR,
> > + errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> > + errmsg("replication origin name is too long"),
> > + errdetail("Replication origin names must be no longer than %d bytes.",
> > +   MAX_RONAME_LEN));
> >
> > replorigin_create_with_id() is called by replorigin_create() and
> > binary_upgrade_create_replication_origin().   replorigin_create()
> > already has this check. We should move above check to
> > binary_upgrade_create_replication_origin() and get rid of it from
> > internal function replorigin_create_with_id().
>
> Moved.
>
> >
> > 2)
> >
> > Also the checks:
> > + if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(roident)))
> > + ereport(ERROR,
> > + errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin with ID %u already exists",
> > +    (Oid) roident));
> > +
> > + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> > + ereport(ERROR,
> > + errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin \"%s\" already exists", roname));
> >
> > should be moved to caller binary_upgrade_create_replication_origin().
> > IMO, these checks are not needed for replorigin_create(), it alread
> > has this, which should suffice.
> >
> >                 ereport(ERROR,
> >                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
> >                                  errmsg("could not find free
> > replication origin ID")));
> >
> > ~~
> >
> > Once we correctly place these checks, we can move the 'table_open with
> > lock' to caller (before name and id collision checks) instead of
> > replorigin_create_with_id(), which will take care of race-conditions
> > reported by Nisha.
> >
>
> I have moved the roident check out of replorigin_create_with_id(), but
> kept the roname check there as that is not there in
> replorigin_create()
>
> On Fri, Jun 19, 2026 at 5:48 PM Shlok Kyal  wrote:
> > Hi Ajin,
> >
> > Thanks for providing the updated patch, I reviewed the patch and I
> > have some comments:
> >
> > 1. patch is not applying on HEAD and needs a rebase.
> >
> > 2. New line after 'check_new_cluster_replication_origins' is not required:
> > + check_new_cluster_replication_origins();
> > +
> >
> > 3. pg_dumpall with option '--roles-only' also dumps replication origins
> > eg:
> > ./pg_dumpall -p 9000 --binary-upgrade --roles-only > op.sql
> > output contains:
> > -- For binary upgrade, must preserve replication origin roident and remote_lsn
> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> > 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
> >
> > I think in this case we should not dump the replication origins as we
> > explicitly gave the option of '--roles-only'
> >
>
> I have moved the dump_replication_origins under !roles_only and
> !tablespaces_only checks, I think "globals only" is valid for
> replication origins.
>
>
> > 4. pg_dumpall with --globals-only option also dumps replication origins.
> > eg:
> > ./pg_dumpall -p 9000 --binary-upgrade --globals-only> op.sql and
> > output contains:
> > -- For binary upgrade, must preserve replication origin roident and remote_lsn
> > SELECT pg_catalog.binary_upgrade_create_replication_origin('1'::pg_catalog.oid,
> > 'pg_16387'::pg_catalog.text, '0/00000000'::pg_catalog.pg_lsn);
> >
> > Is this behaviour intentional? Other logical replication objects
> > (e.g., publications and subscriptions) are not included in pg_dumpall
> > --globals-only, so is it okay to dump replication origin?
> >
>
> This is expected as publications and subscriptions are database
> specific and not globals, while replication origins are global.
>
>
>
> On Mon, Jun 22, 2026 at 2:22 AM Rui Zhao  wrote:
> >>
> >> Hi Ajin,
> >>
> >> Thanks for v8. A couple of comments:
> >>
> >> 1) The PG17 gating seems inconsistent between the dump and the check now.
> >> dumpReplicationOrigins() is called unconditionally:
> >>
> >>     if (binary_upgrade && archDumpFormat == archNull)
> >>         dumpReplicationOrigins(conn);
> >>
> >> but get_subscription_info(), which sets nrepl_origins, is still only
> >> called for old clusters >= 17 in check_new_cluster():
> >>
> >>     if (GET_MAJOR_VERSION(old_cluster.major_version) >= 1700)
> >>         ...
> >>         get_subscription_info(&old_cluster);
> >>
> >> and check_new_cluster_replication_origins() returns early on it:
> >>
> >>     if (old_cluster.nrepl_origins == 0)
> >>         return;
> >>
> >> For a < 17 old cluster get_subscription_info() is never called, so
> >> nrepl_origins stays 0 and this returns early. So when such a cluster has a
> >> (user-created) origin, the origin still gets dumped and recreated, while
> >> the "new cluster must have no origins" and max_active_replication_origins
> >> checks are skipped, and the upgrade fails during restore instead of at the
> >> check step. nrepl_origins is just a count(*) on pg_replication_origin, so
> >> moving its collection out of the >= 1700 block should be enough.
> >>
>
> Yes, good catch. I have separated out the replication origin speciifc
> checks into a different function and moved it oustide the >= 1700
> block
>
> >> 2) 004_subscription.pl only checks subscription origins (pg_). Since
> >> the patch migrates all origins, should we also create a user origin
> >> (pg_replication_origin_create()) and verify its roident/remote_lsn after
> >> the upgrade? That would also cover the case in (1).
>
>
> Added.
>
> All the above changes have been addressed in patch v9.
>
Thanks for the updated patch. I have reviewed the patch and here are
some my comments:

1. Since we are quering only one column, do we need to use 'i_norigins'?

+void
+get_replication_origin_info(ClusterInfo *cluster)
+{
+ PGconn    *conn;
+ PGresult   *res;
+ int i_norigins;
+
+ conn = connectToServer(cluster, "template1");
+ res = executeQueryOrDie(conn, "SELECT count(*) AS norigins "
+    "FROM pg_catalog.pg_replication_origin");
+ i_norigins = PQfnumber(res, "norigins");
+
+ cluster->nrepl_origins = atoi(PQgetvalue(res, 0, i_norigins));
+ PQclear(res);
+
+ PQfinish(conn);
+}
I think we can directly use:
cluster->nrepl_origins = atoi(PQgetvalue(res, 0, 0));

Thoughts?

2. In the above code should we also add a check like:
if (PQntuples(res) != 1)
pg_fatal("could not count the number of replication origins");

3. The brackets are not required:
+ if (!tablespaces_only && !roles_only && binary_upgrade)
+ {
+ /* Dump replication origins */
+ dumpReplicationOrigins(conn);
  }
We can move the comment '/* Dump replication origins */' above if condition.
It will make it consistent with the existing code.

4. I ran the tests locally and found that the test_decoding test suit
is failing:
not ok 10    - replorigin                                249 ms

diff:
 -- ensure duplicate creations fail
 SELECT pg_replication_origin_create('regress_test_decoding: regression_slot');
-ERROR:  duplicate key value violates unique constraint
"pg_replication_origin_roname_index"
-DETAIL:  Key (roname)=(regress_test_decoding: regression_slot) already exists.
+ERROR:  replication origin "regress_test_decoding: regression_slot"
already exists
 -- ensure inactive origin cannot be set as session one if pid is specified
 SELECT pg_replication_origin_session_setup('regress_test_decoding:
regression_slot', -1);
 ERROR:  cannot use PID -1 for inactive replication origin with ID 1

I think this is expected because this patch adds a new function
'replorigin_create_with_id'
which adds a check for the already existing replication origin.
In HEAD we don't have such a check. So I think we should update the
expected output file.

Thanks,
Shlok Kyal


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello

+# Verify that the subscription related replication origins are
preserved after upgrade.
+my $post_roident_rows = $new_sub->safe_psql('postgres',
+    "SELECT s.subname, o.roident
+     FROM pg_subscription s
+     JOIN pg_replication_origin o ON o.roname = 'pg_' || s.oid::text
+     ORDER BY s.subname"
+);
+for my $row (split /\n/, $post_roident_rows)
+{
+    my ($subname, $roident) = split /\|/, $row;
+    is($roident, $pre_upgrade_roident{$subname},
+        "roident preserved for subscription '$subname' after upgrade");
+}
+

Won't this check miss (and silently pass) if an entry is missing
post-upgrade? It verifies that all entries that exists match the pre
upgrade entries, but it doesn't verify that the list is the same.


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Wed, Jun 24, 2026 at 2:07 AM Rui Zhao  wrote:
>
> Hi Ajin,
>
> Thanks for v9, and for addressing both my earlier comments. I also went
> through the rest of v9 -- the other reviewers' comments and the
> corresponding fixes (including the replorigin_create() locking rework) look
> good to me; I didn't find any issues there.
>
> A follow-up on the version gating, though: I think it now moved a bit too
> far. get_replication_origin_info() is called unconditionally (outside the
> >= 1700 block):
>
>     /* Get replication origin information */
>     get_replication_origin_info(&old_cluster);
>
> and it runs "SELECT count(*) FROM pg_catalog.pg_replication_origin".
> pg_dumpall's dumpReplicationOrigins() queries the same catalog with no
> version guard either. But pg_replication_origin only exists from 9.5
> (commit 5aa2350426), while pg_upgrade still accepts old clusters back to
> 9.2:
>
>     if (GET_MAJOR_VERSION(old_cluster.major_version) < 902)
>         pg_fatal("This utility can only upgrade from PostgreSQL version %s
>                  and later.", "9.2");
>
> So upgrading from 9.2/9.3/9.4 now fails: the query hits a non-existent
> catalog and pg_fatal()s (and dumpReplicationOrigins would too).
> It should be gated on the version where origins were introduced, e.g.
>
>     if (GET_MAJOR_VERSION(old_cluster.major_version) >= 905)
>         get_replication_origin_info(&old_cluster);
>
> with the matching server_version >= 90500 check on the pg_dumpall side.
> That keeps the < 17 case I flagged working while not breaking 9.2-9.4
> (which have no origins to migrate anyway).
>

Thanks, I have added both the flags.

> One nit while here: there is an extra blank line after the
> check_new_cluster_replication_origins() call in check_new_cluster().
>

Removed.


On Wed, Jun 24, 2026 at 3:09 PM shveta malik  wrote:
>
> On Tue, Jun 23, 2026 at 5:20 PM Ajin Cherian  wrote:
> >
> > All the above changes have been addressed in patch v9.
> >
>
> Thanks for the patches. A few ocmments:
>
> 1)
>
> + * In binary-upgrade mode, skip origin creation here. This is required to
> + * preserve the roident from the old cluster for this subscription.
>
> subscription --> subscription's origin
>

Changed.

> 2)
> replorigin_create_with_id():
>
> + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin \"%s\" already exists", roname));
>
> Can this ever happen? IIUC, since new-cluster should not have any
> origin (as per the check introduced) and old cluster can not have
> duplicate names, we should not hit this error. Do we want to keep it
> as sanity check? If so, can we put a comment atop it.
>

I've removed it.

> 3)
> replorigin_create_with_id:
>
> + if (remote_lsn != InvalidXLogRecPtr)
> + replorigin_advance(roident, remote_lsn, InvalidXLogRecPtr,
> +    false /* backward */,
> +    false /* WAL log */);
>
> We do not want to call 'advance' from regular 'replorigin_create'
> flow. It is only for binary-Upgrade flow. Do you think we should have
> a sanity check here?
>
> if (remote_lsn != InvalidXLogRecPtr)
> {
>     Assert(IsBinaryUpgrade)
>     replorigin_advance(..)
> }
>

Done.

> 4)
> replorigin_create:
>
> + found = true;
>
> + if (!found)
>   ereport(ERROR,
>   (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
>   errmsg("could not find free replication origin ID")));
>
> Do you think we can make use of 'collides' itself here instead of
> adding a new 'found' variable. We can move 'collides' outside of loop
> and use it to emit above error.
>

I've removed found and instead checked if the roident has reached the max limit

> 5)
> binary_upgrade_create_replication_origin:
>
> + node = (ReplOriginId) node_oid;
> +
> + if (SearchSysCacheExists1(REPLORIGIDENT, ObjectIdGetDatum(node)))
> + ereport(ERROR,
> + errcode(ERRCODE_DUPLICATE_OBJECT),
> + errmsg("replication origin with ID %u already exists",
> +    (Oid) node));
>
> How can we hit this? Same comment as #2.
>

Removed

> 6)
> -check_new_cluster_subscription_configuration(void)
> +check_new_cluster_replication_origins(void)
>
> - /* Quick return if there are no subscriptions to be migrated. */
> - if (old_cluster.nsubs == 0)
> - return;
>
> - if (old_cluster.nsubs > max_active_replication_origins)
>
> With these changes, do we even need to capture old-cluster's 'nsubs'
> in get_subscription_info(). I do not see any other usage of nsubs. Let
> me know if I am missing any case.

I've removed nsubs




On Wed, Jun 24, 2026 at 3:21 PM shveta malik  wrote:
>
> On Wed, Jun 24, 2026 at 10:39 AM shveta malik  wrote:
> >
> >
> > 2)
> > replorigin_create_with_id():
> >
> > + if (SearchSysCacheExists1(REPLORIGNAME, roname_d))
> > + ereport(ERROR,
> > + errcode(ERRCODE_DUPLICATE_OBJECT),
> > + errmsg("replication origin \"%s\" already exists", roname));
> >
> > Can this ever happen? IIUC, since new-cluster should not have any
> > origin (as per the check introduced) and old cluster can not have
> > duplicate names, we should not hit this error. Do we want to keep it
> > as sanity check? If so, can we put a comment atop it.
> >
>
> Analyzed a bit more, with this change in patch002, we see an error change:
>
> Without patch:
> postgres=# SELECT pg_replication_origin_create('abcd');
>  pg_replication_origin_create
> ------------------------------
>                             1
> postgres=# SELECT pg_replication_origin_create('abcd');
> ERROR:  duplicate key value violates unique constraint
> "pg_replication_origin_roname_index"
> DETAIL:  Key (roname)=(abcd) already exists.
>
> ----
>
> With patch:
> postgres=#  SELECT pg_replication_origin_create('abcd');
>  pg_replication_origin_create
> ------------------------------
>                             1
>
> postgres=# SELECT pg_replication_origin_create('abcd');
> ERROR:  replication origin "abcd" already exists
>
>
> So without the new check also, we can prevent duplicate name insertion
> (even if that happens during upgrade, which I can not see  how). The
> new error and the check is not wrong, but slightly redundant. Or let
> me know if I am missing something.
>

I've removed that check.




On Wed, Jun 24, 2026 at 11:27 PM Shlok Kyal  wrote:
>
> Thanks for the updated patch. I have reviewed the patch and here are
> some my comments:
>
> 1. Since we are quering only one column, do we need to use 'i_norigins'?
>
> +void
> +get_replication_origin_info(ClusterInfo *cluster)
> +{
> + PGconn    *conn;
> + PGresult   *res;
> + int i_norigins;
> +
> + conn = connectToServer(cluster, "template1");
> + res = executeQueryOrDie(conn, "SELECT count(*) AS norigins "
> +    "FROM pg_catalog.pg_replication_origin");
> + i_norigins = PQfnumber(res, "norigins");
> +
> + cluster->nrepl_origins = atoi(PQgetvalue(res, 0, i_norigins));
> + PQclear(res);
> +
> + PQfinish(conn);
> +}
> I think we can directly use:
> cluster->nrepl_origins = atoi(PQgetvalue(res, 0, 0));
>
> Thoughts?

Removed it.

>
> 2. In the above code should we also add a check like:
> if (PQntuples(res) != 1)
> pg_fatal("could not count the number of replication origins");
>

Added.

> 3. The brackets are not required:
> + if (!tablespaces_only && !roles_only && binary_upgrade)
> + {
> + /* Dump replication origins */
> + dumpReplicationOrigins(conn);
>   }
> We can move the comment '/* Dump replication origins */' above if condition.
> It will make it consistent with the existing code.
>

I've moved the comment up but keeping the brackets as it has more than
one line, that is the recommendation from Tom Lane.

> 4. I ran the tests locally and found that the test_decoding test suit
> is failing:
> not ok 10    - replorigin                                249 ms
>
> diff:
>  -- ensure duplicate creations fail
>  SELECT pg_replication_origin_create('regress_test_decoding: regression_slot');
> -ERROR:  duplicate key value violates unique constraint
> "pg_replication_origin_roname_index"
> -DETAIL:  Key (roname)=(regress_test_decoding: regression_slot) already exists.
> +ERROR:  replication origin "regress_test_decoding: regression_slot"
> already exists
>  -- ensure inactive origin cannot be set as session one if pid is specified
>  SELECT pg_replication_origin_session_setup('regress_test_decoding:
> regression_slot', -1);
>  ERROR:  cannot use PID -1 for inactive replication origin with ID 1
>
> I think this is expected because this patch adds a new function
> 'replorigin_create_with_id'
> which adds a check for the already existing replication origin.
> In HEAD we don't have such a check. So I think we should update the
> expected output file.
>

Based on feedback from Shveta, I've removed that new error as changing
existing behaviour isn't required.



On Thu, Jun 25, 2026 at 2:45 AM Zsolt Parragi  wrote:
>
> Hello
>
> +# Verify that the subscription related replication origins are
> preserved after upgrade.
> +my $post_roident_rows = $new_sub->safe_psql('postgres',
> +    "SELECT s.subname, o.roident
> +     FROM pg_subscription s
> +     JOIN pg_replication_origin o ON o.roname = 'pg_' || s.oid::text
> +     ORDER BY s.subname"
> +);
> +for my $row (split /\n/, $post_roident_rows)
> +{
> +    my ($subname, $roident) = split /\|/, $row;
> +    is($roident, $pre_upgrade_roident{$subname},
> +        "roident preserved for subscription '$subname' after upgrade");
> +}
> +
>
> Won't this check miss (and silently pass) if an entry is missing
> post-upgrade? It verifies that all entries that exists match the pre
> upgrade entries, but it doesn't verify that the list is the same.

Modified this to iterate over pre upgrade and post upgrade
subscriptions making sure both are present.

All the above changes are updated in patch v10.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Sun, Jul 5, 2026 at 9:40 PM Rui Zhao  wrote:
>
> Hi Ajin,
>
> Thanks for v10. On the version gating I asked about earlier -- I think it's
> now moot, and the gates can come back out.
>
> Since v10, 14d8418083 ("Remove pg_upgrade support for upgrading from pre-v10
> servers") raised pg_upgrade's minimum source version to v10.
> pg_replication_origin has existed since 9.5, so every cluster pg_upgrade now
> accepts already has it, and the original unconditional
> get_replication_origin_info() is safe again. Both gates that went into v10 are
> now always true:
>
>   - check.c:      if (GET_MAJOR_VERSION(old_cluster.major_version) >= 905)
>   - pg_dumpall.c: if (server_version >= 90500)   -- only reached under
>                   binary_upgrade, i.e. against the v10+ old cluster
>
> 14d8418083 was itself removing exactly this kind of pre-v10 version check
> across pg_upgrade, so dropping these fits the same cleanup.
>

Thanks for pointing to the commit.

> v10 doesn't apply on current master anyway (0002 fails on pg_proc.dat), so
> could you post a rebase? That'd let it be built and tested against HEAD, and
> it's a natural point to drop the two gates and go back to the unconditional
> calls.

I can apply v10 on the latest HEAD (9d1188f298), can you please try it again?

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Hi Ajin,

Shveta's right, sorry for the noise -- git am --3way applies v10 cleanly on
HEAD (9d1188f298) and it builds. "git apply --check" was tripping on the
shifted pg_proc.dat hunk on my end.

Confirmed Shveta's (6), and it's a crash, not just a bad read:

  cluster->sub_retain_dead_tuples = (strcmp(PQgetvalue(res, 0,
i_retain_dead_tuples), "t") == 0);

With no subscriptions the < 1900 query returns zero rows, PQgetvalue(res, 0,
...) returns NULL for a nonexistent row, and the strcmp segfaults (reproduced
with a small libpq program). Upgrading a v17/v18 cluster that has no
subscriptions hits it. Shveta's "SELECT false" fix is right.

A few more comments from re-reading v10:

1) The doc hunk updates this sentence:

    -     Commit timestamps and origin data are not preserved during
the upgrade.
    +     Commit timestamps are not preserved during the upgrade.

but the twin comment in pg_upgrade.c (~line 222) is left unchanged and needs
the same edit:

     * upgrade. Additionally, commit timestamps and origin data are not
     * preserved during the upgrade. So, even after creating the slot, the

2) dumpReplicationOrigins:

    + appendPQExpBufferStr(buf,
    + "SELECT o.*, os.remote_lsn "
    + "FROM pg_catalog.pg_replication_origin o "
    + "LEFT OUTER JOIN pg_catalog.pg_replication_origin_status os ON
o.roident = os.local_id ");

No ORDER BY, so the output order is whatever the heap returns; every other
query in pg_dumpall.c has one. ORDER BY o.roident would keep the dump stable.

3) Trivia: trailing space in the section header --

    + fprintf(OPF, "--\n-- Replication Origins \n--\n\n");

and a stray blank line at the end of replorigin_create_with_id():

    +    false /* WAL log */);
    + }
    +
    +}

Also, per my earlier mail, the >= 905 / >= 90500 gates can come out now that
14d8418083 raised the pg_upgrade floor to v10.

Thanks,
Rui


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 12:10 PM Shlok Kyal  wrote:
>
> > All the above changes are updated in patch v10.
> >
> I noticed that we can create user defined replication origin even if the
> total count of replication origins exceeds the max_active_replication_origins
> Example:
> postgres=# show max_active_replication_origins;
>  max_active_replication_origins
> --------------------------------
>  1
>
> postgres=# select * from pg_replication_origin;
>  roident |  roname
> ---------+----------
>        1 | pg_16387
>
> postgres=# SELECT pg_replication_origin_create('origin1');
>  pg_replication_origin_create
> ------------------------------
>                             2
>
> postgres=# select * from pg_replication_origin;
>  roident |  roname
> ---------+----------
>        1 | pg_16387
>        2 | origin1
>
> postgres=# select * from pg_replication_origin_status;
>  local_id | external_id | remote_lsn | local_lsn
> ----------+-------------+------------+------------
>         1 | pg_16387    | 0/00000000 | 0/00000000
>
> The documentation for max_active_replication_origins says:
> ```
> Specifies how many replication origins (see
> ) can be tracked simultaneously,
> effectively limiting how many logical replication subscriptions can
> be created on the server. Setting it to a lower value than the current
> number of tracked replication origins (reflected in
> pg_replication_origin_status)
> will prevent the server from starting. It defaults to 10. This parameter
> can only be set at server start.
> ```
> Since the user-created replication origin above is not
> actively tracked in pg_replication_origin_status, no error is reported.
>
> But with this patch, during pg_upgrade we are checking the
> 'max_active_replication_origins' against 'old_cluster.nrepl_origins'
> + if (old_cluster.nrepl_origins > max_active_replication_origins)
>   pg_fatal("\"max_active_replication_origins\" (%d) must be greater
> than or equal to the number of "
> - "subscriptions (%d) in the old cluster",
> - max_active_replication_origins, old_cluster.nsubs);
> + "replication origins (%d) in the old cluster",
> + max_active_replication_origins, old_cluster.nrepl_origins);
>
> Since old_cluster.nrepl_origins counts all replication origins, including
> user-created ones that may not be tracked, should this check instead compare
> max_active_replication_origins with 'the number of rows in
> pg_replication_origin_status in old cluster' (i.e., the number of
> tracked replication origins)?
>

Thanks Shlok for exploring this scenario.

I had a look at it. Please find my analysis.

I was under the assumption that subscription creation (which
internally creates a replication origin) would fail if
max_active_replication_origins was exceeded. However, that is not the
case. See the following experiment:

postgres=# show max_active_replication_origins;
 max_active_replication_origins
--------------------------------
 2

Al these commands succeed:

postgres=# create subscription sub1 ...
postgres=# create subscription sub2 ..
postgres=#  SELECT pg_replication_origin_create('user_origin1');
postgres=#  SELECT pg_replication_origin_create('user_origin2');
postgres=#  SELECT pg_replication_origin_create('user_origin3');
postgres=#  SELECT pg_replication_origin_create('user_origin4');
postgres=# create subscription sub3 ..
postgres=# create subscription sub4...

postgres=# select * from pg_replication_origin_status;
 local_id | external_id | remote_lsn | local_lsn
----------+-------------+------------+------------
        1 | pg_16384    | 0/00000000 | 0/00000000
        2 | pg_16385    | 0/00000000 | 0/00000000
(2 rows)


postgres=# select * from pg_replication_origin;
 roident |    roname
---------+--------------
       1 | pg_16384
       2 | pg_16385
       3 | user_origin1
       4 | user_origin2
       5 | user_origin3
       6 | user_origin4
       7 | pg_16387
       8 | pg_16388
(8 rows)

As shown above, sub3 and sub4 are created successfully, but their
replication origins are not tracked because there are no free active
replication origin slots. The apply workers for these subscriptions
also fail to start:

LOG:  logical replication apply worker for subscription "sub3" has started
ERROR:  could not find free replication state slot for replication
origin with ID 7
HINT:  Increase "max_active_replication_origins" and try again.
LOG:  background worker "logical replication apply worker" (PID
277193) exited with exit code 1

This means that if we implement the check suggested by Shlok:

Although pg_upgrade would succeed, it could leave some subscriptions
on the new cluster in non-functional state. I agree that this
situation (non-functional subscriptions) is also possible on the old
cluster. However, this would also deviate from the previous
implementation, where check_new_cluster_subscription_configuration()
compared old_cluster.nsubs against 'max_active_replication_origins' on
the new cluster, rather than comparing the number of entries in
pg_replication_origin_status.

For this reason, my inclination is to revert to the previous
implementation, where we compare old_cluster.nsubs with
max_active_replication_origins. But I'd like to hear what others think
before we make this change.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Mon, Jul 6, 2026 at 6:40 PM Rui Zhao  wrote:
>
> Hi Ajin,
>
> Shveta's right, sorry for the noise -- git am --3way applies v10 cleanly on
> HEAD (9d1188f298) and it builds. "git apply --check" was tripping on the
> shifted pg_proc.dat hunk on my end.
>
> Confirmed Shveta's (6), and it's a crash, not just a bad read:

Thanks for verifying it.

>   cluster->sub_retain_dead_tuples = (strcmp(PQgetvalue(res, 0,
> i_retain_dead_tuples), "t") == 0);
>
> With no subscriptions the < 1900 query returns zero rows, PQgetvalue(res, 0,
> ...) returns NULL for a nonexistent row, and the strcmp segfaults (reproduced
> with a small libpq program). Upgrading a v17/v18 cluster that has no
> subscriptions hits it. Shveta's "SELECT false" fix is right.
>
> A few more comments from re-reading v10:
>
> 1) The doc hunk updates this sentence:
>
>     -     Commit timestamps and origin data are not preserved during
> the upgrade.
>     +     Commit timestamps are not preserved during the upgrade.
>
> but the twin comment in pg_upgrade.c (~line 222) is left unchanged and needs
> the same edit:
>
>      * upgrade. Additionally, commit timestamps and origin data are not
>      * preserved during the upgrade. So, even after creating the slot, the
>
> 2) dumpReplicationOrigins:
>
>     + appendPQExpBufferStr(buf,
>     + "SELECT o.*, os.remote_lsn "
>     + "FROM pg_catalog.pg_replication_origin o "
>     + "LEFT OUTER JOIN pg_catalog.pg_replication_origin_status os ON
> o.roident = os.local_id ");
>
> No ORDER BY, so the output order is whatever the heap returns; every other
> query in pg_dumpall.c has one. ORDER BY o.roident would keep the dump stable.

+1

>
> 3) Trivia: trailing space in the section header --
>
>     + fprintf(OPF, "--\n-- Replication Origins \n--\n\n");
>
> and a stray blank line at the end of replorigin_create_with_id():
>
>     +    false /* WAL log */);
>     + }
>     +
>     +}
>
> Also, per my earlier mail, the >= 905 / >= 90500 gates can come out now that
> 14d8418083 raised the pg_upgrade floor to v10.
>
> Thanks,
> Rui


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jul 8, 2026 at 11:51 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Shveta,
>
> > For this reason, my inclination is to revert to the previous
> > implementation, where we compare old_cluster.nsubs with
> > max_active_replication_origins. But I'd like to hear what others think
> > before we make this change.
>
> But if origin created by users (or any extensions) have already been tracking the
> Remote_lsn, they should be taken into account. If there are three enabled
> subscriptions, two active user-created origins but the max_active_origin is set
> to three on the new node, the upgrading should fail.
>
> I prefer to preserve the current behavior of the patch, which compares
> max_active_origin and total number of origins. It might cause the false-positive,
> but even now it can happen. E.g., if there was a subscription which has never
> been enabled.
>

Okay, I missed this point earlier. I agree, let's retain the current
behaviour itself.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Jul 8, 2026 at 11:51 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> > For this reason, my inclination is to revert to the previous
> > implementation, where we compare old_cluster.nsubs with
> > max_active_replication_origins. But I'd like to hear what others think
> > before we make this change.
>
> But if origin created by users (or any extensions) have already been tracking the
> Remote_lsn, they should be taken into account. If there are three enabled
> subscriptions, two active user-created origins but the max_active_origin is set
> to three on the new node, the upgrading should fail.
>

Fair point but isn't it sufficient to check the tracked_origins rather
than all origins? In docs of max_active_replication_origins, we say:
"Setting it to a lower value than the current number of tracked
replication origins (reflected in pg_replication_origin_status) will
prevent the server from starting." which suggests here we should have
a tight check of tracked_origins against
max_active_replication_origins.

> I prefer to preserve the current behavior of the patch, which compares
> max_active_origin and total number of origins. It might cause the false-positive,
> but even now it can happen. E.g., if there was a subscription which has never
> been enabled.
>

I think it is possible that non-tracked origins (e.g for subscriptions
that get enabled only after upgrade) could lead to ERROR after upgrade
and starting the server but users can always increase
max_active_replication_origins to accommodate that which she anyway
needs to do even before upgrade.

-- 
With Regards,
Amit Kapila.


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Jun 16, 2026 at 2:50 PM Ajin Cherian  wrote:
>
> On Mon, Jun 15, 2026 at 9:31 PM Amit Kapila  wrote:
>
>>
>> Separately, I don't think we actually need to preserve the
>> subscription OID to meet the goal here. pg_commit_ts stores the
>> numeric roident, not the origin name or the sub OID, and conflict
>> detection compares roidents. So the invariant we must keep is "each
>> subscription owns the same roident after upgrade", which doesn't
>> depend on the name being stable.
>>
>>
>
> Replication origins are global objects and are therefore dumped by pg_dumpall, while subscriptions are database-specific and are dumped by pg_dump. In pg_upgrade, pg_dumpall runs before pg_dump.
>
> The complication if subscription OID is not preserved is that subscription-associated origins derive their name from the subscription's OID. If the subscription OID is not preserved across upgrades, the origin name on the new cluster will differ from the old one, making it impossible to restore the origin independently. For these origins, creation must happen after CreateSubscription has established the new OID and not upfront in pg_dumpall.
>
> Non-subscription origins have no such dependency and continue to be created separately as before. The subscription code also cannot be left untouched: even once the subscription is created, rather than origin being created inside CreateSubscription, its associated origin must still be explicitly created via binary_upgrade_create_replication_origin to ensure the roident matches the original node, which means CreateSubscription needs to be modified anyways. So, there is an advantage of reducing code if subscription OID is preserved and all origins keep the same name as the old node.
>

I think here the key is not reducing the code foot print in
CreateSubscription rather the non-subscription origins anyway needs to
be created separately by pg_dumpall as they don't have any binding
with subscription. So, if we don't preserve sub OIDs, we will never be
able to match the names of origins created with pg_dumpall and then
later used by subscriptions. I feel this reasoning should be captured
in the commit message.

-- 
With Regards,
Amit Kapila.


RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Dear Amit,

> Fair point but isn't it sufficient to check the tracked_origins rather
> than all origins? In docs of max_active_replication_origins, we say:
> "Setting it to a lower value than the current number of tracked
> replication origins (reflected in pg_replication_origin_status) will
> prevent the server from starting." which suggests here we should have
> a tight check of tracked_origins against
> max_active_replication_origins.

Basically it sounds good, but it can slightly change the behavior if the old node
has some subscriptions which have never been enabled. Till now, we just counted
the number of subscriptions, thus we took into account them [1]. But after the
patch they can be ignored; IIUC pg_upgrade can succeed in the case.

If the change is OK, we can proceed with your (and Shlok-san's) idea.

[1]: reproducer is below.
1. initialized old node with max_active_replication_origins=1
2. created two subscriptions with (connect=false)
3. initialized new node with max_active_replication_origins=1
4. ran pg_upgrade and it did error-out

```
$ pg_upgrade -b /usr/local/pgsql/bin/ -d old/ -D new/ -U postgres
Performing Consistency Checks
-----------------------------
...
Checking new cluster configuration for subscriptions          
"max_active_replication_origins" (1) must be greater than or equal to the number of subscriptions (2) in the old cluster
Failure, exiting
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jul 8, 2026 at 4:12 PM Amit Kapila  wrote:
>
> On Wed, Jul 8, 2026 at 3:37 PM Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > > Fair point but isn't it sufficient to check the tracked_origins rather
> > > than all origins? In docs of max_active_replication_origins, we say:
> > > "Setting it to a lower value than the current number of tracked
> > > replication origins (reflected in pg_replication_origin_status) will
> > > prevent the server from starting." which suggests here we should have
> > > a tight check of tracked_origins against
> > > max_active_replication_origins.
> >
> > Basically it sounds good, but it can slightly change the behavior if the old node
> > has some subscriptions which have never been enabled. Till now, we just counted
> > the number of subscriptions, thus we took into account them [1]. But after the
> > patch they can be ignored; IIUC pg_upgrade can succeed in the case.
> >
> > If the change is OK, we can proceed with your (and Shlok-san's) idea.
> >
> > [1]: reproducer is below.
> > 1. initialized old node with max_active_replication_origins=1
> > 2. created two subscriptions with (connect=false)
> > 3. initialized new node with max_active_replication_origins=1
> > 4. ran pg_upgrade and it did error-out
> >
> > ```
> > $ pg_upgrade -b /usr/local/pgsql/bin/ -d old/ -D new/ -U postgres
> > Performing Consistency Checks
> > -----------------------------
> > ...
> > Checking new cluster configuration for subscriptions
> > "max_active_replication_origins" (1) must be greater than or equal to the number of subscriptions (2) in the old cluster
> > Failure, exiting
> > ```
> >
>
> Yes, I understand this case but I feel the old check is more
> restrictive than required. We might want to even back-patch this small
> part in future if we see any such user complaint.
>

Okay, makes sense.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, Jul 9, 2026 at 5:07 PM Ajin Cherian  wrote:
>
> Thank you all for the comments. I have tried to address all the
> comments. I am not responding to each of them here. Based on the
> discussion above, I have retained the logic as mentioned by Shlok to
> compare active origins against max_active_replication_origins.
>
> Attaching v11 with all comments addressed.
>

Thank You Ajin, a few trivial comments:


1)
       The new cluster must have
       max_active_replication_origins
       configured to a value greater than or equal to the number of
-      subscriptions present in the old cluster.
+      replication origins present in the old cluster. The new cluster
must contain no replication origins.

This needs change as well.


2)
+ "LEFT OUTER JOIN pg_catalog.pg_replication_origin_status os ON
o.roident = os.local_id "

We may as well replace 'LEFT OUTER' with 'LEFT'. The 'OUTER' is
generally optional. But I leave it to you.
(The doc says: 'The words INNER and OUTER are optional in all forms.
INNER is the default; LEFT, RIGHT, and FULL imply an outer join.')

3)
+ * Also verify that the max_active_replication_origins configuration is
+ * enough for creating all the replication origins.

We should change this too.

4)
+ * Compare against the number of active origins in the old cluster not the

cluster not --> cluster, not

5)
get_replication_origin_info:
+ if (PQntuples(res) != 1)
+ pg_fatal("could not get the number of replication origins");
+ cluster->nrepl_origins = atoi(PQgetvalue(res, 0, 0));

Can we please leave a blank line after pg_fatal for better readability.

6)
+ * with an entry in pg_replication_origin_status. This can be less than
+ * nrepl_origins, since an origin can exist without ever becoming

A  minor tweak suggestion:
'This can be less than ..' to:
This count can be smaller than nrepl_origins because a replication
origin can exist without ever becoming active

7)
/*
 * get_subscription_info()
 *
 * Gets the information of subscriptions in the cluster.
 */

Originally this function was created to get number of subs and thus
was named as 'get_subscription_info'. I am not sure if this name is
still relevant. It is only getting 'retain_dead_tuples' info. Shall we
modify the comment at-least. Suggestion:

Determine whether any subscription has subretaindeadtuples enabled.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Shlok Kyal <shlok.kyal.oss@gmail.com>
Дата:
On Thu, 9 Jul 2026 at 17:07, Ajin Cherian  wrote:
>
> Attaching v11 with all comments addressed.
>

Thanks Ajin. I reviewed the patch. Here are some comment for it:

1. pg_dumpall.c
  dumpRoleGUCPrivs(conn);
+
  }

+ /* Dump replication origins */
+ if (!tablespaces_only && !roles_only && binary_upgrade)
+ dumpReplicationOrigins(conn);

The blank line below 'dumpRoleGUCPrivs(conn);' is not required

2. Maybe we can initialize the variables during declaration itself:
+ ReplOriginId roident;
+ const char *roname;
+
+ roident = atooid(PQgetvalue(res, i, i_roident));
+ roname = PQgetvalue(res, i, i_roname);

3. We should add a comment on top of this function. Just like other
dumpXXX functions
+static void
+dumpReplicationOrigins(PGconn *conn)

4. In check.c:
+ /*
+ * Compare against the number of active origins in the old cluster not the
+ * total number of origins in pg_replication_origin. An origin can exist

I think we can reword it like:
Compare against the number of active replication origins in the old
cluster, rather than the total number of origins in
pg_replication_origin.

5. In pg_upgrade_support.c:
+#include "utils/syscache.h"

We can remove this include.

Thanks,
Shlok Kyal


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Fri, Jul 10, 2026 at 6:28 PM Shlok Kyal  wrote:
>
>
> Thanks,
> Shlok Kyal

Thanks for all the comments. Here's an updated patch addressing these comments.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Thu, Jul 16, 2026 at 11:36 AM Ajin Cherian  wrote:
>
> On Fri, Jul 10, 2026 at 6:28 PM Shlok Kyal  wrote:
> >
> >
> > Thanks,
> > Shlok Kyal
>
> Thanks for all the comments. Here's an updated patch addressing these comments.
>

Thanks Ajin.  A few trivial comments:

1)
+      configured to a value greater than or equal to the number of active
+      replication origins present in the old cluster. The new cluster
must contain no replication origins.

Suggestion:
configured to a value greater than or equal to the number of tracked
replication origins present in the old cluster (reflected in
pg_replication_origin_status)

(active -->tracked, link to pg_replication_origin_status at the end)

2)
+ * restoring its remote_lsn.  Used by pg_upgrade to preserve replication
+ * origin IDs across the upgrade.

Shall we get rid of 'Used by pg_upgrade to pre..' as it is used by
other flow as well.

3)

+
+ if (remote_lsn != InvalidXLogRecPtr)
+ {
+ Assert(IsBinaryUpgrade);
+ replorigin_advance(roident, remote_lsn, InvalidXLogRecPtr,
+    false /* backward */,
+    false /* WAL log */);
+ }

We can instead add a comment atop Assert here (remove comment atop
function header as suggested in 2)

/*
 * The remote_lsn is expected to be valid only during binary upgrade when
 * preserving an existing replication origin. For the normal origin
 * creation flow, it should always be InvalidXLogRecPtr.
 */

4)

- * preserved during the upgrade. So, even after creating the slot, the
- * upgraded subscriber may be unable to detect conflicts or log relevant
- * commit timestamps and origins when applying changes from the publisher
- * occurred before the upgrade especially if those changes were not
- * replicated.
+ * upgrade. So, even after creating the slot, the upgraded subscriber may
+ * be unable to detect conflicts or log relevant commit timestamps when
+ * applying changes from the publisher occurred before the upgrade
+ * especially if those changes were not replicated.

I think, we should retain 'origins' in above comment as we still can
not log origin info post-upgrade until commit-timestamp is preserved.

5)
# ------------------------------------------------------
# Check that the data inserted to the publisher when the new subscriber is down
# will be replicated once it is started. Also check that the old subscription
# states and relations origins are all preserved, and that the conflict
# detection slot is created.
# ------------------------------------------------------

We can change this existing comment in test in accordance with new
origin-id presrevation test.

6)
# Verify that the subscription related replication origins are
preserved after upgrade.
# Verify that user created replication origins are preserved after upgrade.

Shall we say:
# Verify that subscription replication origins retain their origin IDs
after upgrade.
# Verify that the user-created replication origin retains its origin
ID after upgrade.

thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jul 22, 2026 at 11:24 AM Ajin Cherian  wrote:
>
> On Tue, Jul 21, 2026 at 9:04 PM Shlok Kyal  wrote:
> >
> > 2. I was testing the patch and found a difference of behaviour between
> > HEAD and with Patch.
> > Suppose we have two nodes, publisher and subscriber, and the
> > subscriber has two subscriptions. The replication origin states for
> > the respective subscriptions are:
> >  local_id | external_id | remote_lsn | local_lsn
> > ----------+-------------+------------+------------
> >         1 | pg_16393    | 0/00000000 | 0/0174F518
> >         2 | pg_16394    | 0/017516C0 | 0/0174FDA0
> > Now, we want to upgrade the subscriber node. On the
> > upgraded_subscriber node, max_logical_replication_workers is set to 0.
> >
> > With this patch, the replication origin states after the upgrade are:
> >  local_id | external_id | remote_lsn | local_lsn
> > ----------+-------------+------------+------------
> >         2 | pg_16394    | 0/017516C0 | 0/00000000
> > (1 row)
> >
> > Whereas on HEAD, the replication origin states after the upgrade are:
> >  local_id | external_id | remote_lsn | local_lsn
> > ----------+-------------+------------+------------
> >         1 | pg_16400    | 0/00000000 | 0/00000000
> >         2 | pg_16401    | 0/017516C0 | 0/00000000
> >
> > With this patch, I observed that replication origins whose remote_lsn
> > is '0/00000000' are not present on the upgraded node when
> > max_logical_replication_workers is set to 0.
> > Is this behaviour expected?
> >
>
> The reason for this difference in behaviour is that on head,
> replorigin_advance is called unconditionally even if remote_lsn = 0/0,
> which is even if the origin hasn't replayed anything (e.g.,
> subscription hasn't started replicating, or table sync hasn't
> progressed past the initial state). So, the origin has an entry in
> pg_replication_status. (Should it?)
> With the patch, although the replication origin is created, it is
> advanced at upgrade time only if it has a meaningful remote_lsn and
> otherwise it will eventually get updated when the apply worker starts
> up. But, in the test scenario, the apply worker never gets a chance to
> run because max_logical_replication_workers is set to 0. I think this
> behaviour is fine. But if maintaining consistency with previous
> versions is important, I also understand that.
> The particular code  that causes this difference is:
>
> + if (remote_lsn != InvalidXLogRecPtr)
> + {
> +  /*
> +   * The remote_lsn is expected to be valid only during binary upgrade when
> +   * preserving an existing replication origin. For the normal origin
> +   * creation flow, it should always be InvalidXLogRecPtr.
> +   */
> +  Assert(IsBinaryUpgrade);
> +
> +  replorigin_advance(roident, remote_lsn, InvalidXLogRecPtr,
> +         false /* backward */,
> +         false /* WAL log */);
> + }
>
> The code does not differentiate between a remote_lsn of 0/0 and the
> caller passing InvalidXLogRecPtr. I could revert to older behaviour by
> changing the if condition to if (IsBinaryUpgrade).
>
> Let me know what people think? Keep the existing behaviour or is the
> new behaviour fine?
>

I don't have a strong opinion on this.

The case we are trying to address is an extreme corner case (and, IMO,
rather impractical), so I am fine with leaving the behavior as is.
Changing the check would also work. But the only downside if at all in
the future, someone else uses replorigin_create_with_id() and also
wants to set remote_lsn, we may need to keep adding more conditions,
since checking only IsBinaryUpgrade may not be sufficient.  The
current condition is more generic and seems cleaner to me.


thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Hi Ajin,

One more thing for the remote_lsn = 0/0 question Shlok raised: whichever way it
is settled, the new max_active_replication_origins check should follow it,
because right now the two disagree.

The check counts status rows on the old cluster -- get_replication_origin_info()
fills nrepl_origins_active from

    SELECT count(*) FROM pg_catalog.pg_replication_origin_status

and check_new_cluster_replication_origins() compares that against the setting:

    if (old_cluster.nrepl_origins_active > max_active_replication_origins)

The rationale for counting tracked origins rather than all of them was that this
is what decides whether the new server comes up ("Setting it to a lower value
than the current number of tracked replication origins ... will prevent the
server from starting"). But restore does not reproduce that set on the new
cluster. An origin sitting at 0/0 has a status row on the old cluster and is
counted, while replorigin_create_with_id() skips the advance for it, since
0/0 is InvalidXLogRecPtr:

    if (remote_lsn != InvalidXLogRecPtr)
        replorigin_advance(...);

so it ends up untracked on the new cluster and counts for nothing there. The
check is therefore comparing the setting against a larger set than the one the
new server will actually have to start with.

Two user origins, one advanced and one left at 0/0:

    SELECT pg_replication_origin_create('uo_advanced');
    SELECT pg_replication_origin_advance('uo_advanced', '0/12345678');
    SELECT pg_replication_origin_create('uo_zero');
    SELECT pg_replication_origin_advance('uo_zero', '0/0');
    -- 2 status rows

New cluster with max_active_replication_origins = 1:

    "max_active_replication_origins" (1) must be greater than or equal to the
    number of active replication origins (2) in the old cluster

-- refused, though 1 is in fact enough. Run it through with a higher setting and
the new cluster ends up with a single status row (uo_advanced); uo_zero is there
in pg_replication_origin with its roident preserved, but untracked. Dropping
uo_zero on the old cluster and re-running with the same setting of 1 passes,
which is what pins it on the 0/0 origin.

So if the skip stays as it is, the count should follow it -- counting only
status rows whose remote_lsn is non-zero. If instead it goes back to advancing
unconditionally, the two line up on their own and the check needs no change.
Either is fine by me; it's the pair being out of step that seemed worth
mentioning while that behaviour is still being decided.

Minor, unrelated: the doc note was updated to "Commit timestamps are not
preserved during the upgrade", but the twin comment in pg_upgrade.c still reads

    * upgrade. Additionally, commit timestamps and origin data are not
    * preserved during the upgrade. ...

which is no longer true now that this patch preserves origins -- same
edit as the
.sgml. (I mentioned this on v10; just flagging it's still there.)

Thanks,
Rui


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Rui Zhao <zhaorui126@gmail.com>
Дата:
Вложения:
Hi Ajin,

v15 applies to master (eb983d0a94), builds warning-free, make check 245/245,
pg_upgrade TAP 148/148.  I also ran a real pg_upgrade with one origin in each
of the three states -- never advanced, advanced to 0/0, advanced to a real
LSN -- and all three keep their tracking state:

    origin           old cluster   new cluster
    o_never          untracked     untracked
    o_tracked_zero   0/00000000    0/00000000
    o_tracked_real   0/12345678    0/12345678

A test gap, a doc paragraph the pre-17 change left behind, and three small
things.

1. 004_subscription.pl covers the first and third rows -- regress_user_origin
is never advanced, the subscription origins have a non-zero remote_lsn -- but
not the second, and the second is the only row where !PG_ARGISNULL(2) gets it
right and a plain remote_lsn check would get it wrong.  The suite cannot tell
the two apart: with !XLogRecPtrIsInvalid(remote_lsn) swapped in as a
deliberately wrong version, the file still passes 24/24, and the same upgrade
as above becomes

    o_tracked_zero   0/00000000    untracked

Attached adds an origin advanced to 0/0 next to the never-advanced one -- two
statements and one assertion.  It passes on v15 as posted (25/25), and under
the substitution the one failure is

    Failed test 'origin 'regress_zero_origin' advanced to 0/0 is still tracked
    after upgrade'

2. Since v8, per the discussion upthread, origins migrate from pre-17 old
clusters too.  I tested that on a real upgrade -- a PG16 old cluster
with one subscription (connect = false) and one user origin, upgraded to
master+v15:

    roident  roname          old (PG16)   new cluster
    1        pg_16384        untracked    untracked
    2        user_origin_16  0/12345678   0/12345678

with pg_subscription.oid preserved as well.  But "Prepare for Subscriber
Upgrades" in logical-replication.sgml still says:

    pg_upgrade attempts to migrate subscription dependencies which includes
    the subscription's table information present in pg_subscription_rel
    system catalog and also the subscription's replication origin. [...]
    Migration of subscription dependencies is only supported when the old
    cluster is version 17.0 or later. Subscription dependencies on clusters
    before version 17.0 will silently be ignored.

The origin half of that is no longer true.  The origin should come out of
the "17.0 or later" claim: origins and their remote_lsn now migrate from any
old version, while the pg_subscription_rel state still does not.

3. Small things:

- Nothing reads the origin_status join in getSubscriptions() any more --
  suboriginremotelsn was its last consumer.  The block at pg_dump.c:5248-5251
  can go:

      "LEFT JOIN pg_catalog.pg_replication_origin_status o \n"
      "    ON o.external_id = 'pg_' || s.oid::text \n"

- origin.c:308, in the new comment: "We cannot distinglish only by the
  remote_lsn" -> distinguish.

- pg_dumpall.c:1841 has a trailing space after "Origins" that the other
  headers in the file don't:

      fprintf(OPF, "--\n-- Replication Origins \n--\n\n");

Regards,
Rui

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Fri, Aug 21, 2026 at 10:19 AM Ajin Cherian  wrote:
>
> On Wed, Aug 19, 2026 at 7:52 PM shveta malik  wrote:
> >
> > On Wed, Aug 19, 2026 at 11:13 AM Ajin Cherian  wrote:
> > >
> > >
> > > I have incorporated your comments and your changes in a new patch v16.
> > >
> >
> > Please find a few minor comments:
> >
>
> I've addressed all the comments except the below one.
>
> >
> > 4)
> >
> > +    old subscriber was up to. Migration of the subscription's replication
> > +    origin is supported for all cluster versions.
> >
> > Shall we say:
> > all supported cluster versions
>
> It is stating the obvious saying that it is supported for all
> supported cluster versions, so I didn't change this.
>

Okay. Thanks Ajin.


I have one trivial concern to discuss. We document this:

---
The new cluster must have max_active_replication_origins configured to
a value greater than or equal to the number of tracked replication
origins present in the old cluster (reflected in
pg_replication_origin_status). Furthermore, the new cluster must not
contain any pre-existing replication origins.
---

But we check for pre-existing origins in the new cluster only if the
old cluster has any origins. So, the second check is effectively
conditional. This is probably not harmful; if the old cluster has no
origins, there is nothing to migrate, so we don't really need to worry
about the origin count.
count on the new cluster. But the doc and code are not quite in sync:

check_new_cluster_replication_origins:
+ if (old_cluster.nrepl_origins == 0)
  return;

I noticed a similar inconsistency with replication slots, we mention
this in doc [1]: 'The new cluster must not have any permanent logical
slots',

But the code also conditionally skips the check:
         /*
         * Quick return if there are no slots to be migrated and no
subscriptions
         * have the retain_dead_tuples option enabled.
         */
        if (nslots_on_old == 0 && !old_cluster.sub_retain_dead_tuples)
                return;

So, is the current behavior okay, or should we:

a) Check for pre-existing origins on the new cluster regardless of the
old cluster's origin count?
b) Or update the doc to make it consistent with code, at-least for our
origin case?
c) Leave things as they are?

[1]: https://www.postgresql.org/docs/current/logical-replication-upgrade.html


thanks
Shveta


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Thu, Aug 27, 2026 at 3:55 PM Rui Zhao  wrote:
>
> Hi Ajin,
>
> v17 applies to master (db2d99323f), builds warning-free, make check 245/245,
> pg_upgrade TAP 149/149.  The two upgrades from my last mail still pass, and
> all three points from it are in.
>
> On the commit message: it says commit-timestamp records "are copied
> directly from the old cluster's pg_commit_ts directory", but the copying is
> still the pg_commit_ts migration thread's patch -- so "will be copied"
> would be the accurate tense.
>
> Typo in the comment that replaced the "distinglish" one, at origin.c:309:
> "a status row that exists with remote_ls = 0/0" -> remote_lsn.
>
> Everything else looks good to me.

Addressed these comments and also rebased the patch.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Nisha Moond <nisha.moond412@gmail.com>
Дата:
On Mon, Sep 28, 2026 at 5:51 PM Ajin Cherian  wrote:
>
> Addressed these comments and also rebased the patch.
>

Hi Ajin,

I reviewed and tested v18. Please find my comments below:

1) When upgrading from PG16 or older, a subscription can end up
without its replication origin after the upgrade.

In binary-upgrade mode, CreateSubscription() now skips
replorigin_create(), relying on pg_dumpall to restore the origin. That
only works if the origin exists on the old cluster. For PG17+ sources,
check_old_cluster_subscription_state() rejects subscriptions without
an origin, but that check isn't done for older versions. So if the
subscription's origin was dropped on a PG16 cluster (rare, since it
requires a manual pg_replication_origin_drop()), nothing creates it
during the upgrade.

Reproduced with a PG16 old cluster (subscription created with connect
= false, then its origin dropped):

 HEAD + v18:
   new cluster: subscription oid 16384, origins: []
   ALTER SUBSCRIPTION regress_sub SKIP (lsn = '0/1000000');
   ERROR:  replication origin "pg_16384" does not exist

 HEAD:
   new cluster: subscription oid 16400, origins: [1:pg_16400]
   ALTER SUBSCRIPTION regress_sub SKIP (lsn = '0/1000000');
   ALTER SUBSCRIPTION
 -- on head, CreateSubscription() simply creats a new origin.

The apply worker creates the missing origin once the subscription is
enabled, so this is temporary, but until then commands that need the
origin fail. I think this is a leftover of the case Shlok reported in
[1], which was fixed by dumping origins for all source versions [3].
That fix doesn't cover an origin that's already missing on the old
cluster.

Since dropping a subscription's origin is rare, a simple fix might be
enough: in binary-upgrade mode, create the origin only if it doesn't
already exist, e.g.

- if (!IsBinaryUpgrade)
- {
- ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
sizeof(originname));
+ ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname,
sizeof(originname));
+ if (!IsBinaryUpgrade || !OidIsValid(replorigin_by_name(originname, true)))
  replorigin_create(originname);
- }

Thoughts?
~~~

Tests: 004_subscription.pl:

2) The subscription roident check passes on HEAD, i.e. without the
patch, so it cannot catch a regression:

+my %all_subnames = (%pre_upgrade_roident, %post_upgrade_roident);
+for my $subname (sort keys %all_subnames)
+{
+     next if $subname eq $user_origin_name;
+     is($post_upgrade_roident{$subname}, $pre_upgrade_roident{$subname},
+             "roident preserved for subscription '$subname' after upgrade");
+}

Result on HEAD with the v18 test applied (regress_log_004_subscription snippet):

[15:01:58.310](0.157s) not ok 14 - subscription oid should have been preserved
[15:01:58.310](0.000s)
[15:01:58.310](0.000s) #   Failed test 'subscription oid should have
been preserved'
#   at t/004_subscription.pl line 416.
[15:01:58.310](0.000s) #          got: '16400
# 16401'
#     expected: '16402
# 16406'
[15:01:58.321](0.012s) ok 15 - check that the subscription's running
status, failover, and retain_dead_tuples are preserved
[15:01:58.334](0.012s) ok 16 - roident preserved for subscription
'regress_sub4' after upgrade
[15:01:58.334](0.000s) ok 17 - roident preserved for subscription
'regress_sub5' after upgrade
[15:01:58.345](0.011s) not ok 18 - roident preserved for user-created
origin 'regress_user_origin' after upgrade
[15:01:58.345](0.000s)
[15:01:58.345](0.000s) #   Failed test 'roident preserved for
user-created origin 'regress_user_origin' after upgrade'
#   at t/004_subscription.pl line 461.
[15:01:58.345](0.000s) #          got: ''
#     expected: '3'
```

The subscription OIDs did change (test 14), yet the roidents still
compare equal. Origins get the lowest free ID, and by this point every
earlier subscription and its origin has been dropped. So the old
cluster ends up with IDs:
 regress_sub4 = 1
 regress_sub5 = 2
 regress_user_origin = 3
 regress_zero_origin = 4
Without the patch, the new cluster recreates the subscription origins
in dump order (sub4, then sub5) and gets 1 and 2 again. Only tests 18
and 20 catch a full revert, because the user-created origins are not
migrated at all on HEAD. A partial breakage would pass every check:
for example, origins restored but given fresh IDs instead of the old
roident.

How about leaving a gap, so that a fresh assignment gives different
numbers? Something like:

# before CREATE SUBSCRIPTION regress_sub4
$old_sub->safe_psql('postgres',
      "SELECT pg_replication_origin_create('regress_filler')");
...
# after all origins are created, i.e. after regress_zero_origin
$old_sub->safe_psql('postgres',
      "SELECT pg_replication_origin_drop('regress_filler')");

The old cluster then has sub4 = 2, sub5 = 3. Any fresh assignment
gives 1, 2 so the check can actually fail.

3) Similarly, this check passes on HEAD, but only because the origin
does not exist at all:

+is($result, qq(0),
+     "never-advanced origin '$user_origin_name' is still untracked after upgrad
+);
ok 19 - never-advanced origin 'regress_user_origin' is still untracked
after upgrade

The join to pg_replication_origin by name returns 0 rows whether the
origin is untracked or missing. It would be better to check that the
origin exists and has no status row, e.g. a LEFT JOIN from
pg_replication_origin that expects one row with a NULL local_id.
~~~

4) Almost all files need pgindent to be run.

5) v18-0001 does not compile cleanly on its own:

subscriptioncmds.c:95:7: warning: no previous extern declaration for
non-static variable 'binary_upgrade_next_pg_subscription_oid'
[-Wmissing-variable-declarations]
   95 | Oid
binary_upgrade_next_pg_subscription_oid = InvalidOid;
      |

The #include "catalog/binary_upgrade.h" in subscriptioncmds.c is added
in 0002; it should be moved into 0001.

[1] https://www.postgresql.org/message-id/CANhcyEVFSutXXdt_0XMCD37NE7Yd7ROdDVEE06D8YVyPNEBFHg%40mail.gmail.com
[3] https://www.postgresql.org/message-id/CAA4eK1KzGSANd%3Dg1S8xpcyiwh3M-c%2BUaa4%2B447v-%2BN8chX7K3g%40mail.gmail.com

--
Thanks,
Nisha


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Thu, Oct 8, 2026 at 12:26 AM Nisha Moond  wrote:
>
> On Mon, Sep 28, 2026 at 5:51 PM Ajin Cherian  wrote:
> >
> > Addressed these comments and also rebased the patch.
> >
>
> Hi Ajin,
>
> I reviewed and tested v18. Please find my comments below:
>

Hi Nisha,

Thanks for your comments, I agree with all your comments and have
addressed them in v19.

regards,
Ajin Cherian
Fujitsu Australia

RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi Ajin,

> Thanks for your comments, I agree with all your comments and have
> addressed them in v19.

Thanks for updating the patch. I requested my LLM to review your patch set,
It found a possible issue, when the source is PG16-.. Do you think it should
be fixed?

If the source node is PG16-, the apply worker can start even during the pg_upgrade
command. So, it may be possible that the replication origin can be go backward with
the below steps:
 
1. the pg_dumpall command reads the remote_lsn from the old source. the value is
   LSN_1.
2. the apply worker on the old source receives and applies changes.
3. the worker also updates the replication origin. The value is LSN_2.
4. then the source is stopped and heap is copied by the pg_upgrade command.
   The data is replicated till LSN_2, but the remote_lsn would be LSN_1.
5. the apply worker requests replicating data from LSN_1.

It's not problematic if the confirmed_flush has already been updated to LSN_2 on
publisher side, the publisher ignores the requested startpoint (LSN_1) and starts
for LSN_2. remote_lsn can be eventually corrected.
If not replicated yet, the publisher may send the same data thus can cause the
data duplication error. But IIUC it seems possible even for HEAD. The apply worker
does not request the specific startpoint (i.e., 0/0), and the walsender replicates
after the confirmed_flush.

To the end, the outcome is mostly the same, but origin may show the wrong value
for a while.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Thu, Oct 15, 2026 at 4:26 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi Ajin,
>
> 1. the pg_dumpall command reads the remote_lsn from the old source. the value is
>    LSN_1.
> 2. the apply worker on the old source receives and applies changes.
> 3. the worker also updates the replication origin. The value is LSN_2.
> 4. then the source is stopped and heap is copied by the pg_upgrade command.
>    The data is replicated till LSN_2, but the remote_lsn would be LSN_1.
> 5. the apply worker requests replicating data from LSN_1.
>
> It's not problematic if the confirmed_flush has already been updated to LSN_2 on
> publisher side, the publisher ignores the requested startpoint (LSN_1) and starts
> for LSN_2. remote_lsn can be eventually corrected.
> If not replicated yet, the publisher may send the same data thus can cause the
> data duplication error. But IIUC it seems possible even for HEAD. The apply worker
> does not request the specific startpoint (i.e., 0/0), and the walsender replicates
> after the confirmed_flush.

Hi Kuroda-san,

Thanks for the review.

You’re right that for a PG16-or-older source the apply worker can run
during pg_upgrade, so the dumped remote_lsn (LSN_1) can be behind what
has actually been applied (LSN_2). But I don’t think the patch changes
the outcome compared with HEAD.

When the worker starts on the new cluster, the walsender never streams
from earlier than the slot’s confirmed_flush. With the patch,
replication therefore starts from max(LSN_1, confirmed_flush). On HEAD
the origin is recreated with no remote_lsn for pre-17 sources, so
replication starts from confirmed_flush. The patch’s start point is
never earlier than HEAD’s, so whatever the patch might re-send is a
subset of what HEAD would re-send. Duplicates are possible in both
cases when confirmed_flush lags behind the changes already applied on
the old subscriber; the patch doesn’t introduce them. I checked this
with a script that runs pg_upgrade from a PG16 subscriber while the
publisher is under load. In both cases the new subscriber hit an
insert_exists conflict. With the patch, the first re-applied row was
198, because replication resumed at LSN_1. On HEAD it was row 144,
because replication resumed from the older confirmed_flush. As you
say, the only visible difference is that the origin can show LSN_1 for
a while before the worker advances it again. Pre-17 subscribers are
also restored disabled and without their pg_subscription_rel entries,
so replication doesn’t resume automatically anyway. HEAD’s docs
already say subscription dependencies are not migrated for clusters
before 17.0. One problem with the current patch is the docs:
“Migration of the subscription’s replication origin is supported for
all cluster versions”, right after “continue from where the old
subscriber was up to”, suggests that a pre-17 subscriber also resumes
from the correct position.

So I think a documentation fix is enough here. The attached v20
changes that paragraph to:

... When the old cluster is version 17.0 or later, this allows logical
replication on the new subscriber to continue from where the old
subscriber was up to. Replication origins, including their IDs, are
migrated for all cluster versions. However, for clusters before
version 17.0, the subscription's table information is not migrated and
subscriptions are restored in a disabled state, so replication does
not resume automatically after the upgrade....

There are no code changes from v19.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
Hi all,

Adding some more documentation changes based on Claude code review:

0001:

Reworded the commit message so it no longer describes 0002’s behaviour
as already existing. It now also mentions that tablesync origins
(pg__) depend on the preserved subscription OID.

0002:

Commit message:

The motivation was inconsistent: it said pg_commit_ts is copied during
upgrade, while the patch’s own docs say commit timestamps are not
preserved. It is now framed as a prerequisite for preserving
pg_commit_ts.
Notes that origins not owned by a subscription (e.g. created by
external tools) were previously lost.
Notes that binary_upgrade_replorigin_advance() is removed.
Lists the user-visible changes: origins are now migrated from pre-17
clusters too, so their subscriptions resume from the migrated
remote_lsn once enabled; the new cluster must have no origins; and the
max_active_replication_origins check now counts tracked origins rather
than subscriptions.

Docs:

Origin migration is now described as applying to old clusters 9.5 or
later, rather than “all cluster versions”.
Documented that a subscription from a pre-17 cluster resumes from its
migrated origin position when enabled.
Clarified what “tracked” means in the max_active_replication_origins
prerequisite.

Comments:

Moved the explanation of NULL vs 0/0 remote_lsn from
replorigin_create_with_id() to
binary_upgrade_create_replication_origin(), where the distinction is
made.
Rewrote the header comment of replorigin_create_with_id() to describe
its contract.
Added a header comment for dumpReplicationOrigins().
Added pg_replication_origin.roident to the list of preserved OIDs at
the top of pg_upgrade.c.
Minor wording fixes in info.c and the TAP test.

regards,
Ajin Cherian
Fujitsu Australia

RE: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Hi,

While discussing internally we found a corner case when the source is PG16-.
To avoid the case, I want to propose that pg_upgrade can reject the code while the
tablesync is on-going, even for PG16- node.

Found issue
========
Assuming that source server is PG16-, it has subscriptions and tablesync is on-going.
In this case replication origins created by tablesync workers also exist. If the
pg_upgrade is done at that timing, these replication origins would be additionally
migrated to the new node.
E.g., if source node has 1 subscription and 2 tables are synchronizing, three
origins will be migrated to the new node.

This replication origin cannot be dropped automatically even if users run
DROP SUBSCRIPTION [1] and ALTER SUBSCRIPTION REFRESH PUBLICATION WITH (copy_data = off).
For DROP command, origins for tablesync can be dropped when the corresponding
table is listed in the pg_subscription_rel, but entries cannot be migrated from PG16- node.
Users must run ALTER SUBSCRIPTION REFRESH PUBLICATION WITH (copy_data = on),
or drop the origin manually. First one invokes whole copy of the table and second
one can be easily forgotten.

Proposed fix
=======
Origins for tablesync workers can exist only while the synchronization is on-going,
so my idea is does not allow upgrading during the synchronization. For now,
the check function check_old_cluster_subscription_state() ensures all sync are done,
but it's called when the source is PG17+, which supports migrating the pg_subscription_rel.
I think we can do for the same all cases.

Note
====
check_old_cluster_subscription_state() also ensures that all subscriptions have
the respective replication origins. For now upgrading PG16- node can be done 
even if subscriptions do not have origins, but such a case would be additionally
rejected after the fix.
I felt it's harmless because there are no benefits for origin-missing subscriptions,
but please post here if you have any doubts.

How do you feel?

[1]
```
postgres=# SELECT * FROM pg_replication_origin;
 roident |     roname     
---------+----------------
       1 | pg_16389		// origin for subscription
       2 | pg_16389_16384	// origin for table synchronization
(2 rows)

postgres=# DROP SUBSCRIPTION regress_sub ;
NOTICE:  dropped replication slot "regress_sub" on publisher
DROP SUBSCRIPTION
postgres=# SELECT * FROM pg_replication_origin;
 roident |     roname     
---------+----------------
       2 | pg_16389_16384
(1 row)
```

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Fri, Oct 30, 2026 at 2:46 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi,
>
> While discussing internally we found a corner case when the source is PG16-.
> To avoid the case, I want to propose that pg_upgrade can reject the code while the
> tablesync is on-going, even for PG16- node.
>
> Found issue
> ========
> Assuming that source server is PG16-, it has subscriptions and tablesync is on-going.
> In this case replication origins created by tablesync workers also exist. If the
> pg_upgrade is done at that timing, these replication origins would be additionally
> migrated to the new node.
> E.g., if source node has 1 subscription and 2 tables are synchronizing, three
> origins will be migrated to the new node.
>
> This replication origin cannot be dropped automatically even if users run
> DROP SUBSCRIPTION [1] and ALTER SUBSCRIPTION REFRESH PUBLICATION WITH (copy_data = off).
> For DROP command, origins for tablesync can be dropped when the corresponding
> table is listed in the pg_subscription_rel, but entries cannot be migrated from PG16- node.
> Users must run ALTER SUBSCRIPTION REFRESH PUBLICATION WITH (copy_data = on),
> or drop the origin manually. First one invokes whole copy of the table and second
> one can be easily forgotten.

Thanks for the detailed explanation.

> Proposed fix
> =======
> Origins for tablesync workers can exist only while the synchronization is on-going,
> so my idea is does not allow upgrading during the synchronization. For now,
> the check function check_old_cluster_subscription_state() ensures all sync are done,
> but it's called when the source is PG17+, which supports migrating the pg_subscription_rel.
> I think we can do for the same all cases.
>
> Note
> ====
> check_old_cluster_subscription_state() also ensures that all subscriptions have
> the respective replication origins. For now upgrading PG16- node can be done
> even if subscriptions do not have origins, but such a case would be additionally
> rejected after the fix.
> I felt it's harmless because there are no benefits for origin-missing subscriptions,
> but please post here if you have any doubts.

I have the same understanding. I agree with the proposed solution.

> How do you feel?
>
> [1]
> ```
> postgres=# SELECT * FROM pg_replication_origin;
>  roident |     roname
> ---------+----------------
>        1 | pg_16389             // origin for subscription
>        2 | pg_16389_16384       // origin for table synchronization
> (2 rows)
>
> postgres=# DROP SUBSCRIPTION regress_sub ;
> NOTICE:  dropped replication slot "regress_sub" on publisher
> DROP SUBSCRIPTION
> postgres=# SELECT * FROM pg_replication_origin;
>  roident |     roname
> ---------+----------------
>        2 | pg_16389_16384
> (1 row)
> ```
>
> Best regards,
> Hayato Kuroda
> FUJITSU LIMITED
>


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Fri, Oct 30, 2026 at 8:16 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi,

> Proposed fix
> =======
> Origins for tablesync workers can exist only while the synchronization is on-going,
> so my idea is does not allow upgrading during the synchronization. For now,
> the check function check_old_cluster_subscription_state() ensures all sync are done,
> but it's called when the source is PG17+, which supports migrating the pg_subscription_rel.
> I think we can do for the same all cases.
>
> Note
> ====
> check_old_cluster_subscription_state() also ensures that all subscriptions have
> the respective replication origins. For now upgrading PG16- node can be done
> even if subscriptions do not have origins, but such a case would be additionally
> rejected after the fix.
> I felt it's harmless because there are no benefits for origin-missing subscriptions,
> but please post here if you have any doubts.
>
> How do you feel?
>

Hi Kuroda-san,

+1. I’ve done this in the attached v22:
check_old_cluster_subscription_state() now runs for all supported old
cluster versions, not only 17 and later.

I tested an upgrade from a PG10 subscriber to HEAD. pg_upgrade now
rejects both a relation in ‘d’ state and a subscription with a missing
origin. A clean upgrade preserves all origin IDs and remote_lsn
values. I also agree that rejecting origin-less subscriptions is
harmless, so the fallback in CreateSubscription() that created a
missing origin is removed, since it can no longer be reached.

Regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Tue, Nov 3, 2026 at 3:25 PM Ajin Cherian  wrote:
>
> +1. I’ve done this in the attached v22:

The patch required a rebase. Rebased v23 is attached.

regards,
Ajin Cherian
Fujitsu Australia

Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Zsolt Parragi <zsolt.parragi@percona.com>
Дата:
Hello

I think the old cluster issue still exists eveen with v22/23, as
pointed out by claude:

Set up a PG15 subscriber with an enabled subscription, with its table
in state i at clean shutdown, 50 extra databases (to make the check
phase longer), and pre_auth_delay=1 on the publisher to simulate a
slow connection.

And then pg_upgrade from v23:

Checking subscription state                                   ok
...
-- pg_upgrade_dump_globals.sql:
SELECT pg_catalog.binary_upgrade_create_replication_origin('2'::pg_catalog.oid,
'pg_16391_16384'::pg_catalog.text, '0/40466F8'::pg_catalog.pg_lsn);

-- new cluster, after DROP SUBSCRIPTION s:
 2 | pg_16391_16384

With the default timing the opposite happens: the tablesync starts
before the check, and pg_upgrade fails with 'The table sync state "d"
is not allowed', even though the table was in state i when the cluster
was stopped. The TAP test doesn't see either case because it sets
max_logical_replication_workers = 0 on the old subscriber.


Re: [PATCH] Preserve replication origin OIDs in pg_upgrade

От:
Ajin Cherian <itsajin@gmail.com>
Дата:
Вложения:
On Tue, Nov 17, 2026 at 6:36 AM Zsolt Parragi  wrote:
>
> Hello
>
> I think the old cluster issue still exists eveen with v22/23, as
> pointed out by claude:
>
> Set up a PG15 subscriber with an enabled subscription, with its table
> in state i at clean shutdown, 50 extra databases (to make the check
> phase longer), and pre_auth_delay=1 on the publisher to simulate a
> slow connection.
>

Thanks, I’ve reproduced both cases with a PG15 subscriber.

The cause is that pg_upgrade starts the old cluster with -b, which
only disables the logical replication launcher from PG17 onward. On
older clusters, tablesync workers run while pg_upgrade is checking and
dumping.

v24 (attached) starts pre-17 old clusters with -c
max_logical_replication_workers=0. With that, neither case reproduces
from PG10 or PG15.

Regards,
Ajin Cherian
Fujitsu Australia
FAQ