sequencesync worker race with REFRESH SEQUENCES

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

sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
Вложения:
A Fable 5 review of logical replication of sequences found a way to get
subscribed sequences into READY state despite the subscriber side having data
older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
I reviewed the test, and I think it identifies a genuine defect.

Fable 5 also wrote a lot more that neither it nor I confirmed by test case
construction.  I'm attaching the report; feel free to disregard.  Finding-2
about default_transaction_read_only=on looks worth fixing if true, as do
finding-7 assert failure and finding-17 about documenting a PG19+ publisher
requirement.  Finding-6, publisher version guard, I'd NOT do or do at warning
level if an older publisher could plausibly work via an extension to provide
the needed function.  The other findings are gray areas, perhaps.

RE: sequencesync worker race with REFRESH SEQUENCES

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

Agree the basic approach that we avoid the re-initializing the catalog.
My primitive idea is to follow what slotsync does. SlotSyncCtxStruct::syncing is
checked from the SQL function and the slotsync worker, and either of them can
continue. So we may be able to have LogicalRepCtxStruct::synching_seqs or
something to indicate the status.
But there might be other ways, needs to be investigated.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Fri, Jul 10, 2026 at 12:30 PM vignesh C  wrote:
>
> On Fri, 10 Jul 2026 at 10:22, Noah Misch  wrote:
> >
> > A Fable 5 review of logical replication of sequences found a way to get
> > subscribed sequences into READY state despite the subscriber side having data
> > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > I reviewed the test, and I think it identifies a genuine defect.
>
> Thanks for reporting this. The test case reproduces this issue. This
> issue is not limited to lock contention. It can also occur if the
> sequence synchronization worker is simply slow. For example, the
> worker may fetch the sequence value from the publisher, after which
> the publisher sequence advances and ALTER SUBSCRIPTION ... REFRESH
> SEQUENCES is executed. When the worker eventually updates the
> subscriber, it uses the stale value that it fetched earlier,
> overwriting the sequence with an out-of-date value.

I have the same opinion here.

> How about raising a warning for the second REFRESH SEQUENCES
> indicating that the sequence is already being synchronized and
> skipping it? The warning could also include a hint to rerun ALTER
> SUBSCRIPTION ... REFRESH SEQUENCES after the current synchronization
> completes.

I agree. This is the simplest solution here.

~~

> Agree the basic approach that we avoid the re-initializing the catalog.
> My primitive idea is to follow what slotsync does. SlotSyncCtxStruct::syncing is
> checked from the SQL function and the slotsync worker, and either of them can
> continue. So we may be able to have LogicalRepCtxStruct::synching_seqs or
> something to indicate the status.
> But there might be other ways, needs to be investigated.

If this approach is accepted, I would prefer implementing it similarly
to how ALTER SUBSCRIPTION ... SET (two_phase) is handled. The command
simply fails (with an appropriate hint) if the apply worker for the
subscription is still running, by checking for the presence of the
apply worker.
IMO, a mechanism similar to SlotSync is not needed here because there
is currently no scenario in which continuous incremental
synchronization and one-time manual synchronization can run
concurrently. The worker itself is started only by the manual
synchronization operation and is not a continuously running process.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Fri, 10 Jul 2026 at 14:10, shveta malik  wrote:
>
> On Fri, Jul 10, 2026 at 12:30 PM vignesh C  wrote:
> >
> > On Fri, 10 Jul 2026 at 10:22, Noah Misch  wrote:
> > >
> > > A Fable 5 review of logical replication of sequences found a way to get
> > > subscribed sequences into READY state despite the subscriber side having data
> > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > I reviewed the test, and I think it identifies a genuine defect.
> >
> > Thanks for reporting this. The test case reproduces this issue. This
> > issue is not limited to lock contention. It can also occur if the
> > sequence synchronization worker is simply slow. For example, the
> > worker may fetch the sequence value from the publisher, after which
> > the publisher sequence advances and ALTER SUBSCRIPTION ... REFRESH
> > SEQUENCES is executed. When the worker eventually updates the
> > subscriber, it uses the stale value that it fetched earlier,
> > overwriting the sequence with an out-of-date value.
>
> I have the same opinion here.
>
> > How about raising a warning for the second REFRESH SEQUENCES
> > indicating that the sequence is already being synchronized and
> > skipping it? The warning could also include a hint to rerun ALTER
> > SUBSCRIPTION ... REFRESH SEQUENCES after the current synchronization
> > completes.
>
> I agree. This is the simplest solution here.

The attached v1-0001 patch avoids resetting the synchronization state
of sequences that are already being synchronized. Instead, it emits a
warning informing the user that the sequence is already being
synchronized and suggests rerunning ALTER SUBSCRIPTION ... REFRESH
SEQUENCES after the current synchronization completes. I'm not sure
whether a  test is necessary for this change. Nevertheless, the
attached v1-0002 patch adds a regression test that uses an injection
point to deterministically reproduce the race condition and verifies
that the expected warning is emitted when ALTER SUBSCRIPTION ...
REFRESH SEQUENCES is invoked while a sequence synchronization is
already in progress.

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
>
> A Fable 5 review of logical replication of sequences found a way to get
> subscribed sequences into READY state despite the subscriber side having data
> older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> I reviewed the test, and I think it identifies a genuine defect.
>

Good catch. We have following ways to fix: (a) As mentioned by
Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
sequencesync worker is in progress, we can either make the command
wait till the sequencesync is finished, return ERROR suggesting
sequence sync already in-progress, or first stop the sequencesync
worker and then complete the command and let the worker restart after
REFRESH command is finished; (b) raise a WARNING+HINT for sequences
that are not in ready state as proposed by Vignesh. Shall we
additionally add a Note for user to ensure seuencesync worker is not
in-progress before REFRESH SEQUENCES command?

Do you have any preference? I think WARNING+HINT should be sufficient
for users as this shouldn't be a common scenario but going the other
way is also fine.

--
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
On Sat, Jul 11, 2026 at 10:31:06AM +0530, Amit Kapila wrote:
> On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > A Fable 5 review of logical replication of sequences found a way to get
> > subscribed sequences into READY state despite the subscriber side having data
> > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > I reviewed the test, and I think it identifies a genuine defect.
> 
> Good catch. We have following ways to fix: (a) As mentioned by
> Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> sequencesync worker is in progress, we can either make the command
> wait till the sequencesync is finished, return ERROR suggesting
> sequence sync already in-progress, or first stop the sequencesync
> worker and then complete the command and let the worker restart after
> REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> that are not in ready state as proposed by Vignesh. Shall we
> additionally add a Note for user to ensure seuencesync worker is not
> in-progress before REFRESH SEQUENCES command?
> 
> Do you have any preference? I think WARNING+HINT should be sufficient
> for users as this shouldn't be a common scenario but going the other
> way is also fine.

I haven't formed a preference, but I would use these principles to decide.
Assume we eventually support continuous, WAL-decoded replication of sequences,
not just snapshot replication.  Which choice would make sequence replication
behave most like table replication under the analogous concurrent actions?

If it's an ERROR, I'd probably omit the doc note, since the ERROR would be
clear and unsurprising.  In general, there's no need to document everything
that causes an error.  Documentation is most useful when an error is
surprising or affects how the user writes the application.

If the command merely raises a WARNING, documentation becomes more important,
because warnings are easy to overlook.  That is also an argument against a
WARNING: if the user must take action to avoid incorrect replicated state, it
is risky to rely on the user noticing one.

Does that help?


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Sun, Jul 12, 2026 at 1:44 AM Noah Misch  wrote:
>
> On Sat, Jul 11, 2026 at 10:31:06AM +0530, Amit Kapila wrote:
> > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > > A Fable 5 review of logical replication of sequences found a way to get
> > > subscribed sequences into READY state despite the subscriber side having data
> > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > I reviewed the test, and I think it identifies a genuine defect.
> >
> > Good catch. We have following ways to fix: (a) As mentioned by
> > Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> > sequencesync worker is in progress, we can either make the command
> > wait till the sequencesync is finished, return ERROR suggesting
> > sequence sync already in-progress, or first stop the sequencesync
> > worker and then complete the command and let the worker restart after
> > REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> > that are not in ready state as proposed by Vignesh. Shall we
> > additionally add a Note for user to ensure seuencesync worker is not
> > in-progress before REFRESH SEQUENCES command?
> >
> > Do you have any preference? I think WARNING+HINT should be sufficient
> > for users as this shouldn't be a common scenario but going the other
> > way is also fine.
>
> I haven't formed a preference, but I would use these principles to decide.
> Assume we eventually support continuous, WAL-decoded replication of sequences,
> not just snapshot replication.  Which choice would make sequence replication
> behave most like table replication under the analogous concurrent actions?
>

The other point that we could consider is a future extension of
autosync sequences by allowing syncing at periodic intervals without
user intervention.

> If it's an ERROR, I'd probably omit the doc note, since the ERROR would be
> clear and unsurprising.  In general, there's no need to document everything
> that causes an error.  Documentation is most useful when an error is
> surprising or affects how the user writes the application.
>
> If the command merely raises a WARNING, documentation becomes more important,
> because warnings are easy to overlook.  That is also an argument against a
> WARNING: if the user must take action to avoid incorrect replicated state, it
> is risky to rely on the user noticing one.
>

Sounds reasonable. Considering both your points, I am leaning towards
option (a) (during REFRESH SEQUENCES command, if we detect that the
sequencesync worker is in progress, we make the command return ERROR
suggesting sequence sync is already in-progress). If in future auto
sequence sync functionality is implemented, such an ERROR could still
be appropriate because the auto sync should automatically take care of
syncing. Or, we can even go in the direction that we can use this
command to somehow immediately perform an auto sequence sync cycle
instead of time-based re-sync.

> Does that help?

Yes, thanks. But share your suggestion if you disagree with the above
or any other fix for the problem(s) reported by you.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
On Mon, Jul 13, 2026 at 08:53:42AM +0530, Amit Kapila wrote:
> On Sun, Jul 12, 2026 at 1:44 AM Noah Misch  wrote:

> Sounds reasonable. Considering both your points, I am leaning towards
> option (a) (during REFRESH SEQUENCES command, if we detect that the
> sequencesync worker is in progress, we make the command return ERROR
> suggesting sequence sync is already in-progress). If in future auto
> sequence sync functionality is implemented, such an ERROR could still
> be appropriate because the auto sync should automatically take care of
> syncing. Or, we can even go in the direction that we can use this
> command to somehow immediately perform an auto sequence sync cycle
> instead of time-based re-sync.

Sounds good.

> > Does that help?
> 
> Yes, thanks. But share your suggestion if you disagree with the above
> or any other fix for the problem(s) reported by you.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
' every

On Sat, Jul 11, 2026 at 12:46 PM vignesh C  wrote:
>
> On Sat, 11 Jul 2026 at 10:31, Amit Kapila  wrote:
> >
> > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > >
> > > A Fable 5 review of logical replication of sequences found a way to get
> > > subscribed sequences into READY state despite the subscriber side having data
> > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > I reviewed the test, and I think it identifies a genuine defect.
> > >
> >
> > Good catch. We have following ways to fix: (a) As mentioned by
> > Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> > sequencesync worker is in progress, we can either make the command
> > wait till the sequencesync is finished, return ERROR suggesting
> > sequence sync already in-progress, or first stop the sequencesync
> > worker and then complete the command and let the worker restart after
> > REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> > that are not in ready state as proposed by Vignesh. Shall we
> > additionally add a Note for user to ensure seuencesync worker is not
> > in-progress before REFRESH SEQUENCES command?
> >
> > Do you have any preference? I think WARNING+HINT should be sufficient
> > for users as this shouldn't be a common scenario but going the other
> > way is also fine.
>
> Both approaches seem reasonable to me. One downside of the WARNING
> approach is that if a subscription contains many sequences and the
> user immediately reruns ALTER SUBSCRIPTION ... REFRESH SEQUENCES, they
> could receive a large number of warnings one for each sequence that is
> already being synchronized which may be noisy and not particularly
> useful.

Right.

> Here is a patch implementing approach (a), which detects whether a
> sequence synchronization worker is already running for the
> subscription. If a synchronization is already in progress, ALTER
> SUBSCRIPTION ... REFRESH SEQUENCES reports an error and asks the user
> to rerun the command after the current synchronization completes.
>

As I suggested earlier, I think this approach is preferable.

One potential issue I anticipate is the following: if sequence
synchronization repeatedly fails due to an error that the user is not
concerned about (for example, some sequences are missing on the
publisher), the worker may keep getting started and exiting every few
seconds. If the user happens to retry ALTER SUBSCRIPTION ... REFRESH
SEQUENCES while those worker retries are in progress, they may
repeatedly fail with the new error because the worker keeps getting
restarted. Thus, the user may not easily get the sequences that matter
to sync again. It's difficult to predict how likely this scenario is,
but if the overall situation itself is rare, I think the current
suggested solution should be acceptable.

Another potential solution, slightly more complex than the previous
one, but which could completely avoid such race scenarios is by
introducing a new DATASYNC state. Before starting sequence
synchronization, the worker would move the affected sequences to
DATASYNC. If ALTER SUBSCRIPTION ... REFRESH SEQUENCES is executed
concurrently, it would reset their state back to INIT. Before marking
a sequence as READY, the worker would recheck its current state; if it
finds that the state has been reset to INIT, it would simply skip
synchronizing that sequence. Since the sequence remains in the INIT
state, it will automatically be picked up during the next
synchronization cycle. This avoids applying stale sequence values
while ensuring that fresh values are fetched from the publisher during
the subsequent synchronization attempt.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Jul 13, 2026 at 9:35 AM shveta malik  wrote:
>
> On Sat, Jul 11, 2026 at 12:46 PM vignesh C  wrote:
> >
>
> > Here is a patch implementing approach (a), which detects whether a
> > sequence synchronization worker is already running for the
> > subscription. If a synchronization is already in progress, ALTER
> > SUBSCRIPTION ... REFRESH SEQUENCES reports an error and asks the user
> > to rerun the command after the current synchronization completes.
> >
>
> As I suggested earlier, I think this approach is preferable.
>
> One potential issue I anticipate is the following: if sequence
> synchronization repeatedly fails due to an error that the user is not
> concerned about (for example, some sequences are missing on the
> publisher), the worker may keep getting started and exiting every few
> seconds. If the user happens to retry ALTER SUBSCRIPTION ... REFRESH
> SEQUENCES while those worker retries are in progress, they may
> repeatedly fail with the new error because the worker keeps getting
> restarted. Thus, the user may not easily get the sequences that matter
> to sync again. It's difficult to predict how likely this scenario is,
> but if the overall situation itself is rare, I think the current
> suggested solution should be acceptable.
>

Yeah, I think this is no different than other ERRORs, one can get
during apply like a constraint violation. The way to break the
repeated restart loop is that users need to figure out that by
checking LOGs or may be conflict related information if we ever detect
this as a conflict. So, I agree that even in this situation giving
ERROR on REFRESH SEQUENCES is reasonable.

> Another potential solution, slightly more complex than the previous
> one, but which could completely avoid such race scenarios is by
> introducing a new DATASYNC state. Before starting sequence
> synchronization, the worker would move the affected sequences to
> DATASYNC. If ALTER SUBSCRIPTION ... REFRESH SEQUENCES is executed
> concurrently, it would reset their state back to INIT. Before marking
> a sequence as READY, the worker would recheck its current state; if it
> finds that the state has been reset to INIT, it would simply skip
> synchronizing that sequence. Since the sequence remains in the INIT
> state, it will automatically be picked up during the next
> synchronization cycle. This avoids applying stale sequence values
> while ensuring that fresh values are fetched from the publisher during
> the subsequent synchronization attempt.
>

Hmm, yeah, this is another version (with a bit of additional
complexity) of auto sync as discussed in my response. I think if we
later decide to go in this direction, we may want to achieve it via
some generation_number kind of concept where the command will indicate
somewhere in shared memory that one sync cycle is required.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Sat, Jul 11, 2026 at 12:46 PM vignesh C  wrote:
>
> On Sat, 11 Jul 2026 at 10:31, Amit Kapila  wrote:
> >
> > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > >
> > > A Fable 5 review of logical replication of sequences found a way to get
> > > subscribed sequences into READY state despite the subscriber side having data
> > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > I reviewed the test, and I think it identifies a genuine defect.
> > >
> >
> > Good catch. We have following ways to fix: (a) As mentioned by
> > Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> > sequencesync worker is in progress, we can either make the command
> > wait till the sequencesync is finished, return ERROR suggesting
> > sequence sync already in-progress, or first stop the sequencesync
> > worker and then complete the command and let the worker restart after
> > REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> > that are not in ready state as proposed by Vignesh. Shall we
> > additionally add a Note for user to ensure seuencesync worker is not
> > in-progress before REFRESH SEQUENCES command?
> >
> > Do you have any preference? I think WARNING+HINT should be sufficient
> > for users as this shouldn't be a common scenario but going the other
> > way is also fine.
>
> Both approaches seem reasonable to me. One downside of the WARNING
> approach is that if a subscription contains many sequences and the
> user immediately reruns ALTER SUBSCRIPTION ... REFRESH SEQUENCES, they
> could receive a large number of warnings one for each sequence that is
> already being synchronized which may be noisy and not particularly
> useful.
>
> Here is a patch implementing approach (a), which detects whether a
> sequence synchronization worker is already running for the
> subscription. If a synchronization is already in progress, ALTER
> SUBSCRIPTION ... REFRESH SEQUENCES reports an error and asks the user
> to rerun the command after the current synchronization completes.
>

Please find my comments:

1)
+ /*
+ * Disallow a concurrent REFRESH SEQUENCES while a sequencesync worker
+ * for this subscription is still synchronizing the sequences from a
+ * previous REFRESH SEQUENCES.  Without this check, this command would
+ * reset the sequences' state back to INIT while the running worker is
+ * midway through applying the values it already fetched from the
+ * publisher, which could leave the sequences marked READY with stale
+ * data.
+ */

The wording "reset the sequences' state back to INIT" is incorrect.
There will be no issue if REFRESH resets the state back to INIT (from
READY) as those will then be picked up in the next cycle. The problem
is that there is no reset haappening. I think we can improve this
comment.

Suggestion:

/*
 * Disallow a concurrent REFRESH SEQUENCES while a sequence sync worker
 * for this subscription is still running. This avoids a race where the
 * publisher's sequence advances after the current worker has fetched its
 * value but before it marks the sequence READY. A user may then issue
 * another REFRESH SEQUENCES to synchronize the updated value. Since the
 * affected sequences are already in the INIT state, the running worker
 * has no indication that a new synchronization has been requested. It
 * would then apply the stale value it already fetched and mark the
 * sequence READY, causing the new synchronization request to be lost and
 * preventing the updated publisher values from being synchronized.
 */

2)
I am unsure if a testcase is really needed here as it is a very simple
fix. But I'd like to see what others think here.
If a test is needed, I can review it, currently I have skipped it.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
>
> Fable 5 also wrote a lot more that neither it nor I confirmed by test case
> construction.  I'm attaching the report; feel free to disregard.  Finding-2
> about default_transaction_read_only=on looks worth fixing if true,
>

Agreed on Finding-2  as well. The issue is that the sequencesync
worker sets the value via SetSequence(), which calls
PreventCommandIfReadOnly("setval()") for non-temp sequences, so with
"default_transaction_read_only=on" on the subscriber the worker's
transaction is read-only and sequence sync fails and never reaches
READY. Table apply is unaffected only because
ExecSimpleRelationInsert() bypasses the executor's
ExecCheckXactReadOnly() path which is an undocumented, untested detail
rather than a stated guarantee.

For a minimal backpatch, we can force the sequencesync worker to run
read-write (e.g. set default_transaction_read_only=off for its session
at startup) so it matches table apply, plus a test that sets the GUC
on the subscriber and verifies sequences reach READY. Separately, it's
worth documenting that logical replication apply is exempt from
default_transaction_read_only — it's a per-transaction default meant
to guard user writes and never makes the node physically read-only —
and making that exemption explicit for all logical replication workers
so tables no longer rely on the bypass. What do you think?

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Mon, 13 Jul 2026 at 11:08, shveta malik  wrote:
>
> On Sat, Jul 11, 2026 at 12:46 PM vignesh C  wrote:
> >
> > On Sat, 11 Jul 2026 at 10:31, Amit Kapila  wrote:
> > >
> > > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > > >
> > > > A Fable 5 review of logical replication of sequences found a way to get
> > > > subscribed sequences into READY state despite the subscriber side having data
> > > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > > I reviewed the test, and I think it identifies a genuine defect.
> > > >
> > >
> > > Good catch. We have following ways to fix: (a) As mentioned by
> > > Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> > > sequencesync worker is in progress, we can either make the command
> > > wait till the sequencesync is finished, return ERROR suggesting
> > > sequence sync already in-progress, or first stop the sequencesync
> > > worker and then complete the command and let the worker restart after
> > > REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> > > that are not in ready state as proposed by Vignesh. Shall we
> > > additionally add a Note for user to ensure seuencesync worker is not
> > > in-progress before REFRESH SEQUENCES command?
> > >
> > > Do you have any preference? I think WARNING+HINT should be sufficient
> > > for users as this shouldn't be a common scenario but going the other
> > > way is also fine.
> >
> > Both approaches seem reasonable to me. One downside of the WARNING
> > approach is that if a subscription contains many sequences and the
> > user immediately reruns ALTER SUBSCRIPTION ... REFRESH SEQUENCES, they
> > could receive a large number of warnings one for each sequence that is
> > already being synchronized which may be noisy and not particularly
> > useful.
> >
> > Here is a patch implementing approach (a), which detects whether a
> > sequence synchronization worker is already running for the
> > subscription. If a synchronization is already in progress, ALTER
> > SUBSCRIPTION ... REFRESH SEQUENCES reports an error and asks the user
> > to rerun the command after the current synchronization completes.
> >
>
> Please find my comments:
>
> 1)
> + /*
> + * Disallow a concurrent REFRESH SEQUENCES while a sequencesync worker
> + * for this subscription is still synchronizing the sequences from a
> + * previous REFRESH SEQUENCES.  Without this check, this command would
> + * reset the sequences' state back to INIT while the running worker is
> + * midway through applying the values it already fetched from the
> + * publisher, which could leave the sequences marked READY with stale
> + * data.
> + */
>
> The wording "reset the sequences' state back to INIT" is incorrect.
> There will be no issue if REFRESH resets the state back to INIT (from
> READY) as those will then be picked up in the next cycle. The problem
> is that there is no reset haappening. I think we can improve this
> comment.
>
> Suggestion:
>
> /*
>  * Disallow a concurrent REFRESH SEQUENCES while a sequence sync worker
>  * for this subscription is still running. This avoids a race where the
>  * publisher's sequence advances after the current worker has fetched its
>  * value but before it marks the sequence READY. A user may then issue
>  * another REFRESH SEQUENCES to synchronize the updated value. Since the
>  * affected sequences are already in the INIT state, the running worker
>  * has no indication that a new synchronization has been requested. It
>  * would then apply the stale value it already fetched and mark the
>  * sequence READY, causing the new synchronization request to be lost and
>  * preventing the updated publisher values from being synchronized.
>  */

Modified

> 2)
> I am unsure if a testcase is really needed here as it is a very simple
> fix. But I'd like to see what others think here.
> If a test is needed, I can review it, currently I have skipped it.

Even I feel a test case is not needed for this.

The attached v2 version patch has the changes for the same.
In addition, it includes a fix for Finding 2
(default_transaction_read_only) reported by Noah at [1], following the
approach suggested by Amit at [2].
This version also addresses Findings 6 and 17 by reporting an error
when ALTER SUBSCRIPTION ... REFRESH SEQUENCES is executed against
subscriptions created prior to PostgreSQL 19, and documents this
behavior accordingly.

[1] - https://www.postgresql.org/message-id/20260710045217.f0.noahmisch%40microsoft.com
[2] - https://www.postgresql.org/message-id/CAA4eK1K8LD243UzHgVNCm4skJZ4UCjR3vowDhKp%3DcWnK5oBT-Q%40mail.gmail.com

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Mon, Jul 13, 2026 at 4:38 PM vignesh C  wrote:
>
> On Mon, 13 Jul 2026 at 11:08, shveta malik  wrote:
> >
> > On Sat, Jul 11, 2026 at 12:46 PM vignesh C  wrote:
> > >
> > > On Sat, 11 Jul 2026 at 10:31, Amit Kapila  wrote:
> > > >
> > > > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > > > >
> > > > > A Fable 5 review of logical replication of sequences found a way to get
> > > > > subscribed sequences into READY state despite the subscriber side having data
> > > > > older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> > > > > I reviewed the test, and I think it identifies a genuine defect.
> > > > >
> > > >
> > > > Good catch. We have following ways to fix: (a) As mentioned by
> > > > Kuroda-san, during REFRESH SEQUENCES command, if we detect that the
> > > > sequencesync worker is in progress, we can either make the command
> > > > wait till the sequencesync is finished, return ERROR suggesting
> > > > sequence sync already in-progress, or first stop the sequencesync
> > > > worker and then complete the command and let the worker restart after
> > > > REFRESH command is finished; (b) raise a WARNING+HINT for sequences
> > > > that are not in ready state as proposed by Vignesh. Shall we
> > > > additionally add a Note for user to ensure seuencesync worker is not
> > > > in-progress before REFRESH SEQUENCES command?
> > > >
> > > > Do you have any preference? I think WARNING+HINT should be sufficient
> > > > for users as this shouldn't be a common scenario but going the other
> > > > way is also fine.
> > >
> > > Both approaches seem reasonable to me. One downside of the WARNING
> > > approach is that if a subscription contains many sequences and the
> > > user immediately reruns ALTER SUBSCRIPTION ... REFRESH SEQUENCES, they
> > > could receive a large number of warnings one for each sequence that is
> > > already being synchronized which may be noisy and not particularly
> > > useful.
> > >
> > > Here is a patch implementing approach (a), which detects whether a
> > > sequence synchronization worker is already running for the
> > > subscription. If a synchronization is already in progress, ALTER
> > > SUBSCRIPTION ... REFRESH SEQUENCES reports an error and asks the user
> > > to rerun the command after the current synchronization completes.
> > >
> >
> > Please find my comments:
> >
> > 1)
> > + /*
> > + * Disallow a concurrent REFRESH SEQUENCES while a sequencesync worker
> > + * for this subscription is still synchronizing the sequences from a
> > + * previous REFRESH SEQUENCES.  Without this check, this command would
> > + * reset the sequences' state back to INIT while the running worker is
> > + * midway through applying the values it already fetched from the
> > + * publisher, which could leave the sequences marked READY with stale
> > + * data.
> > + */
> >
> > The wording "reset the sequences' state back to INIT" is incorrect.
> > There will be no issue if REFRESH resets the state back to INIT (from
> > READY) as those will then be picked up in the next cycle. The problem
> > is that there is no reset haappening. I think we can improve this
> > comment.
> >
> > Suggestion:
> >
> > /*
> >  * Disallow a concurrent REFRESH SEQUENCES while a sequence sync worker
> >  * for this subscription is still running. This avoids a race where the
> >  * publisher's sequence advances after the current worker has fetched its
> >  * value but before it marks the sequence READY. A user may then issue
> >  * another REFRESH SEQUENCES to synchronize the updated value. Since the
> >  * affected sequences are already in the INIT state, the running worker
> >  * has no indication that a new synchronization has been requested. It
> >  * would then apply the stale value it already fetched and mark the
> >  * sequence READY, causing the new synchronization request to be lost and
> >  * preventing the updated publisher values from being synchronized.
> >  */
>
> Modified
>
> > 2)
> > I am unsure if a testcase is really needed here as it is a very simple
> > fix. But I'd like to see what others think here.
> > If a test is needed, I can review it, currently I have skipped it.
>
> Even I feel a test case is not needed for this.
>
> The attached v2 version patch has the changes for the same.
> In addition, it includes a fix for Finding 2
> (default_transaction_read_only) reported by Noah at [1], following the
> approach suggested by Amit at [2].
> This version also addresses Findings 6 and 17 by reporting an error
> when ALTER SUBSCRIPTION ... REFRESH SEQUENCES is executed against
> subscriptions created prior to PostgreSQL 19, and documents this
> behavior accordingly.
>
> [1] - https://www.postgresql.org/message-id/20260710045217.f0.noahmisch%40microsoft.com
> [2] - https://www.postgresql.org/message-id/CAA4eK1K8LD243UzHgVNCm4skJZ4UCjR3vowDhKp%3DcWnK5oBT-Q%40mail.gmail.com
>

Thanks. A few comments:

001:
1)
+ if (walrcv_server_version(wrconn) < 190000)
+ ereport(ERROR,
+ errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("cannot synchronize sequences for subscription \"%s\" because
the publisher is running a version earlier than PostgreSQL 19",
+    sub->name));
+

I think the error can be independent of subscription name, we can give
a generic error, similar to:
"cannot enable retain_dead_tuples if the publisher is running a
version earlier than PostgreSQL 19"


2)
The fix will solve the purpose. But I have a doubt for the check in
copy_sequences(). Say a few sequences are already in the INIT state,
and the subscription is then repointed to a pre-PG19 publisher. Would
the apply worker keep launching the sequence sync worker, only for it
to exit each time with this error of copy_sequences? Is my
understanding correct? If so, is there a way to avoid launching the
sequence sync worker altogether when connected to a pre-PG19
publisher? We do have 'LogRepWorkerWalRcvConn' in the apply worker to
check the version.


002: looks good.

003: yet to review.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Fri, 10 Jul 2026 at 10:22, Noah Misch  wrote:
>
> A Fable 5 review of logical replication of sequences found a way to get
> subscribed sequences into READY state despite the subscriber side having data
> older than the last REFRESH SEQUENCES.  I'm attaching the test case it wrote.
> I reviewed the test, and I think it identifies a genuine defect.
>
> Fable 5 also wrote a lot more that neither it nor I confirmed by test case
> construction.  I'm attaching the report; feel free to disregard.  Finding-2
> about default_transaction_read_only=on looks worth fixing if true, as do
> finding-7 assert failure

I agree that the assertion failure reported in Finding 7 can occur
when a sequence is dropped concurrently while ALTER SUBSCRIPTION ...
REFRESH SEQUENCES is running. I've analyzed the issue and posted a
proposed fix at [1], the thread where the relevant code was originally
introduced.

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

Regards,
Vignesh


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Jul 13, 2026 at 4:38 PM vignesh C  wrote:
>
> The attached v2 version patch has the changes for the same.
> In addition, it includes a fix for Finding 2
> (default_transaction_read_only) reported by Noah at [1], following the
> approach suggested by Amit at [2].
>

*
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -5809,6 +5809,14 @@ InitializeLogRepWorker(void)
  */
  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);

+ /*
+ * Ignore default_transaction_read_only for logical replication workers,
+ * as they need to be able to modify subscriber-side state (e.g. apply
+ * changes, update sequences) regardless of that setting.
+ */
+ SetConfigOption("default_transaction_read_only", "off", PGC_SUSET,
+ PGC_S_OVERRIDE);
+
  ApplyContext = AllocSetContextCreate(TopMemoryContext,
  "ApplyContext",
  ALLOCSET_DEFAULT_SIZES);

As pointed out in my previous email, initially let's make
backpatchable fix by adding this override only for sequencesync worker
in SequenceSyncWorkerMain(). We can discuss in a separate thread to
make this generic for all logical rep workers as a HEAD-only patch.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Jul 14, 2026 at 8:21 AM Amit Kapila  wrote:
>
> On Mon, Jul 13, 2026 at 5:46 PM shveta malik  wrote:
> >
> > 2)
> > The fix will solve the purpose. But I have a doubt for the check in
> > copy_sequences(). Say a few sequences are already in the INIT state,
> > and the subscription is then repointed to a pre-PG19 publisher. Would
> > the apply worker keep launching the sequence sync worker, only for it
> > to exit each time with this error of copy_sequences? Is my
> > understanding correct? If so, is there a way to avoid launching the
> > sequence sync worker altogether when connected to a pre-PG19
> > publisher? We do have 'LogRepWorkerWalRcvConn' in the apply worker to
> > check the version.
> >
>
> Good question. I think to handle the case you pointed and even REFRESH
> SEQUENCES case, isn't it better to raise an ERROR when the user is
> trying to point connection to a version prior to 19 and the subscriber
> has sequences? For example, we do something similar retain_dead_tuples
> parameter in AlterSubscription, see handling of
> ALTER_SUBSCRIPTION_SERVER/ALTER_SUBSCRIPTION_CONNECTION->check_pub_rdt
> in AlterSubscription().
>

Yes, that makes sense, as the user will not be able to change the
connection string unless they modify the subscription to remove
sequences.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Tue, 14 Jul 2026 at 08:21, Amit Kapila  wrote:
>
> On Mon, Jul 13, 2026 at 5:46 PM shveta malik  wrote:
> >
> > 2)
> > The fix will solve the purpose. But I have a doubt for the check in
> > copy_sequences(). Say a few sequences are already in the INIT state,
> > and the subscription is then repointed to a pre-PG19 publisher. Would
> > the apply worker keep launching the sequence sync worker, only for it
> > to exit each time with this error of copy_sequences? Is my
> > understanding correct? If so, is there a way to avoid launching the
> > sequence sync worker altogether when connected to a pre-PG19
> > publisher? We do have 'LogRepWorkerWalRcvConn' in the apply worker to
> > check the version.
> >
>
> Good question. I think to handle the case you pointed and even REFRESH
> SEQUENCES case, isn't it better to raise an ERROR when the user is
> trying to point connection to a version prior to 19 and the subscriber
> has sequences? For example, we do something similar retain_dead_tuples
> parameter in AlterSubscription, see handling of
> ALTER_SUBSCRIPTION_SERVER/ALTER_SUBSCRIPTION_CONNECTION->check_pub_rdt
> in AlterSubscription().

This is a better approach, the updated patch has the changes for the same.

> One additional comment on 0001:
> ===========================
> *
> @@ -435,6 +435,19 @@ copy_sequences(WalReceiverConn *conn)
>   StringInfoData cmd;
>   MemoryContext oldctx;
>
> + /*
> + * Sequence synchronization relies on pg_get_sequence_data(), which is
> + * only available since PostgreSQL 19.  Fail with a clear diagnosis
> + * instead of sending a query that the publisher cannot execute (or
> + * cannot even parse), which would otherwise make this worker exit with
> + * a confusing "invalid query response" error.
> + */
> + if (walrcv_server_version(conn) < 190000)
> + ereport(ERROR,
> + errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
> + errmsg("cannot synchronize sequences for subscription \"%s\" because
> the publisher is running a version earlier than PostgreSQL 19",
> +    MySubscription->name));
>
> I think it is better to move this check to the caller immediately
> after making a connection to the publisher. Also, the second part of
> the comment: "Fail with a clear diagnosis instead of sending a query
> that the ..." appears redundant to me as the code is explicit about
> the case.

Now that we are checking it while setting the connection itself, this
cannot happen from the sequence synchronization worker, so removed
this code.

The attached v3 version patch has the changes for the same.

This patch also addresses Shveta's comments from [1], Amit's comment
from [2] and [3].

[1] - https://www.postgresql.org/message-id/CAJpy0uAgM5qg5OrwL3YsiZeaq7aCyXhjSTKWHuuXoxpVcpytBw%40mail.gmail.com
[2] - https://www.postgresql.org/message-id/CAA4eK1%2Ba6FyNW-LEqWAmohM3oC6h6KOrBBSeU%2B-cfopZQLXs3g%40mail.gmail.com
[3] - https://www.postgresql.org/message-id/CAA4eK1Kf9kRm%2BT8DvkgeiPt6Az7%3DTBwWJgZ%2B3UfUEz9q9CDQeA%40mail.gmail.com

Regards,
Vignesh

RE: sequencesync worker race with REFRESH SEQUENCES

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

Thanks for updating the patch. Two comments:

01.
```
+               ereport(ERROR,
+                               errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                               errmsg("cannot execute %s while a sequence synchronization worker for subscription \"%s\" is still running",
+                                          "ALTER SUBSCRIPTION ... REFRESH SEQUENCES",
+                                          sub->name),
+                               errhint("Try again after the current synchronization completes."));
```

Maybe a translator note is needed, per other lines.

02.
```
@@ -2142,6 +2145,12 @@ AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
                         * retain_dead_tuples.
                         */
                        check_pub_rdt = sub->retaindeadtuples;
+
+                       /*
+                        * If the subscription already has sequences, ensure the new
+                        * publisher is new enough to synchronize them.
+                        */
+                       check_pub_seq = HasSubscriptionSequences(subid);
```

HasSubscriptionSequences() can spend long time because it searches pg_subscription_rel
catalog linerly. Do you think we can do the deferrable approach? I imagined to
check the remote version first and then check the catalog if the version is prior
than PG 19. Or it might be more costly to check the remote version?

Also, I find a case that REFRESH command can work even after the sequencesync
worker. I think it's harmless because of the LockSharedObject(), but let me share
just in case.

1. run ALTER SUBSCRIPTION REFRESH SEQUENCES on the first session. all states for
   the sequences can be initialized in pg_subscription_rel.
2. the apply worker finds the needs of sequencesync workers.
3. run ALTER SUBSCRIPTION REFRESH SEQUENCES on the second session. At that time
   the sequencesync worker does not exist, so it does not raise an ERROR.
4. a sequencesync worker starts, but it waits for acquiring the shared object
   with Access Exclusive.
5. the second session re-initialize the sequence states, then commit.
6. a sequencesync worker can resumes.

Can you come up with similar (and harmful) cases?

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
On Mon, Jul 13, 2026 at 03:37:54PM +0530, Amit Kapila wrote:
> On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > Fable 5 also wrote a lot more that neither it nor I confirmed by test case
> > construction.  I'm attaching the report; feel free to disregard.  Finding-2
> > about default_transaction_read_only=on looks worth fixing if true,
> 
> Agreed on Finding-2  as well. The issue is that the sequencesync
> worker sets the value via SetSequence(), which calls
> PreventCommandIfReadOnly("setval()") for non-temp sequences, so with
> "default_transaction_read_only=on" on the subscriber the worker's
> transaction is read-only and sequence sync fails and never reaches
> READY. Table apply is unaffected only because
> ExecSimpleRelationInsert() bypasses the executor's
> ExecCheckXactReadOnly() path which is an undocumented, untested detail
> rather than a stated guarantee.
> 
> For a minimal backpatch, we can force the sequencesync worker to run
> read-write (e.g. set default_transaction_read_only=off for its session
> at startup) so it matches table apply, plus a test that sets the GUC
> on the subscriber and verifies sequences reach READY. Separately, it's
> worth documenting that logical replication apply is exempt from
> default_transaction_read_only — it's a per-transaction default meant
> to guard user writes and never makes the node physically read-only —
> and making that exemption explicit for all logical replication workers
> so tables no longer rely on the bypass. What do you think?

I wouldn't document those things.  default_transaction_read_only just has the
user write "BEGIN READ WRITE" instead of plain "BEGIN".  Hence, it's more like
an "are you sure?" prompt than a restrictive guard.  It's no surprise that
logical replication apply achieves the equivalent of BEGIN READ WRITE; I don't
see that outcome as an exemption.

If easy, I would have the worker do the C equivalent of "BEGIN READ WRITE"
instead of actually changing the GUC.  That makes it clear exactly which areas
are overriding the default.  But changing the GUC is fine.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Wed, 15 Jul 2026 at 07:01, Hayato Kuroda (Fujitsu)
 wrote:
>
> Dear Vignesh,
>
> Thanks for updating the patch. Two comments:
>
> 01.
> ```
> +               ereport(ERROR,
> +                               errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
> +                               errmsg("cannot execute %s while a sequence synchronization worker for subscription \"%s\" is still running",
> +                                          "ALTER SUBSCRIPTION ... REFRESH SEQUENCES",
> +                                          sub->name),
> +                               errhint("Try again after the current synchronization completes."));
> ```
>
> Maybe a translator note is needed, per other lines.

Yes, this should be fixed

> 02.
> ```
> @@ -2142,6 +2145,12 @@ AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
>                          * retain_dead_tuples.
>                          */
>                         check_pub_rdt = sub->retaindeadtuples;
> +
> +                       /*
> +                        * If the subscription already has sequences, ensure the new
> +                        * publisher is new enough to synchronize them.
> +                        */
> +                       check_pub_seq = HasSubscriptionSequences(subid);
> ```
>
> HasSubscriptionSequences() can spend long time because it searches pg_subscription_rel
> catalog linerly. Do you think we can do the deferrable approach? I imagined to
> check the remote version first and then check the catalog if the version is prior
> than PG 19. Or it might be more costly to check the remote version?

If we do it that way, every ALTER SUBSCRIPTION CONNECTION or SERVER
would connect to the publisher, even for subscriptions that don't have
any sequences. At present, we only establish a connection to the
publisher when it is actually required, such as when update_failover,
update_two_phase, or check_pub_rdt is true. Establishing a connection
to the publisher is not a lightweight operation. It involves creating
a new connection, performing authentication, and incurring network
round trips before we can determine whether the publication contains
any sequences. In contrast, HasSubscriptionSequences() only performs a
local catalog lookup on the subscriber to determine whether the
subscription has any sequences, which is significantly cheaper.  Since
subscriptions are likely to have no sequences in few cases, always
connecting to the publisher would introduce additional overhead in the
common case just to discover information that we can often infer
locally. The local check also avoids unnecessary dependence on
publisher connectivity when no sequence-related work is needed.
Additionally this ALTER SUBSCRIPTION ... CONNECTION OR SERVER are very
rare operations. For these reasons, I think it's better to keep the
existing HasSubscriptionSequences() check so that we only connect to
the publisher when there is a possibility that sequence-related
validation is actually required.

> Also, I find a case that REFRESH command can work even after the sequencesync
> worker. I think it's harmless because of the LockSharedObject(), but let me share
> just in case.
>
> 1. run ALTER SUBSCRIPTION REFRESH SEQUENCES on the first session. all states for
>    the sequences can be initialized in pg_subscription_rel.
> 2. the apply worker finds the needs of sequencesync workers.
> 3. run ALTER SUBSCRIPTION REFRESH SEQUENCES on the second session. At that time
>    the sequencesync worker does not exist, so it does not raise an ERROR.
> 4. a sequencesync worker starts, but it waits for acquiring the shared object
>    with Access Exclusive.
> 5. the second session re-initialize the sequence states, then commit.
> 6. a sequencesync worker can resumes.

I think this case is okay. Although the second REFRESH SEQUENCES
reinitializes the sequence states before the sequence sync worker
acquires the lock, the worker has not yet fetched any sequence values
from the publisher at that point. Once it starts running, it will read
the current sequence values from the publisher and synchronize those,
rather than applying any stale values. So I don't think this
interleaving can result in outdated sequence values being applied.

Regards,
Vignesh


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Jul 15, 2026 at 8:28 AM Noah Misch  wrote:
>
> On Mon, Jul 13, 2026 at 03:37:54PM +0530, Amit Kapila wrote:
> > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > > Fable 5 also wrote a lot more that neither it nor I confirmed by test case
> > > construction.  I'm attaching the report; feel free to disregard.  Finding-2
> > > about default_transaction_read_only=on looks worth fixing if true,
> >
> > Agreed on Finding-2  as well. The issue is that the sequencesync
> > worker sets the value via SetSequence(), which calls
> > PreventCommandIfReadOnly("setval()") for non-temp sequences, so with
> > "default_transaction_read_only=on" on the subscriber the worker's
> > transaction is read-only and sequence sync fails and never reaches
> > READY. Table apply is unaffected only because
> > ExecSimpleRelationInsert() bypasses the executor's
> > ExecCheckXactReadOnly() path which is an undocumented, untested detail
> > rather than a stated guarantee.
> >
> > For a minimal backpatch, we can force the sequencesync worker to run
> > read-write (e.g. set default_transaction_read_only=off for its session
> > at startup) so it matches table apply, plus a test that sets the GUC
> > on the subscriber and verifies sequences reach READY. Separately, it's
> > worth documenting that logical replication apply is exempt from
> > default_transaction_read_only — it's a per-transaction default meant
> > to guard user writes and never makes the node physically read-only —
> > and making that exemption explicit for all logical replication workers
> > so tables no longer rely on the bypass. What do you think?
>
> I wouldn't document those things.  default_transaction_read_only just has the
> user write "BEGIN READ WRITE" instead of plain "BEGIN".  Hence, it's more like
> an "are you sure?" prompt than a restrictive guard.  It's no surprise that
> logical replication apply achieves the equivalent of BEGIN READ WRITE; I don't
> see that outcome as an exemption.
>
> If easy, I would have the worker do the C equivalent of "BEGIN READ WRITE"
> instead of actually changing the GUC.  That makes it clear exactly which areas
> are overriding the default.  But changing the GUC is fine.
>

Fair enough. I think this means we need to set XactReadOnly as false
each time after StartTransactionCommand() (where required) as we are
doing in snapbuild.c. There seems to be multiple places and some care
is required unless we want to do it each time after
StartTransactionCommand(). So, I prefer the GUC approach and we are
already overriding it for session_replication_role and search_path
GUC's. The one minor difference could be that for PG19, we set it only
for sequencesync worker and in HEAD for all workers.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
On Wed, Jul 15, 2026 at 05:23:05PM +0530, Amit Kapila wrote:
> On Wed, Jul 15, 2026 at 8:28 AM Noah Misch  wrote:
> > On Mon, Jul 13, 2026 at 03:37:54PM +0530, Amit Kapila wrote:
> > > On Fri, Jul 10, 2026 at 10:22 AM Noah Misch  wrote:
> > > > Fable 5 also wrote a lot more that neither it nor I confirmed by test case
> > > > construction.  I'm attaching the report; feel free to disregard.  Finding-2
> > > > about default_transaction_read_only=on looks worth fixing if true,
> > >
> > > Agreed on Finding-2  as well. The issue is that the sequencesync
> > > worker sets the value via SetSequence(), which calls
> > > PreventCommandIfReadOnly("setval()") for non-temp sequences, so with
> > > "default_transaction_read_only=on" on the subscriber the worker's
> > > transaction is read-only and sequence sync fails and never reaches
> > > READY. Table apply is unaffected only because
> > > ExecSimpleRelationInsert() bypasses the executor's
> > > ExecCheckXactReadOnly() path which is an undocumented, untested detail
> > > rather than a stated guarantee.
> > >
> > > For a minimal backpatch, we can force the sequencesync worker to run
> > > read-write (e.g. set default_transaction_read_only=off for its session
> > > at startup) so it matches table apply, plus a test that sets the GUC
> > > on the subscriber and verifies sequences reach READY. Separately, it's
> > > worth documenting that logical replication apply is exempt from
> > > default_transaction_read_only — it's a per-transaction default meant
> > > to guard user writes and never makes the node physically read-only —
> > > and making that exemption explicit for all logical replication workers
> > > so tables no longer rely on the bypass. What do you think?
> >
> > I wouldn't document those things.  default_transaction_read_only just has the
> > user write "BEGIN READ WRITE" instead of plain "BEGIN".  Hence, it's more like
> > an "are you sure?" prompt than a restrictive guard.  It's no surprise that
> > logical replication apply achieves the equivalent of BEGIN READ WRITE; I don't
> > see that outcome as an exemption.
> >
> > If easy, I would have the worker do the C equivalent of "BEGIN READ WRITE"
> > instead of actually changing the GUC.  That makes it clear exactly which areas
> > are overriding the default.  But changing the GUC is fine.
> 
> Fair enough. I think this means we need to set XactReadOnly as false
> each time after StartTransactionCommand() (where required) as we are
> doing in snapbuild.c. There seems to be multiple places and some care
> is required unless we want to do it each time after
> StartTransactionCommand(). So, I prefer the GUC approach

In that case, changing the GUC works for me.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
BF member skink (uses valgrind) has failed
subscription/t/036_sequences.pl twice since f38afa4ab went in.
I can reproduce that locally if I run the postmaster under valgrind.
However, valgrind isn't issuing any complaint AFAICT.  It looks like
valgrind simply slows things down enough to expose a race condition.
What is in my subscriber's log is

...
2026-07-15 20:29:08.328 EDT client backend[3612746] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
2026-07-15 20:29:09.083 EDT logical replication sequencesync worker[3612758] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] WARNING:  insufficient privileges on publisher sequence ("public.regress_s2")
2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] HINT:  Grant SELECT on the sequence to the role used for the replication connection on the publisher.
2026-07-15 20:29:10.097 EDT logical replication sequencesync worker[3612758] ERROR:  logical replication sequence synchronization failed for subscription "regress_seq_sub"
2026-07-15 20:29:10.274 EDT postmaster[3612613] LOG:  background worker "logical replication sequencesync worker" (PID 3612758) exited with exit code 1
2026-07-15 20:29:10.501 EDT logical replication sequencesync worker[3612763] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
2026-07-15 20:29:10.814 EDT client backend[3612766] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl ERROR:  cannot execute ALTER SUBSCRIPTION ... REFRESH SEQUENCES while a sequence synchronization worker is running
2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl HINT:  Try again after the current synchronization completes.
2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl STATEMENT:  ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES

That is, after checking for the "insufficient privileges" case,
we aren't waiting long enough for the new seqsync worker to quiesce.
This wasn't a problem before f38afa4ab, because it wasn't an error
condition for that worker to still be running.

			regards, tom lane


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Thu, 16 Jul 2026 at 06:21, Tom Lane  wrote:
>
> BF member skink (uses valgrind) has failed
> subscription/t/036_sequences.pl twice since f38afa4ab went in.
> I can reproduce that locally if I run the postmaster under valgrind.
> However, valgrind isn't issuing any complaint AFAICT.  It looks like
> valgrind simply slows things down enough to expose a race condition.
> What is in my subscriber's log is
>
> ...
> 2026-07-15 20:29:08.328 EDT client backend[3612746] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> 2026-07-15 20:29:09.083 EDT logical replication sequencesync worker[3612758] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
> 2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] WARNING:  insufficient privileges on publisher sequence ("public.regress_s2")
> 2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] HINT:  Grant SELECT on the sequence to the role used for the replication connection on the publisher.
> 2026-07-15 20:29:10.097 EDT logical replication sequencesync worker[3612758] ERROR:  logical replication sequence synchronization failed for subscription "regress_seq_sub"
> 2026-07-15 20:29:10.274 EDT postmaster[3612613] LOG:  background worker "logical replication sequencesync worker" (PID 3612758) exited with exit code 1
> 2026-07-15 20:29:10.501 EDT logical replication sequencesync worker[3612763] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
> 2026-07-15 20:29:10.814 EDT client backend[3612766] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl ERROR:  cannot execute ALTER SUBSCRIPTION ... REFRESH SEQUENCES while a sequence synchronization worker is running
> 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl HINT:  Try again after the current synchronization completes.
> 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl STATEMENT:  ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
>
> That is, after checking for the "insufficient privileges" case,
> we aren't waiting long enough for the new seqsync worker to quiesce.
> This wasn't a problem before f38afa4ab, because it wasn't an error
> condition for that worker to still be running.

Thanks for reporting this. I was able to reproduce the issue in my
environment as well, and I agree with your analysis of the root cause.
Here's a breakdown of what is happening from the logs at [1]:
Here, the sequence synchronization worker fails due to insufficient
privileges on the publisher sequence, as shown in the following log:
2026-07-15 23:36:03.801 CEST [1681065][logical replication
sequencesync worker][121/0:0] WARNING:  insufficient privileges on
publisher sequence ("public.regress_s2")
2026-07-15 23:36:03.801 CEST [1681065][logical replication
sequencesync worker][121/0:0] HINT:  Grant SELECT on the sequence to
the role used for the replication connection on the publisher.

The worker then exits with:
2026-07-15 23:36:03.813 CEST [1681065][logical replication
sequencesync worker][121/0:0] ERROR:  logical replication sequence
synchronization failed for subscription "regress_seq_sub"

Since not all sequences have reached the READY state, the sequence
sync worker get restarted:
2026-07-15 23:36:05.523 CEST [1684606][logical replication
sequencesync worker][122/6:0] LOG:  logical replication sequence
synchronization worker for subscription "regress_seq_sub" has started

At nearly the same time, the test executes another ALTER SUBSCRIPTION
... REFRESH SEQUENCES, which fails because a sequence synchronization
worker is already running:
2026-07-15 23:36:05.523 CEST [1684606][logical replication
sequencesync worker][122/6:0] LOG:  logical replication sequence
synchronization worker for subscription "regress_seq_sub" has started
2026-07-15 23:36:07.081 CEST [1685689][client backend][31/2:0] LOG:
statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
2026-07-15 23:36:07.215 CEST [1685689][client backend][31/2:0] ERROR:
cannot execute ALTER SUBSCRIPTION ... REFRESH SEQUENCES while a
sequence synchronization worker is running

The intent of this test is to verify the "insufficient privileges"
error first, and then verify the behavior for missing sequences. Since
the affected sequence has not yet reached the READY state, the apply
worker will automatically launch a new sequence synchronization
worker. Therefore, there is no need to issue an explicit ALTER
SUBSCRIPTION ... REFRESH SEQUENCES in this test.

I think we can simply remove the REFRESH SEQUENCES command and add a
comment explaining that the sequence synchronization worker is
restarted automatically while there are sequences that are not yet in
the READY state.

The attached patch has the changes for the same.

[1] - https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skink&dt=2026-07-15%2018%3A16%3A44

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Jul 16, 2026 at 8:28 AM Tom Lane  wrote:
>
> vignesh C  writes:
> > On Thu, 16 Jul 2026 at 06:21, Tom Lane  wrote:
> >> That is, after checking for the "insufficient privileges" case,
> >> we aren't waiting long enough for the new seqsync worker to quiesce.
> >> This wasn't a problem before f38afa4ab, because it wasn't an error
> >> condition for that worker to still be running.
>
> > I think we can simply remove the REFRESH SEQUENCES command and add a
> > comment explaining that the sequence synchronization worker is
> > restarted automatically while there are sequences that are not yet in
> > the READY state.
>
> Well, that would fix this test, but I wonder if this result isn't
> telling us that f38afa4ab has created a failure condition that will
> bite real users.  Why would the user issuing REFRESH SEQUENCES be
> aware of whether there's a sync worker running right then?  Why
> should it be his problem to avoid that?
>

The reject is there for the correctness reason explained in the commit
(otherwise an in-flight worker can mark sequences READY with values it
fetched before the REFRESH, silently losing the refresh). But you
raised a fair point that it's not ideal to make the user mind worker
timing, but I think it will be uncommon in practice:

1. The sequencesync worker isn't a persistent process; it runs only
while some sequences are still non-READY, i.e. while a sync from
CREATE/REFRESH is initiated. Once all are READY, no worker runs and
REFRESH SEQUENCES just works.
2. While a worker is running, REFRESH SEQUENCES is largely redundant
anyway, as the running worker will itself bring those sequences to
READY with current values. It's genuinely needed only to re-pull newer
values for already-READY sequences, and in that state there's no
worker to conflict with.
3. REFRESH SEQUENCES isn't routine. Since ongoing sequence changes
aren't replicated, its primary use is to update sequences before a
planned switchover/failover/upgrade, and at that point the sequences
are normally already READY, so no worker is running.

The main exception is a sync that keeps failing and restarting (e.g.
missing publisher privileges), which is what skink (BF animal) hit,
but even then the user's goal is met once the underlying issue is
fixed, as the auto-restarting worker completes on its own. And the
command errors with a clear hint to retry after the sync completes.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Thu, 16 Jul 2026 at 08:11, vignesh C  wrote:
>
> On Thu, 16 Jul 2026 at 06:21, Tom Lane  wrote:
> >
> > BF member skink (uses valgrind) has failed
> > subscription/t/036_sequences.pl twice since f38afa4ab went in.
> > I can reproduce that locally if I run the postmaster under valgrind.
> > However, valgrind isn't issuing any complaint AFAICT.  It looks like
> > valgrind simply slows things down enough to expose a race condition.
> > What is in my subscriber's log is
> >
> > ...
> > 2026-07-15 20:29:08.328 EDT client backend[3612746] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> > 2026-07-15 20:29:09.083 EDT logical replication sequencesync worker[3612758] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
> > 2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] WARNING:  insufficient privileges on publisher sequence ("public.regress_s2")
> > 2026-07-15 20:29:10.095 EDT logical replication sequencesync worker[3612758] HINT:  Grant SELECT on the sequence to the role used for the replication connection on the publisher.
> > 2026-07-15 20:29:10.097 EDT logical replication sequencesync worker[3612758] ERROR:  logical replication sequence synchronization failed for subscription "regress_seq_sub"
> > 2026-07-15 20:29:10.274 EDT postmaster[3612613] LOG:  background worker "logical replication sequencesync worker" (PID 3612758) exited with exit code 1
> > 2026-07-15 20:29:10.501 EDT logical replication sequencesync worker[3612763] LOG:  logical replication sequence synchronization worker for subscription "regress_seq_sub" has started
> > 2026-07-15 20:29:10.814 EDT client backend[3612766] 036_sequences.pl LOG:  statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> > 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl ERROR:  cannot execute ALTER SUBSCRIPTION ... REFRESH SEQUENCES while a sequence synchronization worker is running
> > 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl HINT:  Try again after the current synchronization completes.
> > 2026-07-15 20:29:10.837 EDT client backend[3612766] 036_sequences.pl STATEMENT:  ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> >
> > That is, after checking for the "insufficient privileges" case,
> > we aren't waiting long enough for the new seqsync worker to quiesce.
> > This wasn't a problem before f38afa4ab, because it wasn't an error
> > condition for that worker to still be running.
>
> Thanks for reporting this. I was able to reproduce the issue in my
> environment as well, and I agree with your analysis of the root cause.
> Here's a breakdown of what is happening from the logs at [1]:
> Here, the sequence synchronization worker fails due to insufficient
> privileges on the publisher sequence, as shown in the following log:
> 2026-07-15 23:36:03.801 CEST [1681065][logical replication
> sequencesync worker][121/0:0] WARNING:  insufficient privileges on
> publisher sequence ("public.regress_s2")
> 2026-07-15 23:36:03.801 CEST [1681065][logical replication
> sequencesync worker][121/0:0] HINT:  Grant SELECT on the sequence to
> the role used for the replication connection on the publisher.
>
> The worker then exits with:
> 2026-07-15 23:36:03.813 CEST [1681065][logical replication
> sequencesync worker][121/0:0] ERROR:  logical replication sequence
> synchronization failed for subscription "regress_seq_sub"
>
> Since not all sequences have reached the READY state, the sequence
> sync worker get restarted:
> 2026-07-15 23:36:05.523 CEST [1684606][logical replication
> sequencesync worker][122/6:0] LOG:  logical replication sequence
> synchronization worker for subscription "regress_seq_sub" has started
>
> At nearly the same time, the test executes another ALTER SUBSCRIPTION
> ... REFRESH SEQUENCES, which fails because a sequence synchronization
> worker is already running:
> 2026-07-15 23:36:05.523 CEST [1684606][logical replication
> sequencesync worker][122/6:0] LOG:  logical replication sequence
> synchronization worker for subscription "regress_seq_sub" has started
> 2026-07-15 23:36:07.081 CEST [1685689][client backend][31/2:0] LOG:
> statement: ALTER SUBSCRIPTION regress_seq_sub REFRESH SEQUENCES
> 2026-07-15 23:36:07.215 CEST [1685689][client backend][31/2:0] ERROR:
> cannot execute ALTER SUBSCRIPTION ... REFRESH SEQUENCES while a
> sequence synchronization worker is running
>
> The intent of this test is to verify the "insufficient privileges"
> error first, and then verify the behavior for missing sequences. Since
> the affected sequence has not yet reached the READY state, the apply
> worker will automatically launch a new sequence synchronization
> worker. Therefore, there is no need to issue an explicit ALTER
> SUBSCRIPTION ... REFRESH SEQUENCES in this test.
>
> I think we can simply remove the REFRESH SEQUENCES command and add a
> comment explaining that the sequence synchronization worker is
> restarted automatically while there are sequences that are not yet in
> the READY state.
>
> The attached patch has the changes for the same.

While reviewing this further, I noticed another scenario. After the
sequence synchronization worker marks all sequences as READY, if we
pause execution at report_sequence_errors(), an ALTER SUBSCRIPTION ...
REFRESH SEQUENCES can still fail. This means that checking
pg_subscription_rel and verifying that all sequences are in the READY
state is not sufficient. We also need to ensure that the sequence
synchronization worker itself has exited before proceeding, since it
may still be running even after updating the state to READY. I've
updated the test accordingly to include this additional check.
The attached v2 version patch has the changes for the same.

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
[ please, please, please: proper bottom-quoting does not mean to quote
the entire damn thread and then add a few lines of new material.  The
point of quoting is just to *briefly* remind readers of the topic. ]

vignesh C  writes:
> While reviewing this further, I noticed another scenario. After the
> sequence synchronization worker marks all sequences as READY, if we
> pause execution at report_sequence_errors(), an ALTER SUBSCRIPTION ...
> REFRESH SEQUENCES can still fail. This means that checking
> pg_subscription_rel and verifying that all sequences are in the READY
> state is not sufficient. We also need to ensure that the sequence
> synchronization worker itself has exited before proceeding, since it
> may still be running even after updating the state to READY. I've
> updated the test accordingly to include this additional check.

I grow even more skeptical that f38afa4ab was a good idea.  It seems
inevitable that it will cause annoying failures in the field.
I think that our goal here needs to be to fix the backend, not
band-aid these existing, always-worked-before test cases.

Could we, on detecting the race condition problem, wait awhile
to see if it resolves?  Or simply exit and let the REFRESH be
a no-op?

			regards, tom lane


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
Вложения:
On Fri, Jul 17, 2026 at 12:14 PM Amit Kapila  wrote:
>
> On Fri, Jul 17, 2026 at 11:03 AM Tom Lane  wrote:
> >
> > Could we, on detecting the race condition problem, wait awhile
> > to see if it resolves?
> >
>
> Yes, we can do that. But it may not be completely reliable because
> sequencesync worker can exit and restart due to some ERROR. In those
> cases, again we can miss synchronizing the latest value of sequence.
>

Thinking some more on this idea, we can achieve to close the race
condition Noah reported without giving ERROR. The idea is that REFRESH
SEQUENCES can acquired lock on pg_subscription_rel in
AccessExclusiveLock to prevent a race with the apply worker
re-launching a sequence sync worker while we reset the states. Even if
a new worker starts, it can't progress: it opens pg_subscription_rel
in AccessShareLock mode in LogicalRepSyncSequences() and will block
until we commit, by which time the sequences are INIT and it will sync
the latest values. After acquiring, REFRESH SEQUENCES command can stop
the sequencesync worker and then made all sequence states to INIT. The
stop-and-restart design along with lock ensures that after REFRESH
SEQUENCES is finished all sequences will be guaranteed to have new
values. Attached patch implements this idea. I did basic testing and
it seems to be working but needs more review and test. I also want to
once review the decision of locking pg_subscription_rel.

Note: I'll think some more on the above idea and if I or someone
didn't find any hole in it then will revert f38afa4ab tomorrow and
then make this patch ready early next week.

-- 
With Regards,
Amit Kapila.

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
Вложения:
On Fri, Jul 17, 2026 at 5:23 PM Amit Kapila  wrote:
>
> Thinking some more on this idea, we can achieve to close the race
> condition Noah reported without giving ERROR. The idea is that REFRESH
> SEQUENCES can acquired lock on pg_subscription_rel in
> AccessExclusiveLock to prevent a race with the apply worker
> re-launching a sequence sync worker while we reset the states. Even if
> a new worker starts, it can't progress: it opens pg_subscription_rel
> in AccessShareLock mode in LogicalRepSyncSequences() and will block
> until we commit, by which time the sequences are INIT and it will sync
> the latest values. After acquiring, REFRESH SEQUENCES command can stop
> the sequencesync worker and then made all sequence states to INIT. The
> stop-and-restart design along with lock ensures that after REFRESH
> SEQUENCES is finished all sequences will be guaranteed to have new
> values. Attached patch implements this idea. I did basic testing and
> it seems to be working but needs more review and test. I also want to
> once review the decision of locking pg_subscription_rel.
>
> Note: I'll think some more on the above idea and if I or someone
> didn't find any hole in it then will revert f38afa4ab tomorrow and
> then make this patch ready early next week.
>

I have pushed the revert. Attached patch fixes the race without taking
lock on pg_subscription_rel. This should be race-free because
AlterSubscription() already holds AccessExclusiveLock on the
subscription object. That lock blocks a running worker's
UpdateSubscriptionRelState(), which takes AccessShareLock on the
object, and also any worker the apply worker re-launches, because a
new worker takes AccessShareLock on the object in
InitializeLogRepWorker() before it reads pg_subscription_rel. Such a
worker cannot act on the sequence states until the refresh commits, by
which time they are reset to INIT and it will synchronize the latest
publisher values.

-- 
With Regards,
Amit Kapila.

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Sat, Jul 18, 2026 at 9:05 AM Amit Kapila  wrote:
>
> On Fri, Jul 17, 2026 at 5:23 PM Amit Kapila  wrote:
> >
> > Thinking some more on this idea, we can achieve to close the race
> > condition Noah reported without giving ERROR. The idea is that REFRESH
> > SEQUENCES can acquired lock on pg_subscription_rel in
> > AccessExclusiveLock to prevent a race with the apply worker
> > re-launching a sequence sync worker while we reset the states. Even if
> > a new worker starts, it can't progress: it opens pg_subscription_rel
> > in AccessShareLock mode in LogicalRepSyncSequences() and will block
> > until we commit, by which time the sequences are INIT and it will sync
> > the latest values. After acquiring, REFRESH SEQUENCES command can stop
> > the sequencesync worker and then made all sequence states to INIT. The
> > stop-and-restart design along with lock ensures that after REFRESH
> > SEQUENCES is finished all sequences will be guaranteed to have new
> > values. Attached patch implements this idea. I did basic testing and
> > it seems to be working but needs more review and test. I also want to
> > once review the decision of locking pg_subscription_rel.
> >
> > Note: I'll think some more on the above idea and if I or someone
> > didn't find any hole in it then will revert f38afa4ab tomorrow and
> > then make this patch ready early next week.
> >
>
> I have pushed the revert. Attached patch fixes the race without taking
> lock on pg_subscription_rel. This should be race-free because
> AlterSubscription() already holds AccessExclusiveLock on the
> subscription object. That lock blocks a running worker's
> UpdateSubscriptionRelState(), which takes AccessShareLock on the
> object, and also any worker the apply worker re-launches, because a
> new worker takes AccessShareLock on the object in
> InitializeLogRepWorker() before it reads pg_subscription_rel. Such a
> worker cannot act on the sequence states until the refresh commits, by
> which time they are reset to INIT and it will synchronize the latest
> publisher values.
>

The patch looks good. These are my obseravtions while testing:

1. If REFERSH-seq is triggered before the current seq-worker has not
reached its first UpdateSubscriptionRelState(), the seq-worker is
immediately killed and REFRESH proceeds.
2. If REFERSH-seq is triggered while a running seq-worker has already
processed one or few UpdateSubscriptionRelState(), REFRESH waits for
the worker to commit that batch, then the worker is killed and REFRESH
proceeds.
3. If seq-worker is re-launched while REFERSH-seq is changing states,
seq-worker is blocked to acquire AccessShareLock on
SubscriptionRelationId in InitializeLogRepWorker. Worker proceeds only
when REFERSH commits.

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Mon, 20 Jul 2026 at 10:47, Amit Kapila  wrote:
>
> I am attaching the subscriber log as well. I am planning to proceed
> without a test as I also can't see a reliable way to write an
> automated test for it.

I don't have a better test for this right now. Since the fix has
already been thoroughly validated manually and verified through local
debugging, I'm okay with proceeding without a test.

Regards,
Vignesh


RE: sequencesync worker race with REFRESH SEQUENCES

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

> I have pushed the revert. Attached patch fixes the race without taking
> lock on pg_subscription_rel.

Thanks for posting the patch. I confirmed that if ALTER SEQUENCE REFRESH
SEQUENCES are called twice, the second call would wait till the seqencesync
worker exits. As you told, the command will acquire the AccessExclusiveLock for the
subscription object thus it could be blocked till the sequencesync worker releases
the same lock, typically it finishes the transaction.
One concern was that CHECK_FOR_INTERRUPTS() is not called at the beginning of
the batch loop(), but it won't cause the large issue: upcoming walrcv_exec()
handles that.

The main code LGTM. I did not check the test code though.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Wed, 15 Jul 2026 at 17:23, Amit Kapila  wrote:
>
> So, I prefer the GUC approach and we are
> already overriding it for session_replication_role and search_path
> GUC's. The one minor difference could be that for PG19, we set it only
> for sequencesync worker and in HEAD for all workers.

Here is a patch to handle the same. v4-0001 patch has the changes to
set default_transaction_read_only guc in InitializeLogRepWorker which
is common to logical replication workers in master branch and v4_PG19
patch has the changes to set default_transaction_read_only guc in
SequenceSyncWorkerMain which is only for sequence sync worker.

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Jul 15, 2026 at 2:44 PM vignesh C  wrote:
>
> On Wed, 15 Jul 2026 at 07:01, Hayato Kuroda (Fujitsu)
>  wrote:
> >
>
> > 02.
> > ```
> > @@ -2142,6 +2145,12 @@ AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
> >                          * retain_dead_tuples.
> >                          */
> >                         check_pub_rdt = sub->retaindeadtuples;
> > +
> > +                       /*
> > +                        * If the subscription already has sequences, ensure the new
> > +                        * publisher is new enough to synchronize them.
> > +                        */
> > +                       check_pub_seq = HasSubscriptionSequences(subid);
> > ```
> >
> > HasSubscriptionSequences() can spend long time because it searches pg_subscription_rel
> > catalog linerly. Do you think we can do the deferrable approach? I imagined to
> > check the remote version first and then check the catalog if the version is prior
> > than PG 19. Or it might be more costly to check the remote version?
>
> If we do it that way, every ALTER SUBSCRIPTION CONNECTION or SERVER
> would connect to the publisher, even for subscriptions that don't have
> any sequences. At present, we only establish a connection to the
> publisher when it is actually required, such as when update_failover,
> update_two_phase, or check_pub_rdt is true. Establishing a connection
> to the publisher is not a lightweight operation. It involves creating
> a new connection, performing authentication, and incurring network
> round trips before we can determine whether the publication contains
> any sequences. In contrast, HasSubscriptionSequences() only performs a
> local catalog lookup on the subscriber to determine whether the
> subscription has any sequences, which is significantly cheaper.
>

I agree with this reasoning for not performing connection before
checking sequences. I think if we want to make
HasSubscriptionSequences() cheap then we can have an index on srsubid
in pg_subscription_rel or somehow track the presence of sequences at
pg_subscription level. The other idea to optimize is that for the
cases where we anyway need to form connection with the publisher, we
can defer checking the sequences. However, I feel changing the
connection string shouldn't be performed often enough to worry about
or adding additional complexity in code or adding more optimizations
for it.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Tue, 21 Jul 2026 at 10:48, Hayato Kuroda (Fujitsu)
 wrote:
>
> My assumption was that the connection was not so heavy operation.
> If it's not correct, yes the connection should be established later.

FYI, the v3-0002 patch from [1], which fixes this issue, applies
cleanly to both the master and PG19 branches. I'm re-attaching the
same patch here to make it easier for reviewers to access and review
it.

[1] - https://www.postgresql.org/message-id/CALDaNm0wi5XxbHsmKT%2BphLHwV%3DNtUeFeCpiKkjx29RanJjJ7UQ%40mail.gmail.com

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Jul 21, 2026 at 11:04 AM vignesh C  wrote:
>
> On Tue, 21 Jul 2026 at 10:48, Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > My assumption was that the connection was not so heavy operation.
> > If it's not correct, yes the connection should be established later.
>
> FYI, the v3-0002 patch from [1], which fixes this issue, applies
> cleanly to both the master and PG19 branches. I'm re-attaching the
> same patch here to make it easier for reviewers to access and review
> it.
>
> [1] - https://www.postgresql.org/message-id/CALDaNm0wi5XxbHsmKT%2BphLHwV%3DNtUeFeCpiKkjx29RanJjJ7UQ%40mail.gmail.com
>


The logic of fix looks good. A few comments:

1)
Note
Sequence synchronization requires the publisher to be running
PostgreSQL 19 or later.

This note appears to be at odd position in
logical-replication-sequences.html. Please have a look at html and
move it to end of that section if you agree.

2)
+     from the tables themselves.  Note that
+     
+     ALTER SUBSCRIPTION ... REFRESH SEQUENCES only
+     re-synchronizes sequences that are already known to the subscription
+     (see ); in particular, it
+     requires the publisher to be running PostgreSQL
+     19 or later. Before relying on it to prepare for a switchover or
+     failover, confirm that the publisher's version supports sequence
+     replication and that the sequences of interest are already known to the
+     subscription.

Do you think above is necessary? At subscription creation time, a
publisher running a version earlier than PostgreSQL 19 cannot have a
publication containing all sequences, so the subscription cannot have
such sequences known to it. Furthermore, ALTER SUBSCRIPTION to change
publisher-connection will report an error if the required
prerequisites are not met. Therefore, asking users to separately
verify the publisher version and sequence membership seems redundant
to me.

3)
+bool
+HasSubscriptionSequences(Oid subid)

Do you think we can resuse HasSubscriptionTables instead of
duplicating the complete code? We can have
HasSubscriptionRelations(subid, bool *has_tables, bool
*has_sequences)) Or is it not worth?

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Tue, 21 Jul 2026 at 12:49, shveta malik  wrote:
>
> The logic of fix looks good. A few comments:
>
> 1)
> Note
> Sequence synchronization requires the publisher to be running
> PostgreSQL 19 or later.
>
> This note appears to be at odd position in
> logical-replication-sequences.html. Please have a look at html and
> move it to end of that section if you agree.

Modified

> 2)
> +     from the tables themselves.  Note that
> +     
> +     ALTER SUBSCRIPTION ... REFRESH SEQUENCES only
> +     re-synchronizes sequences that are already known to the subscription
> +     (see ); in particular, it
> +     requires the publisher to be running PostgreSQL
> +     19 or later. Before relying on it to prepare for a switchover or
> +     failover, confirm that the publisher's version supports sequence
> +     replication and that the sequences of interest are already known to the
> +     subscription.
>
> Do you think above is necessary? At subscription creation time, a
> publisher running a version earlier than PostgreSQL 19 cannot have a
> publication containing all sequences, so the subscription cannot have
> such sequences known to it. Furthermore, ALTER SUBSCRIPTION to change
> publisher-connection will report an error if the required
> prerequisites are not met. Therefore, asking users to separately
> verify the publisher version and sequence membership seems redundant
> to me.

This scenario can be possible, Kuroda-san has reported a similar issue at [1].

> 3)
> +bool
> +HasSubscriptionSequences(Oid subid)
>
> Do you think we can resuse HasSubscriptionTables instead of
> duplicating the complete code? We can have
> HasSubscriptionRelations(subid, bool *has_tables, bool
> *has_sequences)) Or is it not worth?

Since checking at set connection does not handle all the cases, now
I'm checking this at refresh sequences because of which this code has
been now removed.

The attached patch has the changes for the same. This patch also fixes
the issue reported by Kuroda-san at [1].

[1] - https://www.postgresql.org/message-id/flat/OS9PR01MB12149C5AC91BB56D5CB4B96B2F5C22%40OS9PR01MB12149.jpnprd01.prod.outlook.com#a291e836a2bb2736ca36c8d127e2dc77

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jul 22, 2026 at 8:16 AM vignesh C  wrote:
>
> On Tue, 21 Jul 2026 at 12:49, shveta malik  wrote:
> >
> > The logic of fix looks good. A few comments:
> >
> > 1)
> > Note
> > Sequence synchronization requires the publisher to be running
> > PostgreSQL 19 or later.
> >
> > This note appears to be at odd position in
> > logical-replication-sequences.html. Please have a look at html and
> > move it to end of that section if you agree.
>
> Modified
>
> > 2)
> > +     from the tables themselves.  Note that
> > +     
> > +     ALTER SUBSCRIPTION ... REFRESH SEQUENCES only
> > +     re-synchronizes sequences that are already known to the subscription
> > +     (see ); in particular, it
> > +     requires the publisher to be running PostgreSQL
> > +     19 or later. Before relying on it to prepare for a switchover or
> > +     failover, confirm that the publisher's version supports sequence
> > +     replication and that the sequences of interest are already known to the
> > +     subscription.
> >
> > Do you think above is necessary? At subscription creation time, a
> > publisher running a version earlier than PostgreSQL 19 cannot have a
> > publication containing all sequences, so the subscription cannot have
> > such sequences known to it. Furthermore, ALTER SUBSCRIPTION to change
> > publisher-connection will report an error if the required
> > prerequisites are not met. Therefore, asking users to separately
> > verify the publisher version and sequence membership seems redundant
> > to me.
>
> This scenario can be possible, Kuroda-san has reported a similar issue at [1].
>
> > 3)
> > +bool
> > +HasSubscriptionSequences(Oid subid)
> >
> > Do you think we can resuse HasSubscriptionTables instead of
> > duplicating the complete code? We can have
> > HasSubscriptionRelations(subid, bool *has_tables, bool
> > *has_sequences)) Or is it not worth?
>
> Since checking at set connection does not handle all the cases, now
> I'm checking this at refresh sequences because of which this code has
> been now removed.
>
> The attached patch has the changes for the same. This patch also fixes
> the issue reported by Kuroda-san at [1].
>

When this idea was discussed earlier, I had asked whether we could
move the version check from copy_sequences() to the apply worker
(ProcessSequencesForSync) before it starts sequnece sync worker. The
intention was to avoid repeatedly starting the sequence-sync worker
only for it to exit in copy_sequences(). The apply worker itself could
report an error similar to how the backend reports it during REFRESH.
Thoughts?

--

Commit msg says:
Sequence synchronization relies on pg_get_sequence_data(), which was
added in PostgreSQL 19.

IIRC, it is present in PG18 as well, no?

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Jul 22, 2026 at 8:58 AM shveta malik  wrote:
>
> On Wed, Jul 22, 2026 at 8:16 AM vignesh C  wrote:
> >
> > On Tue, 21 Jul 2026 at 12:49, shveta malik  wrote:
> > >
> > > The logic of fix looks good. A few comments:
> > >
> > > 1)
> > > Note
> > > Sequence synchronization requires the publisher to be running
> > > PostgreSQL 19 or later.
> > >
> > > This note appears to be at odd position in
> > > logical-replication-sequences.html. Please have a look at html and
> > > move it to end of that section if you agree.
> >
> > Modified
> >
> > > 2)
> > > +     from the tables themselves.  Note that
> > > +     
> > > +     ALTER SUBSCRIPTION ... REFRESH SEQUENCES only
> > > +     re-synchronizes sequences that are already known to the subscription
> > > +     (see ); in particular, it
> > > +     requires the publisher to be running PostgreSQL
> > > +     19 or later. Before relying on it to prepare for a switchover or
> > > +     failover, confirm that the publisher's version supports sequence
> > > +     replication and that the sequences of interest are already known to the
> > > +     subscription.
> > >
> > > Do you think above is necessary? At subscription creation time, a
> > > publisher running a version earlier than PostgreSQL 19 cannot have a
> > > publication containing all sequences, so the subscription cannot have
> > > such sequences known to it. Furthermore, ALTER SUBSCRIPTION to change
> > > publisher-connection will report an error if the required
> > > prerequisites are not met. Therefore, asking users to separately
> > > verify the publisher version and sequence membership seems redundant
> > > to me.
> >
> > This scenario can be possible, Kuroda-san has reported a similar issue at [1].
> >
> > > 3)
> > > +bool
> > > +HasSubscriptionSequences(Oid subid)
> > >
> > > Do you think we can resuse HasSubscriptionTables instead of
> > > duplicating the complete code? We can have
> > > HasSubscriptionRelations(subid, bool *has_tables, bool
> > > *has_sequences)) Or is it not worth?
> >
> > Since checking at set connection does not handle all the cases, now
> > I'm checking this at refresh sequences because of which this code has
> > been now removed.
> >
> > The attached patch has the changes for the same. This patch also fixes
> > the issue reported by Kuroda-san at [1].
> >
>
> When this idea was discussed earlier, I had asked whether we could
> move the version check from copy_sequences() to the apply worker
> (ProcessSequencesForSync) before it starts sequnece sync worker. The
> intention was to avoid repeatedly starting the sequence-sync worker
> only for it to exit in copy_sequences(). The apply worker itself could
> report an error similar to how the backend reports it during REFRESH.
> Thoughts?

Apply-worker can report a WARNING instead of ERROR. It's no use if the
apply worker keeps exiting and restarting instead of the seqsync
worker.

> --
>
> Commit msg says:
> Sequence synchronization relies on pg_get_sequence_data(), which was
> added in PostgreSQL 19.
>
> IIRC, it is present in PG18 as well, no?
>
> thanks
> Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
Вложения:
On Wed, Jul 22, 2026 at 9:09 AM shveta malik  wrote:
>
> On Wed, Jul 22, 2026 at 8:58 AM shveta malik  wrote:
> >
> > When this idea was discussed earlier, I had asked whether we could
> > move the version check from copy_sequences() to the apply worker
> > (ProcessSequencesForSync) before it starts sequnece sync worker. The
> > intention was to avoid repeatedly starting the sequence-sync worker
> > only for it to exit in copy_sequences(). The apply worker itself could
> > report an error similar to how the backend reports it during REFRESH.
> > Thoughts?
>
> Apply-worker can report a WARNING instead of ERROR. It's no use if the
> apply worker keeps exiting and restarting instead of the seqsync
> worker.
>

I feel the WARNINGs can go unnoticed. Anyway, we do restart sync/apply
workers on ERROR or parameter change, so it seems okay to give ERROR
from sequence syncworker itself.

-- 
With Regards,
Amit Kapila.


RE: sequencesync worker race with REFRESH SEQUENCES

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

> The attached patch has the changes for the same. This patch also fixes
> the issue reported by Kuroda-san at [1].

Thanks for updating the patch. I confirmed after applying your patch, the ALTER
SUBSCRIPTION could raise an ERROR like:

```
postgres=# ALTER SERVER server OPTIONS (SET port '5434');
ALTER SERVER
postgres=# ALTER SUBSCRIPTION sub REFRESH SEQUENCES ;
ERROR:  cannot synchronize sequences if the publisher is running a version earlier than PostgreSQL 19
```

... because the backend always confirms the remove version before updating the local catalog.
I have no comments anymore.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
On Wed, 22 Jul 2026 at 16:16, Amit Kapila  wrote:
>
> On Wed, Jul 22, 2026 at 8:16 AM vignesh C  wrote:
> >
> > The attached patch has the changes for the same. This patch also fixes
> > the issue reported by Kuroda-san at [1].
> >
>
> The patch used two different error codes
> (ERRCODE_FEATURE_NOT_SUPPORTED and
> ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE) for the same condition. I
> preferred to use ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE in both
> places because the error is about the remote server's state (it isn't
> new enough), not about a capability this backend fails to implement.
> That's exactly what OBJECT_NOT_IN_PREREQUISITE_STATE is for, and it's
> what the existing publisher-version guards use. OTOH,
> FEATURE_NOT_SUPPORTED reads as "PostgreSQL doesn't implement this" —
> misleading here, since sequence sync is implemented; the publisher
> just predates it.
>
> I made this change and slightly changed the comments in the patch. See attached.

Thanks for the updated patch.

I verified the following scenarios:
Scenario 1:
1. Create a logical replication setup with sequence publication on
PostgreSQL 20.
2. Change the subscription connection to point to a PostgreSQL 18 publisher.
3. Run 'ALTER SUBSCRIPTION ... REFRESH SEQUENCES'.
The command fails with expected error:
ERROR: cannot synchronize sequences if the publisher is running a
version earlier than PostgreSQL 19

Scenario 2:
1. Create a logical replication setup with sequence publication on
PostgreSQL 20, but create the subscription with 'WITH (enabled =
false)' so that the sequences remain in the INIT state in
'pg_subscription_rel'.
2. Change the subscription connection to point to a PostgreSQL 18 publisher.
3. Enable the subscription, which starts the sequence synchronization worker.
It logs the expected error logs:
ERROR: cannot synchronize sequences if the publisher is running a
version earlier than PostgreSQL 19

I also verified the above scenarios with PostgreSQL 19 logical
replication setup and changing the connection to PostgreSQL 18
publication

I tested both scenarios using the 'CONNECTION' and 'SERVER' variants
of 'SUBSCRIPTION', and in both cases it works as expected.

The changes look good to me.

Regards,
Vignesh


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Fri, 10 Jul 2026 at 10:22, Noah Misch  wrote:
>
The other findings are gray areas, perhaps.

I had analyzed some more issues and found that these issues need to be fixed:
a) Finding 9: A running sequence synchronization worker continues
processing after ALTER SUBSCRIPTION ... DISABLE.  In this case the
leader apply worker only terminated its parallel apply workers on
detach, so a running sequencesync worker could outlive a DISABLE.
logicalrep_worker_detach() now also stops the sequencesync worker. b)
Finding 11: The sequence-removal loop runs after publisher-side
synchronization slots are dropped, violating the existing "slot drops
last" invariant. The fix moves the sequence-removal loop before the
slot-drop loop to keep the drop slots at the end. c) Finding 14: psql
tab completion for ALTER SUBSCRIPTION ... REFRESH PUBLICATION
regressed and no longer suggests WITH (. The fix restores the missing
tab-completion rule.  d) Finding 15: pg_stat_subscription reports
misleading timestamp values for the sequence synchronization worker,
and the documentation does not describe its NULL column values. The
fix reports NULL for the appropriate timestamp fields and updates the
monitoring documentation accordingly. e) Finding 16: The catalogs.sgml
description of srsublsn does not describe its meaning for sequence
rows. The fix updates the documentation to describe the semantics of
srsublsn for sequence rows.

There are a few remaining issues that I will discuss in a subsequent email.

Regards,
Vignesh

RE: sequencesync worker race with REFRESH SEQUENCES

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Вложения:
Dear Vignesh,

> a) Finding 9: A running sequence synchronization worker continues
> processing after ALTER SUBSCRIPTION ... DISABLE.  In this case the
> leader apply worker only terminated its parallel apply workers on
> detach, so a running sequencesync worker could outlive a DISABLE.
> logicalrep_worker_detach() now also stops the sequencesync worker.

Hmm, but tablesync workers, which can connect to the publisher by itself are not
terminated by the function. IIUC, tablesync workers can read the subscription
catalog and recognize the catalog. I feel we should follow that approach.

Note: I cannot find the place sequencesync worker calls maybe_reread_subscription().
It might mean that the worker cannot recognize alternations of the subscription.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Fri, 10 Jul 2026 at 10:22, Noah Misch  wrote:
>
>  The other findings are gray areas, perhaps.

I analyzed finding 4: "Gathering scan holds a lock on every INIT
relation in one unbounded transaction."

The sequence synchronization worker acquires a RowExclusiveLock on
every INIT sequence while scanning pg_subscription_rel and retains
those locks until the transaction commits. On subscriptions with a
large number of INIT sequences, this can exhaust the shared lock
table, causing repeated "out of shared memory" failures. The attached
v1-0001 patch addresses this by releasing the lock immediately after
synchronizing each sequence, preventing lock accumulation. It also
acquires an AccessShareLock instead of a RowExclusiveLock, since
AccessShareLock is sufficient to ensure that the sequence's identity
(namespace and name) remains stable against concurrent DROP, RENAME,
and SET SCHEMA operations while the sequence is being synchronized.

The attached v1-0002 patch contains a TAP test that reproduces the
issue on HEAD. I'm attaching it in case anyone wants to reproduce the
problem locally, although I don't think this test needs to be
committed.

Regards,
Vignesh

RE: sequencesync worker race with REFRESH SEQUENCES

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

> The attached v1-0002 patch contains a TAP test that reproduces the
> issue on HEAD. I'm attaching it in case anyone wants to reproduce the
> problem locally, although I don't think this test needs to be
> committed.

Thanks for posting a patch. I confirmed that "out of shared memory" error
could happen on the HEAD, and after the patch it won't happen anymore.

One minor comment:
```
+               /*
+                * Lock the sequence so its identity (namespace and name) cannot change
+                * under us via a concurrent DROP, RENAME or SET SCHEMA. Release it
+                * right away rather than at transaction end, to avoid accumulating a
+                * lock per sequence.
+                */
+               sequence_rel = try_table_open(subrel->srrelid, AccessShareLock);
```

I think this comment is not enough. We can describe why the releasing the lock
immediately is OK. IIUC, it's because the name and the namespace would be checked
again in copy_sequences(), right?

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Jul 28, 2026 at 4:14 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> One minor comment:
> ```
> +               /*
> +                * Lock the sequence so its identity (namespace and name) cannot change
> +                * under us via a concurrent DROP, RENAME or SET SCHEMA. Release it
> +                * right away rather than at transaction end, to avoid accumulating a
> +                * lock per sequence.
> +                */
> +               sequence_rel = try_table_open(subrel->srrelid, AccessShareLock);
> ```
>
> I think this comment is not enough. We can describe why the releasing the lock
> immediately is OK. IIUC, it's because the name and the namespace would be checked
> again in copy_sequences(), right?
>

Yes, that is correct. How about a comment as follows:
/*
 * Lock the sequence so its identity (namespace and name) cannot change
 * under us via a concurrent DROP, RENAME or SET SCHEMA while we read it.
 * The lock is released immediately rather than at transaction end. The
 * later synchronization does not depend on this captured identity
 * remaining valid, as it re-opens the sequence and tolerates concurrent
 * changes. Releasing early also avoids holding one lock per sequence,
 * which could exhaust the lock table.
 */

-- 
With Regards,
Amit Kapila.


RE: sequencesync worker race with REFRESH SEQUENCES

От:
"Hayato Kuroda (Fujitsu)" <kuroda.hayato@fujitsu.com>
Дата:
Вложения:
Dear Amit,

> Yes, that is correct. How about a comment as follows:
> /*
>  * Lock the sequence so its identity (namespace and name) cannot change
>  * under us via a concurrent DROP, RENAME or SET SCHEMA while we read it.
>  * The lock is released immediately rather than at transaction end. The
>  * later synchronization does not depend on this captured identity
>  * remaining valid, as it re-opens the sequence and tolerates concurrent
>  * changes. Releasing early also avoids holding one lock per sequence,
>  * which could exhaust the lock table.
>  */

LGTM.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Jul 29, 2026 at 8:35 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> > Yes, that is correct. How about a comment as follows:
> > /*
> >  * Lock the sequence so its identity (namespace and name) cannot change
> >  * under us via a concurrent DROP, RENAME or SET SCHEMA while we read it.
> >  * The lock is released immediately rather than at transaction end. The
> >  * later synchronization does not depend on this captured identity
> >  * remaining valid, as it re-opens the sequence and tolerates concurrent
> >  * changes. Releasing early also avoids holding one lock per sequence,
> >  * which could exhaust the lock table.
> >  */
>
> LGTM.
>

Thanks, pushed now.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Jul 29, 2026 at 12:25 PM vignesh C  wrote:
>
> I had a look at the remaining 4 findings that were left, here are my thoughts:
> Finding 3: `run_as_owner=false`: one un-SET-ROLE-able sequence owner
> stalls all sequence sync, unattributed.
> I think this need not be handled. We have already handled the most
> common per-sequence failure cases, such as sequence mismatch,
> insufficient privileges on the publisher, insufficient privileges on
> the subscriber, and sequences skipped because they were removed. Those
> are common scenarios that users are expected to encounter during
> sequence synchronization. The case described here requires the
> subscription owner to be unable to SET ROLE to the sequence owner when
> run_as_owner = false, which is a much less common configuration issue.
> We can revisit and do it if this gets reported from the field.
>

Agreed, I also feel it would be difficult to detect all ERRORs and
skip to next sequence sync. So, we can leave this at least for now.

> Finding 5: Sequencesync worker starved by tablesync workers; REFRESH
> SEQUENCES silently deferred
> This is handled like this intentionally and need not be handled. The
> sequence synchronization worker intentionally shares the same
> max_sync_workers_per_subscription budget as table synchronization
> workers. This is an existing design choice to limit the number of
> concurrent synchronization workers for a subscription, and the
> documentation already states that both table and sequence
> synchronization workers consume this budget. Prioritizing table
> synchronization is also intentional, since a subscription is generally
> not considered fully initialized until table synchronization has
> completed. Delaying sequence synchronization until worker slots become
> available is therefore expected behavior rather than starvation.
>

Right, so we can leave this one as well.

> Finding 10: REFRESH SEQUENCES vs concurrent subscriber DROP SEQUENCE:
> internal XX000 errors
> I don't think this needs to be addressed. REFRESH SEQUENCES is an
> administrative command that is expected to be run infrequently, and
> concurrently dropping replicated sequences on the subscriber while it
> is executing is not a common or recommended operation. The reported
> failures arise only from this narrow race and are transient. After
> such a failure, the sequence synchronization worker will be restarted
> automatically. On the subsequent run, it will either synchronize the
> remaining sequences successfully or report an appropriate error.
>

Make sense. We can leave this one as well.

> Finding 18: Restrictions bullet still claims only tables can be replicated
> I don't think this needs to be changed. The restriction is describing
> the kinds of relations that participate in logical replication itself,
> i.e., replicating changes from the publisher to the subscriber.
> Sequences are different—they do not participate in ongoing logical
> replication. The current feature only provides synchronization of
> sequence values on demand (during CREATE SUBSCRIPTION with copy_data,
> ALTER SUBSCRIPTION ... REFRESH PUBLICATION, or ALTER SUBSCRIPTION ...
> REFRESH SEQUENCES); subsequent sequence changes are not replicated
> automatically. Therefore, I don't think the existing restriction is
> misleading. The "Replicating Sequences" section already explains the
> supported behavior and its limitations, making the distinction between
> table replication and sequence synchronization clear. Changing this
> bullet could instead blur that distinction by implying that sequences
> participate in logical replication in the same way as tables, which
> they currently do not.
>

The bullet point: "Incremental sequence changes are not
replicated...." on the Restriction page explained the limitations
related to sequences, so I don't see any need to update this section
of docs.

-- 
With Regards,
Amit Kapila.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Noah Misch <noah@leadboat.com>
Дата:
On Fri, Jul 31, 2026 at 02:55:33PM +0530, Amit Kapila wrote:
> On Fri, Jul 31, 2026 at 11:06 AM vignesh C  wrote:
> > Here's the summary of the findings:
> > Finding 1: Refresh paths race the in-flight sequencesync worker -
> > committed (45cf7b1e5bf923ca48dfd9aa5001bdd0630d11c3)
> > Finding 2: `default_transaction_read_only=on` permanently blocks
> > sequence sync - committed (4cd02d552263ed8d4b148aaefd24cd9dd8af57ed)
> > Finding 3: `run_as_owner=false`: one un-SET-ROLE-able sequence owner
> > stalls all sequence sync, unattributed - Rejected at [1]
> > Finding 4: Gathering scan holds a lock on every INIT relation in one
> > unbounded transaction - committed
> > (c12c101b0846b1e6488f2dc986a852fbc6bf2e3b)
> > Finding 5: Sequencesync worker starved by tablesync workers; REFRESH
> > SEQUENCES silently deferred  - Rejected at [1]
> > Finding 6: No publisher-version guard: pre-PG19 publisher causes a
> > perpetual, cryptic error loop - committed
> > (57e7c52c0fe43fff36d0f4440eea13cf5668b160)
> > Finding 7: `has_sequence_privilege()` NULL on concurrent publisher
> > DROP: Assert crash / wrong diagnosis - committed
> > (55f518684895bfe43e667acf59284b49707ee685)
> > Finding 8: Permission-denied sequences double-reported as "missing on
> > publisher" - committed (13b7a8a0ef56d9decae284b4983894175c17d217)
> > Finding 9: ALTER SUBSCRIPTION ... DISABLE never stops a running
> > sequencesync worker - committed
> > (b8d9cf512c1259f97f9896593cc1c8352c1118ac)
> > Finding 10: REFRESH SEQUENCES vs concurrent subscriber DROP SEQUENCE:
> > internal XX000 errors - Rejected at [1]
> > Finding 11: Sequence-removal loop runs after irreversible tablesync
> > slot drops - committed (b8d9cf512c1259f97f9896593cc1c8352c1118ac)
> > Finding 12: Batch query mixes MVCC definition columns with live
> > `last_value`: validation bypass - this is a base code issue, which is.
> > being tracked at [2]
> > Finding 13: REFRESH SEQUENCES warning misattributes a `copy_data`
> > request the command cannot express - committed
> > (00b3e50054dad648e74d19cc199555381ab366d2)
> > Finding 14: psql tab-completion regression after `REFRESH PUBLICATION`
> > - committed (b8d9cf512c1259f97f9896593cc1c8352c1118ac)
> > Finding 15: pg_stat_subscription row for the sequencesync worker:
> > fabricated times, undocumented NULLs - committed
> > (b8d9cf512c1259f97f9896593cc1c8352c1118ac)
> > Finding 16: catalogs.sgml `srsublsn` description wrong for sequence
> > rows - committed (b8d9cf512c1259f97f9896593cc1c8352c1118ac)
> > Finding 17: Docs omit the PG19+ publisher requirement for sequence
> > sync; REFRESH SEQUENCES silently no-ops - committed
> > (57e7c52c0fe43fff36d0f4440eea13cf5668b160)
> > Finding 18: Restrictions bullet still claims only tables can be
> > replicated - Rejected at [1]
> >
> > With all agreed issues now committed, the remaining four findings
> > rejected by consensus, and Finding 12 being tracked separately as a
> > pre-existing base code issue, I believe all items have been addressed.
> > I felt this thread can now be marked as closed.
> 
> I agree with your analysis of the reported issues and will close the
> corresponding open item [1] early next week unless someone thinks
> otherwise. Noah, would you like to cross-verify?

No need to involve me at that level of detail.  Thanks.  I'm glad some of the
lesser findings also deserved changes.


Re: sequencesync worker race with REFRESH SEQUENCES

От:
Nikolay Samokhvalov <nik@postgres.ai>
Дата:
Вложения:
On Fri, Jul 31, 2026, vignesh C  wrote:
> Here's the summary of the findings:
> Finding 1: Refresh paths race the in-flight sequencesync worker -
> committed (45cf7b1e5bf923ca48dfd9aa5001bdd0630d11c3)

The PG19 open-items page still lists this item under "resolved before
19beta3". I left that entry unchanged; please decide whether it should
be reopened.

Part (B) of that finding is still there on REL_19_STABLE (b73d13c3)
and master (d39fda1c). 45cf7b1e5bf stops the worker in
AlterSubscription_refresh_seq(), but the sequence-removal loop in
AlterSubscription_refresh() still only takes AccessExclusiveLock on
pg_subscription_rel and calls RemoveSubscriptionRel(). Unlike the table
loop right above it, it does not stop the sequencesync worker. A worker
that already has the sequence in its INIT list fails once the refresh
commits:

  ERROR:  subscription relation 16390 in subscription 16392 does not exist

The batch is rolled back and sync_seq_error_count goes up. With
disable_on_error = true the whole subscription is disabled, tables
included. The worker has also already applied the publisher value to the
local sequence, which is no longer subscribed.

Deterministic reproducer on REL_19_STABLE, no injection points:

publisher:
    create table t (id int primary key);
    create sequence s1; create sequence s2;
    create publication pub_seq for all sequences;
    create publication pub_tab for table t;

subscriber:
    create table t (id int primary key);
    create sequence s1; create sequence s2;
    create subscription sub1 connection '...' publication pub_seq
        with (disable_on_error = true, enabled = false);

publisher, session A, keep it open:
    begin; drop sequence s1;

subscriber:
    alter subscription sub1 enable;
    -- wait until the sequencesync worker's batch query is blocked on
    -- the publisher: pg_locks shows a not-granted AccessShareLock on s1
    alter subscription sub1 set publication pub_tab;

publisher, session A:
    rollback;

subscriber, once the worker has exited:
    select subenabled from pg_subscription;                        -- f
    select sync_seq_error_count from pg_stat_subscription_stats;   -- 1

The attached patch stops the sequencesync worker in the removal loop,
as the tablesync loop and AlterSubscription_refresh_seq() do, with the
same lock argument. It adds a test to 036_sequences.pl using the
publisher-side blocking trick that file already uses. The test fails on
unpatched REL_19_STABLE with the error above and the subscription
disabled, and passes with the fix.

My AI harness found this while re-checking the fixes from this thread
and prepared the patch; I have not fully reviewed it by hand. With the
patch on b73d13c3 (cassert), the subscription TAP suite (39 files, 594
tests) and the core regression suite (239 tests) pass.

Nik

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Andrey Borodin <x4mmm@yandex-team.ru>
Дата:
On 22 Sep 2026, Nikolay Samokhvalov wrote:
> The attached patch stops the sequencesync worker in the removal loop,

I reviewed the worker stop/start interlock and reproduced the failure on
master. Your test disables the subscription without the fix and passes
with it.

I also tested REFRESH PUBLICATION removing just one of two sequences
while the worker was blocked on the publisher. The remaining sequence
reached READY, the unsubscribed local sequence kept its old value, and
table replication continued with disable_on_error = true. There were no
sequence synchronization errors.

The patch looks good.

Thank you!


Best regards, Andrey Borodin.



Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Sep 22, 2026 at 8:42 AM Nikolay Samokhvalov  wrote:
>
> On Fri, Jul 31, 2026, vignesh C  wrote:
> > Here's the summary of the findings:
> > Finding 1: Refresh paths race the in-flight sequencesync worker -
> > committed (45cf7b1e5bf923ca48dfd9aa5001bdd0630d11c3)
>
> The PG19 open-items page still lists this item under "resolved before
> 19beta3". I left that entry unchanged; please decide whether it should
> be reopened.
>
> Part (B) of that finding is still there on REL_19_STABLE (b73d13c3)
> and master (d39fda1c). 45cf7b1e5bf stops the worker in
> AlterSubscription_refresh_seq(), but the sequence-removal loop in
> AlterSubscription_refresh() still only takes AccessExclusiveLock on
> pg_subscription_rel and calls RemoveSubscriptionRel(). Unlike the table
> loop right above it, it does not stop the sequencesync worker. A worker
> that already has the sequence in its INIT list fails once the refresh
> commits:
>
>   ERROR:  subscription relation 16390 in subscription 16392 does not exist
>
> The batch is rolled back and sync_seq_error_count goes up. With
> disable_on_error = true the whole subscription is disabled, tables
> included. The worker has also already applied the publisher value to the
> local sequence, which is no longer subscribed.
>
> Deterministic reproducer on REL_19_STABLE, no injection points:
>
> publisher:
>     create table t (id int primary key);
>     create sequence s1; create sequence s2;
>     create publication pub_seq for all sequences;
>     create publication pub_tab for table t;
>
> subscriber:
>     create table t (id int primary key);
>     create sequence s1; create sequence s2;
>     create subscription sub1 connection '...' publication pub_seq
>         with (disable_on_error = true, enabled = false);
>
> publisher, session A, keep it open:
>     begin; drop sequence s1;
>
> subscriber:
>     alter subscription sub1 enable;
>     -- wait until the sequencesync worker's batch query is blocked on
>     -- the publisher: pg_locks shows a not-granted AccessShareLock on s1
>     alter subscription sub1 set publication pub_tab;
>
> publisher, session A:
>     rollback;
>
> subscriber, once the worker has exited:
>     select subenabled from pg_subscription;                        -- f
>     select sync_seq_error_count from pg_stat_subscription_stats;   -- 1
>
> The attached patch stops the sequencesync worker in the removal loop,
> as the tablesync loop and AlterSubscription_refresh_seq() do, with the
> same lock argument. It adds a test to 036_sequences.pl using the
> publisher-side blocking trick that file already uses. The test fails on
> unpatched REL_19_STABLE with the error above and the subscription
> disabled, and passes with the fix.
>
> My AI harness found this while re-checking the fixes from this thread
> and prepared the patch; I have not fully reviewed it by hand. With the
> patch on b73d13c3 (cassert), the subscription TAP suite (39 files, 594
> tests) and the core regression suite (239 tests) pass.
>

I had a look at the patch. The sequence sync worker is not per relid,
unlike the tablesync worker. So stopping the sequence worker when the
relid (one or a few) is removed is not quite the right analogy, since
a single sequence worker could be handling a large number of
sequences.

Additionally, the same race condition can be reproduced by using the
'alter sub..refresh pub' command. The following test reproduces it
using 'alter sub..refresh pub'. So whichever fix we decide on should
address both the scenarios:

Pub:
create sequence s1;
create sequence s2;
create publication pub_seq for all sequences;

Sub:
create sequence s1;
create sequence s2;
create subscription sub1 connection '...' publication pub_seq with
(disable_on_error = true, enabled = false);
--pg_subscription_rel populated with both s1 and s2 in 'i' state.

Pub's Session A:
begin;
alter sequence s2 rename to s2_tmp;

Sub:
alter subscription sub1 enable;
--The worker started by above will wait on AccessExclusiveLock lock on
pub while fetching seq s2 information.

Pub's Session B:
drop sequence s1;

Sub: refresh while worker is still stuck on s2 on pub.
alter subscription sub1 refresh publication;
--This will remove s1's entry on sub from pg_subscription_rel

Pub's Session A:
rollback;

Seq-worker proceeds and errors out as s1 is not found in
pg_subscription_rel, it disables subscription
[12132] ERROR:  subscription relation 16384 in subscription 16386 does not exist

thanks
Shveta


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Tue, 22 Sept 2026 at 08:42, Nikolay Samokhvalov  wrote:
>
> On Fri, Jul 31, 2026, vignesh C  wrote:
> > Here's the summary of the findings:
> > Finding 1: Refresh paths race the in-flight sequencesync worker -
> > committed (45cf7b1e5bf923ca48dfd9aa5001bdd0630d11c3)
>
> The PG19 open-items page still lists this item under "resolved before
> 19beta3". I left that entry unchanged; please decide whether it should
> be reopened.

I will open an item after a couple of days, once we agree that this
needs to be fixed, unless you think otherwise.

> Part (B) of that finding is still there on REL_19_STABLE (b73d13c3)
> and master (d39fda1c). 45cf7b1e5bf stops the worker in
> AlterSubscription_refresh_seq(), but the sequence-removal loop in
> AlterSubscription_refresh() still only takes AccessExclusiveLock on
> pg_subscription_rel and calls RemoveSubscriptionRel(). Unlike the table
> loop right above it, it does not stop the sequencesync worker. A worker
> that already has the sequence in its INIT list fails once the refresh
> commits:
>
>   ERROR:  subscription relation 16390 in subscription 16392 does not exist
>
> The batch is rolled back and sync_seq_error_count goes up. With
> disable_on_error = true the whole subscription is disabled, tables
> included. The worker has also already applied the publisher value to the
> local sequence, which is no longer subscribed.
>
> Deterministic reproducer on REL_19_STABLE, no injection points:
>
> publisher:
>     create table t (id int primary key);
>     create sequence s1; create sequence s2;
>     create publication pub_seq for all sequences;
>     create publication pub_tab for table t;
>
> subscriber:
>     create table t (id int primary key);
>     create sequence s1; create sequence s2;
>     create subscription sub1 connection '...' publication pub_seq
>         with (disable_on_error = true, enabled = false);
>
> publisher, session A, keep it open:
>     begin; drop sequence s1;
>
> subscriber:
>     alter subscription sub1 enable;
>     -- wait until the sequencesync worker's batch query is blocked on
>     -- the publisher: pg_locks shows a not-granted AccessShareLock on s1
>     alter subscription sub1 set publication pub_tab;
>
> publisher, session A:
>     rollback;
>
> subscriber, once the worker has exited:
>     select subenabled from pg_subscription;                        -- f
>     select sync_seq_error_count from pg_stat_subscription_stats;   -- 1
>
> The attached patch stops the sequencesync worker in the removal loop,
> as the tablesync loop and AlterSubscription_refresh_seq() do, with the
> same lock argument. It adds a test to 036_sequences.pl using the
> publisher-side blocking trick that file already uses. The test fails on
> unpatched REL_19_STABLE with the error above and the subscription
> disabled, and passes with the fix.

Thanks Nik for reporting this.

Attached is v2, which takes a slightly different approach to the same
problem. Instead of stopping the sequence sync worker when a refresh
removes a sequence, copy_sequence() now checks whether the sequence is
still part of the subscription before updating it and skips it if it
is no longer subscribed.

I preferred the v2 approach for the following reasons: a) It avoids
discarding progress for other sequences in the batch. Sequences are
synchronized in batches of up to MAX_SEQUENCES_SYNC_PER_BATCH (100) in
a single transaction. Stopping the worker because one sequence was
removed discards the catalog progress for up to 99 other sequences.
Those sequences return to INIT and have to be fetched and synchronized
again by the next worker. b) The cost of stopping the worker depends
on the batch size. If the batch size is increased in the future, v1
would silently make this case more expensive.  c) It can stop the
worker unnecessarily. AlterSubscription_refresh() removes the
pg_subscription_rel row regardless of its current state. Thus, even
removing a sequence that was already marked READY can stop the worker
while it is processing an unrelated set of sequences.

With v2, the check is made at the point where the sequence is about to
be updated, so a sequence that is no longer part of the subscription
is simply skipped.

A test for this is possible using the same publisher-side uncommitted
DROP as in the test above, but I don't think it is necessary. The
scenario requires two subscription DDLs to overlap with an ongoing
sequence synchronization, which is rare in practice, and the result is
now just a skipped sequence and a log message. Adding such a test
would require another background session, two polling loops, and a
full re-synchronization on every run of 036_sequences.pl. I don't
think the extra test is necessary for such a rare case.

The attached v2 version patch has the changes for the same.

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Tue, Sep 22, 2026 at 5:34 PM vignesh C  wrote:
>
> On Tue, 22 Sept 2026 at 08:42, Nikolay Samokhvalov  wrote:
> > The attached patch stops the sequencesync worker in the removal loop,
> > as the tablesync loop and AlterSubscription_refresh_seq() do, with the
> > same lock argument. It adds a test to 036_sequences.pl using the
> > publisher-side blocking trick that file already uses. The test fails on
> > unpatched REL_19_STABLE with the error above and the subscription
> > disabled, and passes with the fix.
>
> Thanks Nik for reporting this.
>
> Attached is v2, which takes a slightly different approach to the same
> problem. Instead of stopping the sequence sync worker when a refresh
> removes a sequence, copy_sequence() now checks whether the sequence is
> still part of the subscription before updating it and skips it if it
> is no longer subscribed.

This approach makes sense to me.

I didn't find any major issues in the patch, but I have a few questions:

1.

+ /*
+ * The sequence may no longer be part of the subscription. There is
+ * nothing left to synchronize, so leave the local sequence alone and let
+ * the caller skip it.
+ */
+ if (GetSubscriptionRelState(MySubscription->oid, seqoid,
+ &statelsn) == SUBREL_STATE_UNKNOWN)

Can we simply use SearchSysCacheExists2 to check for the subrel entry here ?

2.

+ rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
...
+ table_close(rel, NoLock);
+ table_close(rel, NoLock);
+ table_close(rel, NoLock);

The patch adds 3 table_close calls in each return branch. Would it be possible
to delay the table_open to just before UpdateSubscriptionRelState, so that only
one close call is needed?

Best Regards,
Zhijie Hou


Re: sequencesync worker race with REFRESH SEQUENCES

От:
vignesh C <vignesh21@gmail.com>
Дата:
Вложения:
On Tue, 22 Sept 2026 at 19:21, Zhijie Hou  wrote:
> >
> > Attached is v2, which takes a slightly different approach to the same
> > problem. Instead of stopping the sequence sync worker when a refresh
> > removes a sequence, copy_sequence() now checks whether the sequence is
> > still part of the subscription before updating it and skips it if it
> > is no longer subscribed.
>
> This approach makes sense to me.
>
> I didn't find any major issues in the patch, but I have a few questions:
>
> 1.
>
> + /*
> + * The sequence may no longer be part of the subscription. There is
> + * nothing left to synchronize, so leave the local sequence alone and let
> + * the caller skip it.
> + */
> + if (GetSubscriptionRelState(MySubscription->oid, seqoid,
> + &statelsn) == SUBREL_STATE_UNKNOWN)
>
> Can we simply use SearchSysCacheExists2 to check for the subrel entry here ?

Yes, it can be used.

> 2.
>
> + rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
> ...
> + table_close(rel, NoLock);
> + table_close(rel, NoLock);
> + table_close(rel, NoLock);
>
> The patch adds 3 table_close calls in each return branch. Would it be possible
> to delay the table_open to just before UpdateSubscriptionRelState, so that only
> one close call is needed?

Modified

The attached v3 version patch has the changes for the same.

Regards,
Vignesh

Re: sequencesync worker race with REFRESH SEQUENCES

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Tue, Sep 22, 2026 at 11:29 PM vignesh C  wrote:
>
> On Tue, 22 Sept 2026 at 19:21, Zhijie Hou  wrote:
> > >
> > > Attached is v2, which takes a slightly different approach to the same
> > > problem. Instead of stopping the sequence sync worker when a refresh
> > > removes a sequence, copy_sequence() now checks whether the sequence is
> > > still part of the subscription before updating it and skips it if it
> > > is no longer subscribed.
> >
> > This approach makes sense to me.
> >
> > I didn't find any major issues in the patch, but I have a few questions:
> >
> > 1.
> >
> > + /*
> > + * The sequence may no longer be part of the subscription. There is
> > + * nothing left to synchronize, so leave the local sequence alone and let
> > + * the caller skip it.
> > + */
> > + if (GetSubscriptionRelState(MySubscription->oid, seqoid,
> > + &statelsn) == SUBREL_STATE_UNKNOWN)
> >
> > Can we simply use SearchSysCacheExists2 to check for the subrel entry here ?
>
> Yes, it can be used.
>
> > 2.
> >
> > + rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
> > ...
> > + table_close(rel, NoLock);
> > + table_close(rel, NoLock);
> > + table_close(rel, NoLock);
> >
> > The patch adds 3 table_close calls in each return branch. Would it be possible
> > to delay the table_open to just before UpdateSubscriptionRelState, so that only
> > one close call is needed?
>
> Modified
>
> The attached v3 version patch has the changes for the same.
>

I liked the patch's idea; I verified it, and it works well. I have no
further comments.

Thanks.
Shveta


FAQ