[PG19] Promotion hangs behind a backend blocked on a stuck client

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

[PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi,

Since 67c20979ce7, promotion waits until every process absorbs a
ProcSignalBarrier, even with wal_level=replica and no slots. A backend
blocked sending to a client never absorbs it. If a client on the standby
pauses while fetching a result, promotion has no upper bound. A paused
client that stayed connected still held it after 300 seconds. If the
client goes away, promotion waits until TCP gives up, about 16 minutes.
18.6 promotes in 0.1 seconds. This is item 8 in [1].

Manu found why in [2]. ProcessClientWriteInterrupt() only acts on
ProcDiePending, so the barrier stays pending while secure_write() waits.
Once the send buffer is full it hangs every time.

The same wait blocks crash failover and standby
replay when the primary creates its first logical slot. With
synchronous_commit=remote_apply, commits on the primary then wait too.
DROP DATABASE has had the same problem since 15.

The patch absorbs barriers after a blocked wait in secure_read() or
secure_write() wakes up, if interrupts are not held. The normal path
does not change. We may be in the middle of a message, and
AbsorbDataChecksumsBarrier() can throw. So any error is made FATAL and
kept from the client, as Andres suggested in [3]. With a temporary
injection point there, the client sees the connection close. Without
that, the error lands inside a DataRow and the client hangs.

On the REL_19_STABLE head 84572589029 on Linux, all 38 runs with a stuck
client hung on 19, and all finished within 210 ms with the patch. The
attached file has each case and the controls.

DROP DATABASE waits for a barrier too. A stuck client has blocked 
it since 15, and 14 is fine. 0001 applies to 15 and later as is, so I
think it should go back to 15. 

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
Вложения:
On Thu, Oct 15, 2026 at 12:54 PM shihao zhong  wrote:
>
> Hi,
>
> Since 67c20979ce7, promotion waits until every process absorbs a
> ProcSignalBarrier, even with wal_level=replica and no slots.

Promotion currently waits for the barrier even with wal_level = logical?
Is that really necessary? XLogLogicalInfoActive() seems to always return
true in that case, regardless of the cached value.

Even with your patch allowing backends to process barriers while blocked
on client I/O, in addition to that fix, it's also worth skipping this barrier
when wal_level = logical? That would avoid unnecessary synchronization
with all running processes and could reduce promotion time.

Regards,

-- 
Fujii Masao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Fujii, Shihao,

Thanks for turning the diagnosis into a patch, Shihao. Fujii, good
question on whether the barrier is needed at all; I went and measured it.

> it's also worth skipping this barrier when wal_level = logical?

Yes, and a bit more. Your WIP skips it for wal_level=logical and that
case promotes (the base hangs there 6/6). But the reported case is
wal_level=replica with no slots, and there the barrier is still emitted
and still hangs (12/12 here).

The wait isn't needed when the new status is "off" either: a process
still caching "on" only writes extra logical info, which is safe, the
same reasoning DisableLogicalDecoding() already uses to emit without
waiting. So the barrier only needs waiting on when promotion turns the
status ON. The attached 0003 (on top of Shihao's 0001) does that:
replica and logical both promote, including the mid-error case v2 can't
reach; logical decoding stays correct (48/48, calibrated against a
no-barrier mutant); the recovery suite and make check pass; and healthy
promotion is unchanged (~5 ms).

It doesn't replace Shihao's patch. When the standby already has logical
slots the wait is real, and there 0003 hangs while v2 fixes it. The two
are complementary.

One note on the v2 test: without the fix the promotion subtest still
passes most of the time (the send buffer has to fill first), so it
doesn't reliably catch that case; the DROP DATABASE subtest fails every
time. On 15 and 16 the test exits early since psql there uses
FETCH_COUNT cursors, and the meson.build hunk doesn't apply on the
stable branches. 0001 itself applies cleanly from 14 to master.

Full measurements attached.

Regards,
Manu

RE: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

While discussing with LLM, I found that the current code might stuck in future,
when the callbacks in ProcessProcSignalBarrier() returns false.

According to the code comment, it can return false if it's not an appropriate
time thus we must try once again. At that time, the latch seems not to be set.
I came up with the below case for read:

1. callbacks in ProcessProcSignalBarrier() returns false.
2. it returns without seting the latch again.
3. secure_read() tries to read from the socket, but nothing found again
   (errno == EAGAIN)
4. The backend reaches WaitEventSetWait() again. The caller side of the barrier
   also keeps waiting.

I could reproduce with your patch set and below change. The reproducer could
stuck again on my env.

```
 bool
 ProcessBarrierSmgrRelease(void)
 {
+       static bool defer_once = true;
+
+       /*
+        * If this called from ProcessClientBarrierInterrupt() for the first time,
+        * do no-op and returns false. This simulates the case we have to try once
+        * again.
+        */
+       if (ExitOnAnyError && defer_once)
+       {
+               defer_once = false;
+               return false;
+       }
+
```

Actually, I'm quite unclear how we should fix. Should we just note the risk
somewhere because it does not happen yet? Another primitive idea is to set the
latch again in ProcessClientBarrierInterrupt() if ProcSignalBarrierPending is still
true, but it may waste the CPU time, wait in the secure_read() may finish soon
and check the socket again may times.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
Вложения:
On Thu, Oct 15, 2026 at 3:51 PM Manu  wrote:
> The wait isn't needed when the new status is "off" either: a process
> still caching "on" only writes extra logical info, which is safe, the
> same reasoning DisableLogicalDecoding() already uses to emit without
> waiting.

0003 looks good to me. I've attached an updated version with revised
comments in UpdateLogicalDecodingStatusEndOfRecovery(), which still
claimed that all processes had updated their XLogLogicalInfo state
before the function returned.

I think it's better to backpatch this to v19, since commit 67c20979ce7
introduced the unnecessary barrier wait. Thoughts?

Barring any objections, I'm thinking to commit it.

Regards,

-- 
Fujii Masao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Oct 15, 2026 at 9:56 AM Fujii Masao  wrote:
>
> On Thu, Oct 15, 2026 at 3:51 PM Manu  wrote:
> > The wait isn't needed when the new status is "off" either: a process
> > still caching "on" only writes extra logical info, which is safe, the
> > same reasoning DisableLogicalDecoding() already uses to emit without
> > waiting.
>
> 0003 looks good to me. I've attached an updated version with revised
> comments in UpdateLogicalDecodingStatusEndOfRecovery(), which still
> claimed that all processes had updated their XLogLogicalInfo state
> before the function returned.
>
> I think it's better to backpatch this to v19, since commit 67c20979ce7
> introduced the unnecessary barrier wait. Thoughts?
>
> Barring any objections, I'm thinking to commit it.

Thank you for the patch. It looks good to me, and I agree that it
should be backpatched to v19.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Fujii,

> I think it's better to backpatch this to v19, since commit 67c20979ce7
> introduced the unnecessary barrier wait. Thoughts?

+1, and thanks for the comment fixes. Only the comments changed from
0003, and they read right to me. I ran v3 on REL_19_STABLE: it applies
cleanly there and on master, and make check and the recovery suite pass.
Unpatched 19 hung 12/12 on promotion with one backend stuck writing to a
client; with v3 it promoted 12/12 in 10-27 ms. Unpatched 18 promoted
12/12 in the same time, so 19 is the only branch that needs it.

v3 only covers promotion without logical slots. Shihao's 0001, which
came with his report, is the general fix for when the wait is real.
Since 0001 and his test will need backpatching too, I ran them on 15
through master. Shihao, the full numbers are in the attachment; in
short:

- 060 is now taken on every branch (060_multixact_crashed_updater.pl
  went in today), so the test needs another number. 061 is free
  everywhere. Renumbered and otherwise unchanged, it passes with 0001
  on 17 through master, recovery suite included.
- On 15 and 16 it dies before testing anything: psql there runs
  FETCH_COUNT through a cursor, so the backend never blocks. psql()
  there also returns 0 on timeout, so the DROP DATABASE check can pass
  while DROP DATABASE is still stuck.
- Once v3 is in, promotion with no slot doesn't wait at all, so the
  promotion subtest passes without 0001.

The attached diff is a suggestion for all three: a COPY TO STDOUT writer,
a timed_out check, and a logical slot on the standby (19 and master
only). With it the test fails without 0001 and passes with it on 15
through master. The COPY writer also helps on its own: on unpatched
master the promotion subtest caught the hang 5/5 with it, against 1/5
as it stands. It's your test, so take whatever is useful.

Hayato, I could reproduce what you found: with your change, DROP DATABASE
stays blocked behind a backend in COPY FROM STDIN, 6/6, with or without
v3. So it's in 0001's absorb path, and v3 neither causes nor fixes it.
It's latent today: every barrier callback, in 19 and master, returns
true or throws ERROR, and none of about 1800 calls over the recovery
suite returned false. If 0001 wants to guard against it, setting the
latch again when ProcSignalBarrierPending is still set (second attached
diff) cleared your reproducer 3/3. A plain Assert there could fire
spuriously, since a new barrier can arrive right after the call.

Regards,
Manu

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi,

Hayato, you are right, thanks. v4-0001 sets the latch again if a
barrier is still pending, as Manu suggested. With your change on top,
DROP DATABASE waited 60 seconds with v2-0001 and 15 ms with v4-0001.

Manu, I took all of your test changes. On 19 and master the test fails
without 0001 and passes with it.

I call these v4 so they don't get mixed up with Fujii's v3. 

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
> DROP DATABASE waited 60 seconds with v2-0001 and 15 ms with v4-0001.

Thanks, and nicely done pulling it together -- 60 s to 15 ms is a good
result. The test changes read right to me too, and the regression is
pinned now: it fails without 0001 and passes with it on 19 and master.

It's been a pleasure to help on this one. I'll keep an eye on the thread
and jump in wherever it is useful, the backpatch included -- the test
will want renumbering there, since 060 is taken on every branch now.

Regards,
Manu


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Fri, Oct 16, 2026 at 2:40 AM Masahiko Sawada  wrote:
> Thank you for the patch. It looks good to me, and I agree that it
> should be backpatched to v19.

I've pushed the patch. Thanks!

Regards,

-- 
Fujii Masao


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Fujii,

> I've pushed the patch. Thanks!

Thanks for taking it through, and for the comment pass on v3. Glad it
made 19.

Regards,
Manu


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Oct 15, 2026 at 8:27 PM shihao zhong  wrote:
>
> Hi,
>
> Hayato, you are right, thanks. v4-0001 sets the latch again if a
> barrier is still pending, as Manu suggested. With your change on top,
> DROP DATABASE waited 60 seconds with v2-0001 and 15 ms with v4-0001.
>
> Manu, I took all of your test changes. On 19 and master the test fails
> without 0001 and passes with it.

I agree that 0001 is what fixes the rest. I'm reviewing it now, but
what I'm unsure about is whether to include it in v19 at this point.
It creates a new place where barrier callbacks run in the middle of a
protocol message, with any ERROR upgraded to FATAL, and every barrier
type we add later will have to be safe there. Neither of the two types
in v19 throws today, so this is more about what could break there
later, but it's the kind of change I'd want more time on than RC gives
us.

From the numbers upthread, a backend blocked writing to the client
(for example COPY TO STDOUT, or taking a base backup) looks like the
only case that is both likely and unbounded; the others either release
themselves or can't happen on a standby. It also needs a consumer that
has stopped rather than one that is just slow.

There are workarounds in the meantime. Setting wal_level=logical on
the standby skips the barrier entirely thanks to the recent commit. If
it does happen, the startup process logs the holding PID every five
seconds, and pg_terminate_backend() on that PID lets the promotion
finish.

So I'm currently leaning towards master only and we live with the
restriction in v19. Feedback is very welcome.

Regards,

--
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
> So I'm currently leaning towards master only and we live with the
> restriction in v19. Feedback is very welcome.

+1 to master only. I tried to break the three assumptions on current
REL_19_STABLE (c705304a0f4, which has 239c4d30699), one fresh
primary/standby pair per run, 97 runs, and they hold up:

- Since 239c4d30699 the barrier wait only happens on a wal_level=replica
  standby that has a logical slot on it -- one created on the standby, or
  a failover slot synced by the slotsync worker (I measured both). Without
  such a slot a stuck COPY TO STDOUT or a stuck base backup no longer
  delays promotion (promoted 6/6, 10-27 ms). So the restriction is a bit
  narrower than it first looks.

- With the slot, the only unbounded holders were backends blocked writing
  to a client that stopped reading: COPY TO STDOUT, a large SELECT, and a
  base backup (still waiting past 300 s). Idle, idle in transaction,
  CPU-bound queries, pg_sleep, advisory-lock and AccessExclusiveLock waits
  (including a lock the startup process itself holds), slow-but-alive
  readers at 256 KB/s, and cascading/logical walsenders all promoted in
  under 80 ms. A client stuck in authentication releases itself at
  authentication_timeout.

- Both workarounds held: wal_level=logical on the standby promoted 19/19
  in ~20 ms with the same stuck clients, and pg_terminate_backend() on the
  PID the startup process logs every 5 s finished the promotion in 9-73 ms
  in every hung run.

One edge worth a footnote in the docs or release notes: if the stuck write
is an ErrorResponse rather than a data message, pg_terminate_backend() does
not release it, because PostgresMain sends the error with interrupts held
(HOLD_INTERRUPTS before EmitErrorReport). That is not new in 19 and the
trigger I used to reach it is contrived, but there the ways out are killing
the client connection or tcp_user_timeout on the standby (10 s -> promoted
in ~7 s); wal_level=logical avoids it too.

Happy to share the scripts and the raw per-run numbers if they're useful.

Regards,
Manu


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Masahiko,

I would still like 0001 in 19, because the cases that remain are the
HA ones.

After 239c4d30699 the wait only happens when the standby has a logical
slot, and Manu measured that a failover slot synced by the slotsync
worker is enough. That is exactly the setup of an HA cluster that
keeps logical replication across failover.

A network split or a dead app host leaves such a client behind. 
Promotion then waits until TCP gives up, which may took up to 15 minutes

The workarounds need someone to know about this ahead of time, and
most failover tools do not terminate backends before promoting.

If you still prefer master only, I am fine with it and we need to
add that into the doc note for 19.

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Sun, Oct 18, 2026 at 5:14 PM shihao zhong  wrote:
>
> Hi Masahiko,
>
> I would still like 0001 in 19, because the cases that remain are the
> HA ones.
>
> After 239c4d30699 the wait only happens when the standby has a logical
> slot, and Manu measured that a failover slot synced by the slotsync
> worker is enough. That is exactly the setup of an HA cluster that
> keeps logical replication across failover.
>
> A network split or a dead app host leaves such a client behind.
> Promotion then waits until TCP gives up, which may took up to 15 minutes
>
> The workarounds need someone to know about this ahead of time, and
> most failover tools do not terminate backends before promoting.
>
> If you still prefer master only, I am fine with it and we need to
> add that into the doc note for 19.

TBH I'm still unsure that the 0001 patch is the correct approach.
ProcessProcSignalBarrier() is written on the assumption that a handler
can raise an error. That's why it has a PG_TRY block for a later
retry. In v19 we have only two handlers, ProcessBarrierSmgrRelease()
and ProcessBarrierUpdateXLogLogicalInfo(), and neither raises an
error. But on master, AbsorbDataChecksumsBarrier() raises an error on
purpose, with a comment saying it "will be caught by the procsignal
machinery for a later retry". With 0001 that error would terminate the
session instead of being retried. So the assumption that 0001 adds is
already false on master.

Other possible solutions are: (1) send the signal barrier at promotion
only when we really need to send it. In other words, if we know that
logical decoding has been enabled from the startup and no change
happened during the recovery, we can skip it even if wal_level =
replica. (2) the startup process terminates the backend who doesn't
absorb the barrier, like as we resolve the recovery conflicts.

(1) would narrow further the case where we need the wait, but doesn't
eliminate the case completely. (2) sounds more promising to me, and we
already have similar machinery such as
ResolveRecoveryConflictWithVirtualXIDs(). Probably it could help DROP
DATABASE too: TerminateOtherDBBackends() terminates only the backends
connected to the target database, so FORCE doesn't help today if a
backend connected to another database doesn't absorb the SMGRRELEASE
barrier.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi Masahiko,

I think you are right, 0001 would turn the checksum barrier's retry into a
FATAL.

Option (1) can cover the failover slot case in 19. At the end of
recovery, a stale cache can only be in a process started before
StartupLogicalDecodingStatus(), like the checkpointer. Later ones read
it at startup, and a replayed enable waits for everyone. So the startup
process can emit the barrier there, and at the end of recovery wait for
that generation when the status did not change.

It does not help when replaying the enable record has to wait, or
when the end of recovery itself turns the status on. For master I
agree (2) is better, and it helps DROP DATABASE too.

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Hi Shihao,

> At the end of recovery, a stale cache can only be in a process started
> before StartupLogicalDecodingStatus(), like the checkpointer. Later ones
> read it at startup, and a replayed enable waits for everyone.

I checked that directly for the failover-slot case (slot present before the
base backup, synced by slotsync, no status change replayed): with gdb I read
the process-local XLogLogicalInfo of every standby child just before
pg_promote(), over 8 runs. The only stale ones were the checkpointer, the
background writer, the two io workers and the startup process; every client
backend (including the one blocking promotion), the walreceiver and the
slotsync worker already had it set. So at end of recovery the barrier only
has to reach those auxiliaries, and the backend that blocks promotion is
already up to date. (I did not check whether any of those auxiliaries writes
WAL that needs the updated status.)

> It does not help when replaying the enable record has to wait, or
> when the end of recovery itself turns the status on. For master I
> agree (2) is better, and it helps DROP DATABASE too.

To check that (2) really clears these cases, I wrote a small,
measurement-only prototype of Sawada-san's idea on master (0497318e442):
in WaitForProcSignalBarrier(), after a fixed grace, a client backend or
walsender that still has not absorbed the barrier gets SIGTERM, as
pg_terminate_backend() does. It is not a patch proposal; the direction is
Sawada-san's and yours, and the diff is yours to use or ignore. (I built
your v5-0001 on the same base to compare the numbers below.)

Each case had one backend stuck in COPY TO STDOUT to a client that
stopped reading, a 2 s grace, and 3 runs:

- promotion, logical decoding enabled since startup: master hung, the
  prototype promoted in ~2.02 s, v5 in 7-22 ms
- promotion after an enable record was replayed: the same
- replay of the enable record with the backend already stuck: master
  and v5 stayed stopped for the whole 15 s, the prototype caught up in
  ~2.03 s
- pg_enable_data_checksums() on a primary: master was still
  "inprogress-on" after 15 s, the prototype reached "on" in ~2.1 s
- DROP DATABASE with the backend connected to another database: master
  hung for 20 s, the prototype dropped it in ~2.01 s

The stuck backend always ended with "terminating connection due to
administrator command". With a 5 s grace the times became ~5.0-5.1 s,
and the termination never came before the grace. As a negative control
I ran five idle sessions, one in pg_sleep() and one slow reader
(256 KB/s) through promotion, checksum enabling and DROP DATABASE: all
9 runs finished in 10-111 ms, and none of the 63 sessions was
terminated.

Two findings that may matter for the design:

- The recovery-conflict signal, as it is, does not reach such a backend.
  The same prototype sending SignalRecoveryConflict() instead of SIGTERM
  released none of them (0/12 across promotion, replay, checksums and
  DROP DATABASE), since ProcessClientWriteInterrupt() acts only on
  ProcDiePending. The same is true today for real conflicts: with
  max_standby_streaming_delay = 1s, a snapshot conflict against that
  backend kept replay stopped for the whole 15 s (3/3); the startup
  process named it as the conflicting process, and confl_snapshot
  stayed 0.

- For DROP DATABASE, a stuck backend connected to the target database
  is not a barrier wait: a plain DROP fails after 5 s with "is being
  accessed by other users", and WITH (FORCE) already works on master
  (~115 ms). The barrier case is a backend on another database, as
  Sawada-san said.

I can share the scripts, the diff and the per-run numbers if that is useful.

Regards,
Manu


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Oct 20, 2026 at 2:47 AM Masahiko Sawada  wrote:
>
> On Sun, Oct 18, 2026 at 5:14 PM shihao zhong  wrote:
>
> TBH I'm still unsure that the 0001 patch is the correct approach.
> ProcessProcSignalBarrier() is written on the assumption that a handler
> can raise an error. That's why it has a PG_TRY block for a later
> retry. In v19 we have only two handlers, ProcessBarrierSmgrRelease()
> and ProcessBarrierUpdateXLogLogicalInfo(), and neither raises an
> error. But on master, AbsorbDataChecksumsBarrier() raises an error on
> purpose, with a comment saying it "will be caught by the procsignal
> machinery for a later retry". With 0001 that error would terminate the
> session instead of being retried. So the assumption that 0001 adds is
> already false on master.
>
> Other possible solutions are: (1) send the signal barrier at promotion
> only when we really need to send it. In other words, if we know that
> logical decoding has been enabled from the startup and no change
> happened during the recovery, we can skip it even if wal_level =
> replica. (2) the startup process terminates the backend who doesn't
> absorb the barrier, like as we resolve the recovery conflicts.
>
> (1) would narrow further the case where we need the wait, but doesn't
> eliminate the case completely.
>

Right, for example, If the first logical slot appeared on the primary
shortly before promotion, replay toggled the status (false→true), the
case counts as "changed," and the wait remains. So, the same problem
still exists.

> (2) sounds more promising to me, and we
> already have similar machinery such as
> ResolveRecoveryConflictWithVirtualXIDs().
>

Like ResolveRecoveryConflictWithVirtualXIDs(), we may want to wait for
sometime (which needs GUC or a fixed time wait) before terminating the
backend. I think this is a direction worth pursuing but I feel it is
too late for v19 considering the amount/complexity of changes
required. I feel for v19, we can add a Note in the docs with a
workaround and then discuss the more robust solution for HEAD.

-- 
With Regards,
Amit Kapila.


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
Вложения:
On Tue, Oct 20, 2026 at 12:20 AM Amit Kapila  wrote:
>
> On Tue, Oct 20, 2026 at 2:47 AM Masahiko Sawada  wrote:
> >
> > On Sun, Oct 18, 2026 at 5:14 PM shihao zhong  wrote:
> >
> > TBH I'm still unsure that the 0001 patch is the correct approach.
> > ProcessProcSignalBarrier() is written on the assumption that a handler
> > can raise an error. That's why it has a PG_TRY block for a later
> > retry. In v19 we have only two handlers, ProcessBarrierSmgrRelease()
> > and ProcessBarrierUpdateXLogLogicalInfo(), and neither raises an
> > error. But on master, AbsorbDataChecksumsBarrier() raises an error on
> > purpose, with a comment saying it "will be caught by the procsignal
> > machinery for a later retry". With 0001 that error would terminate the
> > session instead of being retried. So the assumption that 0001 adds is
> > already false on master.
> >
> > Other possible solutions are: (1) send the signal barrier at promotion
> > only when we really need to send it. In other words, if we know that
> > logical decoding has been enabled from the startup and no change
> > happened during the recovery, we can skip it even if wal_level =
> > replica. (2) the startup process terminates the backend who doesn't
> > absorb the barrier, like as we resolve the recovery conflicts.
> >
> > (1) would narrow further the case where we need the wait, but doesn't
> > eliminate the case completely.
> >
>
> Right, for example, If the first logical slot appeared on the primary
> shortly before promotion, replay toggled the status (false→true), the
> case counts as "changed," and the wait remains. So, the same problem
> still exists.
>
> > (2) sounds more promising to me, and we
> > already have similar machinery such as
> > ResolveRecoveryConflictWithVirtualXIDs().
> >
>
> Like ResolveRecoveryConflictWithVirtualXIDs(), we may want to wait for
> sometime (which needs GUC or a fixed time wait) before terminating the
> backend. I think this is a direction worth pursuing but I feel it is
> too late for v19 considering the amount/complexity of changes
> required. I feel for v19, we can add a Note in the docs with a
> workaround and then discuss the more robust solution for HEAD.

Thank you for the comments.

shihao zhong drafted (1) the idea above upthread[1]. There seems to be
room for improvement there and the patch would look like the attached:
it initializes the status in shared memory from the control file, so
that the processes the postmaster forks before the startup process
reads the checkpoint record don't start with a stale cache. Given the
patch and analysis[2] shared by Manu, let me summarize the issue and
solutions.

With the v6 patch, we would need to wait for the signal barrier to be
absorbed only when the startup process enables logical decoding at the
end of recovery, which is a rare case. On standbys the status is
toggled by replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record,
and the enable case waits for all processes. In some corner cases, the
startup process enables logical decoding at the end of recovery on
behalf of a backend creating a logical slot, so we need a wait for
that case. While making this case rarer is appealing, the v6 patch
doesn't remove it.

The v6 patch also doesn't resolve the case where the replay itself
stops because a backend is stuck writing to a client. As Amit
mentioned, if that delay happens shortly before the promotion, the
promotion would get blocked. The same can be applied to recovery
conflict cases: Manu measured that such a backend is not released by a
recovery conflict signal either[2], since
ProcessClientWriteInterrupt() services only ProcDiePending, and
therefore the recovery gets blocked even with
max_standby_streaming_delay set.

So I think that the recovery (and the promotion) getting stuck due to
client write I/O is not new in v19. max_standby_streaming_delay
doesn't work against a backend stuck writing to a client, and v19 just
adds one more way to hit the same limitation. I still prefer dealing
with this issue only for master, and leave the code in v19 as it is.
For v19 I think we should add a note to the documentation, as Amit
suggested. And possibly we can backpatch the v6 patch in a later minor
release once we test the approach enough on the master.

Regards,

[1] https://www.postgresql.org/message-id/CAGRkXqR8Kfdd%3DG1Le%3DRzhRHzZBbLtPc44207bwhrPDu_C5ZMEA%40mail.gmail.com
[2] https://www.postgresql.org/message-id/179247119467.2410654.17218914322784616346%40gmail.com

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Вложения:
Hi Masahiko,

I agree. 19 gets a note in the docs, and v6 goes to master first.

The docs patch for 19 is attached. It says what blocks, how to see the
PID, and how to get out. I am happy to change the wording.

For (2), I think it is still worth doing on master even with v6. It
would also cover replay of the enable record and recovery conflicts
with a backend stuck on a client write. Manu, do you want to post it?
If not, I am happy to take it.

Thanks,
Shihao


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
Вложения:
On Wed, Oct 21, 2026 at 6:09 AM shihao zhong  wrote:
>
> I agree. 19 gets a note in the docs, and v6 goes to master first.
>
> The docs patch for 19 is attached. It says what blocks, how to see the
> PID, and how to get out. I am happy to change the wording.
>


+    To avoid the wait, set wal_level to
+    logical on the standby.

Will this help when the promotion is stuck? I feel this defeats the
purpose of the feature introduced in commit 67c20979ce7. Also, not
sure saying: " 15 minutes with default TCP settings" doesn't sound
like a good idea because default on Windows may be different;
additionally, if the client is alive but has stopped reading, it can
take much more time. I have tried to make it generic in the attached
(the patch is atop v20 for now).

> For (2), I think it is still worth doing on master even with v6. It
> would also cover replay of the enable record and recovery conflicts
> with a backend stuck on a client write. Manu, do you want to post it?
> If not, I am happy to take it.
>

If we anyway would like to implement killing of connections that
didn't absorb barriers then do we even need v6. I am slightly hesitant
about v6 because it adds more assumptions in the code like which
processes can have stale cache.

-- 
With Regards,
Amit Kapila.

RE: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

> Will this help when the promotion is stuck? I feel this defeats the
> purpose of the feature introduced in commit 67c20979ce7. Also, not
> sure saying: " 15 minutes with default TCP settings" doesn't sound
> like a good idea because default on Windows may be different;
> additionally, if the client is alive but has stopped reading, it can
> take much more time. I have tried to make it generic in the attached
> (the patch is atop v20 for now).

Yes, the original patch was too Linux-specific, in general yours was better.
Few comments:

```
+     On a standby with wal_level set to
+     replica that has a logical replication slot
```
We can clarify that the valid replication slot is needed.

```
The setting takes effect only for connections
+     established after it is configured,
```

Hmm, is it correct?
There is an assign hook which can update the socket option. My below experiment
also indicated that TCP_USER_TIMEOUT can be enabled for established connections.

1. Connected via TCP connection
$ psql -h 127.0.0.1 -U postgres

2. Set the tcp_user_timeout

```
postgres=# SHOW tcp_user_timeout ;
 tcp_user_timeout 
------------------
 0
(1 row)

postgres=# SET tcp_user_timeout = '3s';
SET
```

3. Sent a large amount of data to the client.

```
postgres=# COPY (                         
    SELECT repeat('x', 1000000)
    FROM generate_series(1, 100000)
) TO STDOUT;
```

4. Sent a STOP signal to psql process, from another terminal
```
$ kill -STOP 40049
```

5. After sometime the backend could be terminated due to the tcp timeout.
According to the log:

```
LOG:  could not send data to client: Connection timed out
STATEMENT:  COPY (
            SELECT repeat('x', 1000000)
            FROM generate_series(1, 100000)
        ) TO STDOUT;
```

Note: the backend could retain if step2 was skipped.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi,

shihao zhong wrote:
> Manu, do you want to post it? If not, I am happy to take it.

I would, thanks. Attached is v1 of (2) for master, for review.

After procsignal_barrier_timeout, WaitForProcSignalBarrier() sends
SIGTERM to any client backend or WAL sender that still has not absorbed
the barrier, as pg_terminate_backend() would, and keeps waiting until
it exits. Other processes are never signaled. The waiter logs

  LOG:  terminating process 12345 because it has not accepted
        ProcSignalBarrier within 2000 ms

and the session ends with the usual "terminating connection due to
administrator command".

Choices I made, all easy to change:

- SIGTERM rather than SignalRecoveryConflict(). A backend blocked in a
  client write only services ProcDiePending
  (ProcessClientWriteInterrupt()), which is why the conflict variant of
  the prototype released none of the 12 stuck cases.

- It applies to every waiter, not only the startup process (marked
  XXX in the patch). The same hang happens on a primary; in the test
  the waiters are a client backend (DROP DATABASE), the datachecksums
  launcher and the startup process.

- A GUC: default 30s, the same as max_standby_streaming_delay, 0
  disables, PGC_SIGHUP since it decides whether other users' sessions
  get terminated. Fixed time vs GUC, name and default are all open.

- Signaled once per process; after that the wait continues as today
  and wakes up when the process exits.

- No dedicated message for the terminated session. Its client cannot
  receive it anyway, since a blocked write switches output to DestNone;
  the waiter's LOG line names the PID.

The new TAP test (recovery/061) uses a psql whose output is never read,
so its backend blocks in ClientWrite, and a 2 s timeout. On unpatched
master, with the same setup in a separate script, each of the cases
below was still stuck after 10 s and finished a few ms after a manual
pg_terminate_backend(). With the patch, over 5 runs of the test:

- DROP DATABASE with the session on another database
- pg_enable_data_checksums()
- DROP DATABASE with a WAL sender stuck in a base backup
- replay of the record enabling logical decoding on a standby
- promotion of a standby with a logical slot

all completed, the stuck session terminated 2001-2020 ms after the
operation started, never before the timeout. Negative control: an idle
session, one in pg_sleep() and a slow but steady reader survived
DROP DATABASE and pg_disable_data_checksums() in all runs, with no
termination and the DROP under 2 s; an idle session on the standby
survived the promotion. With the timeout at 0, DROP DATABASE kept
waiting, as on master.

make check, the recovery suite (848 tests, with injection points) and
test_checksums with checksum_extended (458) pass; no other test
triggered a termination.

What it does not cover:

- Recovery conflicts. With the patch, a snapshot conflict against such
  a session still stopped replay for the whole 15 s window (3/3): that
  path signals with SignalRecoveryConflict() and is not changed here.
  Escalating to SIGTERM after max_standby_*_delay for a backend in a
  client write could be a follow-up, if people want it.

- A backend stuck while sending an ERROR, which holds interrupts; as
  reported upthread, pg_terminate_backend() does not release it
  either.

On v6: (2) also covers replay of the enable record, data checksums,
DROP DATABASE and WAL senders, which v6 does not. v6 is still the
cheaper path at end of recovery: without it a promotion behind a stuck
session waits the full timeout (30 s by default) and terminates that
session, even though in the failover-slot case I checked, that backend
already had the up-to-date status. So I see v6 as a fast path rather
than something (2) makes unnecessary, but that is your call.

Regards,
Manu

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Amit,

> Will this help when the promotion is stuck?

No, you are right. It only avoids the wait next time, and it gives up
the point of 67c20979ce7. Your version is better, mine was too Linux
specific. Please go with yours.

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Manu,

Thanks for posting your patch, I have 3 thoughts.

1. I think it kills more than client writes. With a 2s timeout it also killed
a session waiting for sync rep, and a COPY FROM STDIN client that
paused(in primary),

2. 061 failed 4 of 11 runs here. slow_reader stops reading before the
checksums launcher waits, so it gets killed.

3. shouldTerminateBarrierStraggler() recheck pss_barrierGeneration
under pss_mutex? because it can kill a new backend in the same slot.

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Oct 21, 2026 at 2:36 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> ```
> The setting takes effect only for connections
> +     established after it is configured,
> ```
>
> Hmm, is it correct?
> There is an assign hook which can update the socket option. My below experiment
> also indicated that TCP_USER_TIMEOUT can be enabled for established connections.
>
> 1. Connected via TCP connection
> $ psql -h 127.0.0.1 -U postgres
>
> 2. Set the tcp_user_timeout
>
> ```
> postgres=# SHOW tcp_user_timeout ;
>  tcp_user_timeout
> ------------------
>  0
> (1 row)
>
> postgres=# SET tcp_user_timeout = '3s';
> SET
> ```
>
> 3. Sent a large amount of data to the client.
>
> ```
> postgres=# COPY (
>     SELECT repeat('x', 1000000)
>     FROM generate_series(1, 100000)
> ) TO STDOUT;
> ```
>
> 4. Sent a STOP signal to psql process, from another terminal
> ```
> $ kill -STOP 40049
> ```
>
> 5. After sometime the backend could be terminated due to the tcp timeout.
> According to the log:
>
> ```
> LOG:  could not send data to client: Connection timed out
> STATEMENT:  COPY (
>             SELECT repeat('x', 1000000)
>             FROM generate_series(1, 100000)
>         ) TO STDOUT;
> ```
>
> Note: the backend could retain if step2 was skipped.
>

Thanks for the test but how can the user know when to set it, if not
before connection? Anyway, how about something generic as follows:
-     To bound such waits in advance, set
-     tcp_user_timeout on the standby, where supported by
-     the operating system.  The setting takes effect only for connections
-     established after it is configured, and does not affect a connection
-     whose backend is already blocked.
+     To bound such waits, configure tcp_user_timeout on
+     the standby ahead of time, for example in
+     postgresql.conf, where supported by the operating
+     system.  Setting it after a backend is already blocked sending data has
+     no effect on that backend.

-- 
With Regards,
Amit Kapila.


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shveta malik <shveta.malik@gmail.com>
Дата:
On Wed, Oct 21, 2026 at 10:47 AM Amit Kapila  wrote:
>
> On Wed, Oct 21, 2026 at 6:09 AM shihao zhong  wrote:
> >
> > I agree. 19 gets a note in the docs, and v6 goes to master first.
> >
> > The docs patch for 19 is attached. It says what blocks, how to see the
> > PID, and how to get out. I am happy to change the wording.
> >
>
> 
> +    To avoid the wait, set wal_level to
> +    logical on the standby.
>
> Will this help when the promotion is stuck? I feel this defeats the
> purpose of the feature introduced in commit 67c20979ce7.

+1.

I like the doc idea on PG19 and the patch 'fix_doc.1'. A few comments:

1)
+     replica that has a logical replication slot at the end
+1 on what Kuroda-san pointed. I think we should mention 'valid' slots

2)
It would be better to link tcp_user_timeout (and wal_level) rather
than only naming it, so readers can find the platform and Unix-socket
restrictions.

3)
+     To bound such waits in advance, set
+     tcp_user_timeout on the standby, where supported by
+     the operating system.  The setting takes effect only for connections
+     established after it is configured, and does not affect a connection
+     whose backend is already blocked.

Shall we change to:

To bound such waits in advance, set tcp_user_timeout on the standby;
it applies only to TCP connections, on platforms that support it.
After a configuration reload, an existing session picks up the new
value when its client sends the next query. Consequently, the setting
does not affect a backend that is already blocked.

thanks
Shveta


RE: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

> After a configuration reload, an existing session picks up the new
> value when its client sends the next query.

IIUC the description is correct: a backend process reloads the configuration in
the main loop, and assign hook can be called there. But yours are also OK if you
think it's too detail.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Shihao,

Thanks for testing it and for the review. v2 is attached, on today's
master. Point by point:

> 1. I think it kills more than client writes. With a 2s timeout it also
> killed
> a session waiting for sync rep, and a COPY FROM STDIN client that
> paused(in primary),

Reproduced: v1 terminated both after 2.02 s, and after 30.02 s with the
default; the sync rep one with "might not have been replicated to the
standby". Neither can absorb the barrier while it waits:
SyncRepWaitForLSN() doesn't run CHECK_FOR_INTERRUPTS(), and a COPY FROM
STDIN read only services ProcDiePending. On master, DROP DATABASE was
still waiting for them after 45 s and finished 15 ms after each one was
released.

v2 terminates only a client backend or WAL sender whose wait event is
ClientWrite. Any other straggler is left alone and checked again at
each wakeup. With v2, at 2 s and at 30 s, both sessions survive, DROP
waits as on master and finishes 4-15 ms after they move on, and the
five stuck cases from v1 still clear once the timeout expires. Both
are now negative cases in 061.

One gray zone is left: a session still sending a single large value to
a slow client also sits in ClientWrite, with no CHECK_FOR_INTERRUPTS()
until the value is out. Through a proxy limited to 2 MB/s, a 100 MB
value made DROP wait 50.5 s on master; v2 with the default 30 s
terminated that session at 30.05 s. I documented it in config.sgml,
but I don't see a way to tell it apart from a client that stopped
reading, with what another process can see. Ideas welcome.

> 2. 061 failed 4 of 11 runs here. slow_reader stops reading before the
> checksums launcher waits, so it gets killed.

Right: pg_disable_data_checksums() returns before the launcher emits
its barriers. 061 passed 11/11 here, but holding the launcher at
datachecksumsworker-launcher-delay until the reader had blocked, v1's
loop got the reader terminated 2/2. v2 keeps reading until
data_checksums is off: 0/2.

Pinned to one CPU, a second race showed up: woken by the barrier's
signal, a backend blocked in ClientWrite on a Unix socket can still fit
one more send (16 kB more queued while psql wasn't reading), reach a
CHECK_FOR_INTERRUPTS() and absorb, so the first DROP did not wait. v2's
061 wakes each stuck session with pg_log_backend_memory_contexts()
until it no longer logs. 061 then passed 11/11 normally and 11/11
pinned to one CPU. The mutants (no grace period, SIGINT, no kill, no
ClientWrite check) all fail it, without hanging now.

> 3. shouldTerminateBarrierStraggler() recheck pss_barrierGeneration
> under pss_mutex? because it can kill a new backend in the same slot.

Yes. Reproduced with gdb: with the waiter stopped on entry to
TerminateBarrierStraggler(), the stuck session exits and a new session,
also in ClientWrite, takes the same slot; v1 then terminated the new
one, 5/5. v2 reads pss_pid and pss_barrierGeneration together under
pss_mutex and skips the slot once the generation is reached, since a
new process starts at the current one: 0/5 (3/3 again with the recheck
removed). 061 can't reach that window; I can turn it into an injection
point test if you think it's worth it.

make check, the recovery suite (857 tests, including 061) and
test_checksums with checksum_extended pass on master f2edf5dd00d.

Regards,
Manu

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Oct 22, 2026 at 10:42 AM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi Amit, Shveta,
>
> > After a configuration reload, an existing session picks up the new
> > value when its client sends the next query.
>
> IIUC the description is correct: a backend process reloads the configuration in
> the main loop, and assign hook can be called there. But yours are also OK if you
> think it's too detail.
>

I am also okay with both but would prefer mine as that appears clear
and succinct.

-- 
With Regards,
Amit Kapila.


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shveta malik <shveta.malik@gmail.com>
Дата:
Вложения:
On Thu, Oct 22, 2026 at 11:45 AM Amit Kapila  wrote:
>
> On Thu, Oct 22, 2026 at 10:42 AM Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > Hi Amit, Shveta,
> >
> > > After a configuration reload, an existing session picks up the new
> > > value when its client sends the next query.
> >
> > IIUC the description is correct: a backend process reloads the configuration in
> > the main loop, and assign hook can be called there. But yours are also OK if you
> > think it's too detail.
> >
>
> I am also okay with both but would prefer mine as that appears clear
> and succinct.

Okay, PFA the patch with comments addressed.

thanks
Shveta

RE: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

> Okay, PFA the patch with comments addressed.

```
+     replica that has a valid (not invalidated) logical
```

We have already had a term "valid replication slot", in protocol.sgml. So I think
the part () may not be needed. Please use v3 if it's acceptable.

FYI: I confirmed the patch can be applied atop HEAD and REL_19_STABLE.

Best regards,
Hayato Kuroda
FUJITSU LIMITED

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

On Thu, Oct 22, 2026 at 2:29 PM shveta malik  wrote:
>
> On Thu, Oct 22, 2026 at 11:45 AM Amit Kapila  wrote:
> >
> > On Thu, Oct 22, 2026 at 10:42 AM Hayato Kuroda (Fujitsu)
> >  wrote:
> > >
> > > Hi Amit, Shveta,
> > >
> > > > After a configuration reload, an existing session picks up the new
> > > > value when its client sends the next query.
> > >
> > > IIUC the description is correct: a backend process reloads the configuration in
> > > the main loop, and assign hook can be called there. But yours are also OK if you
> > > think it's too detail.
> > >
> >
> > I am also okay with both but would prefer mine as that appears clear
> > and succinct.
>
> Okay, PFA the patch with comments addressed

The doc patch looks good to me. One minor nit:
"valid (not invalidated)" feels a bit redundant, as "valid" alone seems
sufficient.

Best Regards,
Zhijie Hou


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

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

On Thu, Oct 22, 2026 at 2:53 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> Hi Shveta,
>
> > Okay, PFA the patch with comments addressed.
>
> ```
> +     replica that has a valid (not invalidated) logical
> ```
>
> We have already had a term "valid replication slot", in protocol.sgml. So I think
> the part () may not be needed. Please use v3 if it's acceptable.
>
> FYI: I confirmed the patch can be applied atop HEAD and REL_19_STABLE.

Oh, I missed this message and posted a similar comment, sorry for that.

This version looks good to me.

Best Regards,
Zhijie Hou


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Thu, Oct 22, 2026 at 12:23 PM Hayato Kuroda (Fujitsu)
 wrote:
>
> > Okay, PFA the patch with comments addressed.
>
> ```
> +     replica that has a valid (not invalidated) logical
> ```
>
> We have already had a term "valid replication slot", in protocol.sgml. So I think
> the part () may not be needed. Please use v3 if it's acceptable.
>

LGTM. Sawada-San, feel free to review and push.

-- 
With Regards,
Amit Kapila.


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Amit,

> If we anyway would like to implement killing of connections that
> didn't absorb barriers then do we even need v6. I am slightly hesitant
> about v6 because it adds more assumptions in the code like which
> processes can have stale cache.

With the docs note for 19 settled, I'd like to bring this back to
HEAD. v2 [1] implements option (2): once a barrier wait exceeds
procsignal_barrier_timeout (default 30s), a client backend or WAL
sender that hasn't absorbed it and is blocked in ClientWrite gets
SIGTERM. Nothing else is signaled.

To answer your question with numbers, I ran the same scenarios on
master (f2edf5dd00d) with three builds: unpatched, v6, and v2 (timeout
2 s for these runs), 3 runs per cell. The stuck backend is a session
whose client is alive but has stopped reading. The full matrix, with
how each row was measured, and the scripts to reproduce every row are
attached.

Promotion (failover slot synced from the start, local slot, slot
created or toggled during recovery, crash restart before promotion):
master hung every time, v6 promoted in 9-26 ms, v2 after its timeout.

Replay stuck behind the backend, then the primary creates its first
logical slot: master and v6 stalled replay for the whole 15 s, v2
caught up after its timeout.

On a primary (enabling checksums, DROP DATABASE of another database,
DROP DATABASE with a walsender in a base backup): master and v6 hung,
v2 finished after its timeout.

Controls (idle, pg_sleep, a slow reader, a sync rep waiter, a paused
COPY FROM STDIN) behaved the same in all three builds, and none was
terminated in 45 runs.

So v2 alone clears every case here, including the ones v6 doesn't
reach, and doesn't depend on v6. What v6 adds is speed: without it, a
promotion behind such a backend waits for the whole timeout. On the
stale caches, I read XLogLogicalInfo of every standby process with gdb
before and after pg_promote(). With the status on since startup,
master had the same five processes stale before promotion
(checkpointer, background writer, both io workers, startup) in every
run, and v6 had none, also after a crash restart. After promotion
nothing was stale in any build. That is evidence for these setups, not
a proof.

Two limits of v2. It doesn't change recovery conflicts: as Sawada-san
noted, a backend in ClientWrite doesn't service them, and with v1
replay still stopped behind one, 3/3; v2 only narrows whom it
terminates. And a session sending one large value to a slow client
for longer than the timeout is terminated too (documented in
config.sgml).

Reviews of v2 would be very welcome.

Regards,
Manu

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

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Manu,

Thanks for the quick update and the gdb repro. I tested v2 and it
works for all three points.

One case is still stuck. A backend can block while it sends an
error. It holds interrupts then, so SIGTERM does nothing. v2 still
logs "terminating process". That can confuse users.

For the large value case, maybe add a send counter in PGPROC. If the
counter moves during the timeout, the client is slow but alive. I
have not tried this.

Thanks,
Shihao

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Shihao,

Thanks for testing it again.
v3 is attached, on today's master.

On Thu, Oct 22, 2026 at 9:12 PM shihao zhong
 wrote:
> One case is still stuck. A backend can block while it sends an error.
> It holds interrupts then, so SIGTERM does nothing. v2 still logs
> "terminating process". That can confuse users.

Reproduced with SELECT repeat('x', 30000000)::int from a client that
does not read: the backend sits in EmitErrorReport() -> ... ->
secure_write() with InterruptHoldoffCount = 1 and wait event
ClientWrite. After pg_terminate_backend() it was still there 10 s
later, 3/3 on master and on v2, and v2 logged "terminating process".

I found no clean way to tell from another process that interrupts are
held: InterruptHoldoffCount is process-local, and publishing it would
add a shared memory store to every HOLD/RESUME_INTERRUPTS(). SIGQUIT
and SIGKILL do release it, but cause a crash restart. So v3 does not
release it; it stays stuck as on master. What changes is the log. v3
says "requesting termination of process N ...", and if N is still
there at the next wakeup, "process N has not exited 5005 ms after its
termination was requested", with a DETAIL saying that it is blocked
sending to its client and will exit once the client reads or the
connection is closed. DROP DATABASE keeps waiting, and the backend
exits within milliseconds once the client reads or goes away. On TCP,
tcp_user_timeout = 5s also released it, after 5.18 s, with no
restart. The case is in 061 now.

> For the large value case, maybe add a send counter in PGPROC. If the
> counter moves during the timeout, the client is slow but alive. I
> have not tried this.

It works. v3 adds clientSendCount to PGPROC, and
internal_flush_buffer() bumps it after each completed send (a load and
a store by the owner, no lock). The waiter samples all the counts when
it starts sleeping, and terminates a ClientWrite straggler only once it
has gone procsignal_barrier_timeout without completing a send.

With 100 MB to a client reading at 2 MB/s and the default 30 s, the
session now survives and DROP waits for the value: 51.26 s (master
50.97 s; v2 terminated it at 30.07 s). The stuck cases still clear
after 2 s: I redid the coverage matrix from my mail to Amit with v3,
and no cell changes and no control was terminated. One correction to
that matrix: the slow reader control is bimodal, DROP finishing in
about 7 ms or about 0.9 s depending on where the socket is, on master
as well; it is never terminated.

A client that reads slowly enough does not move the count either: a
send only completes once the kernel has freed a sizable part of the
socket's send buffer. With a 5 s timeout, clients reading 1 byte every
3 s, 1 kB/s and 16 kB/s were terminated at the timeout, while one at
256 kB/s kept the count moving. So a live but very slow client, for
example on a poor mobile link, can still be terminated, as with v2.
Where that matters, procsignal_barrier_timeout can be raised, or set
to 0 to disable this.

In the other direction, a client reading just enough could hold the
barrier forever, so v3 also terminates a session that is still sending
once the whole wait reaches 10 times procsignal_barrier_timeout (5 min
by default). At 256 kB/s with a 5 s timeout it was terminated at
50.0 s. The factor is arbitrary; I can change it or make it a separate
setting.

The counter costs nothing measurable: pgbench -M prepared, 16 runs per
build in alternating order, v3/master was 1.007 for -S, 0.999 for one
100 kB value and 0.995 for 1000 rows, each with a 95% CI around 1.

The commit message now has Suggested-by for you.

Regards,
Manu

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello hackers,

23.10.2026 08:05, Manu wrote:
One case is still stuck. A backend can block while it sends an error.
It holds interrupts then, so SIGTERM does nothing. v2 still logs
"terminating process". That can confuse users.
Reproduced with SELECT repeat('x', 30000000)::int from a client that
does not read: the backend sits in EmitErrorReport() -> ... ->
secure_write() with InterruptHoldoffCount = 1 and wait event
ClientWrite. After pg_terminate_backend() it was still there 10 s
later, 3/3 on master and on v2, and v2 logged "terminating process".

I'm sorry for being late to this train and maybe a bit off-topic, but I'd
like to share one more way to have a backend blocked on connection due to
a barrier not absorbed:
echo "
synchronous_standby_names = 'nosuch'
synchronous_commit = local
authentication_timeout = 10s
log_connections = on
" > $PGDATA/postgresql.auto.conf

pg_ctl -l server.log -w start
psql -c "SHOW procsignal_barrier_timeout"
psql -c "CREATE DATABASE victim"
psql -c "SET synchronous_commit = remote_apply" -c "CREATE TABLE t ()" &
sleep 1
psql -c "DROP DATABASE victim WITH (FORCE)" &
sleep 1
psql -c "VACUUM FULL pg_subscription" &
sleep 2
psql -c "VACUUM FULL pg_authid"

echo "Test connection..."
date
timeout 60 psql -c "SELECT 1" || echo "Connection timeout"
date
pg_ctl -m fast stop
wait

The script produces:
 procsignal_barrier_timeout
----------------------------
 30s
(1 row)

CREATE DATABASE
SET
VACUUM
Test connection...
Fri Oct 23 12:21:18 PM EEST 2026
Connection timeout
Fri Oct 23 12:22:18 PM EEST 2026

2026-10-23 12:21:18.412 EEST [3519423] LOG:  connection received: host=[local]
2026-10-23 12:21:18.413 EEST [3519423] LOG:  connection authenticated: user="law" method=trust (.../pg_hba.conf:117)
2026-10-23 12:21:18.413 EEST [3519423] LOG:  connection authorized: user=law database=postgres application_name=psql
2026-10-23 12:21:19.417 EEST [3519423] LOG:  process 3519423 still waiting for AccessShareLock on relation 6100 of database 0 after 1000.027 ms
2026-10-23 12:21:19.417 EEST [3519423] DETAIL:  Process holding the lock: 3519408. Wait queue: 3519413, 3519423.
2026-10-23 12:21:19.417 EEST [3519423] CONTEXT:  waiting for AccessShareLock on relation 6100 of database 0
2026-10-23 12:21:20.418 EEST [3519408] LOG:  still waiting for backend with PID 3519403 to accept ProcSignalBarrier
2026-10-23 12:21:20.418 EEST [3519408] STATEMENT:  DROP DATABASE victim WITH (FORCE)
2026-10-23 12:21:25.419 EEST [3519408] LOG:  still waiting for backend with PID 3519403 to accept ProcSignalBarrier
2026-10-23 12:21:25.419 EEST [3519408] STATEMENT:  DROP DATABASE victim WITH (FORCE)
...
2026-10-23 12:22:10.441 EEST [3519408] LOG:  still waiting for backend with PID 3519403 to accept ProcSignalBarrier
2026-10-23 12:22:10.441 EEST [3519408] STATEMENT:  DROP DATABASE victim WITH (FORCE)
2026-10-23 12:22:15.268 EEST [3519536] LOG:  process 3519536 still waiting for AccessShareLock on relation 6100 of database 0 after 1000.047 ms
2026-10-23 12:22:15.268 EEST [3519536] DETAIL:  Process holding the lock: 3519408. Wait queue: 3519413, 3519423, 3519536.
2026-10-23 12:22:15.268 EEST [3519536] CONTEXT:  waiting for AccessShareLock on relation 6100 of database 0
2026-10-23 12:22:15.447 EEST [3519408] LOG:  still waiting for backend with PID 3519403 to accept ProcSignalBarrier
2026-10-23 12:22:15.447 EEST [3519408] STATEMENT:  DROP DATABASE victim WITH (FORCE)
2026-10-23 12:22:18.412 EEST [3519386] LOG:  received fast shutdown request


That is, with v3 applied, a backend still gets stuck.

Best regards,
Alexander Lakhin
Databricks

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Manu <manuelreyesbravo@gmail.com>
Дата:
Вложения:
Hi Alexander,

Thanks for the script, it reproduced here as is.

On Fri, Oct 23, 2026 at 1:00 PM Alexander Lakhin
 wrote:
> That is, with v3 applied, a backend still gets stuck.

It does, and so does master: your script gives the same result on
master, 18.6 and 17.11, 3 runs out of 3 on each. DROP DATABASE waits
for the backend in SyncRepWaitForLSN(), which holds interrupts and
never absorbs the barrier. v1 terminated such a session, which shihao
pointed out; since v2 it is left alone, because its transaction has
already committed locally. The login blocks behind the two VACUUM
FULLs queued on DROP DATABASE's lock on pg_subscription.

The attached v5 is split in two. 0001 fixes your case on its own and
has no new GUC: it absorbs the barrier inside the sync-rep wait (and
in a paused COPY FROM STDIN), but only for barrier types that do
nothing commit does not already do after its commit record. The
commit message has the details, including io_method=io_uring. 0002
is the timeout part from before, on top of it.

With 0001 alone and your script, DROP DATABASE completes in 41-83 ms
and the test login in under 10 ms, while the waiter keeps waiting for
the standby; once synchronous_standby_names is reset, its COMMIT
returns without a WARNING. With a paused COPY instead, DROP completes
in under 65 ms and the COPY goes on once the client sends the rest.
Both cases are in 0001's own test, 061.

In the coverage matrix, 0001 alone clears only the sync-rep and COPY
controls, in 8-9 ms; the ClientWrite rows stay stuck as on master.
With 0002 on top they clear after the timeout as with v3, and no
control session is terminated.

Regards,
Manu

Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Thu, Oct 22, 2026 at 2:07 AM Amit Kapila  wrote:
>
> On Thu, Oct 22, 2026 at 12:23 PM Hayato Kuroda (Fujitsu)
>  wrote:
> >
> > > Okay, PFA the patch with comments addressed.
> >
> > ```
> > +     replica that has a valid (not invalidated) logical
> > ```
> >
> > We have already had a term "valid replication slot", in protocol.sgml. So I think
> > the part () may not be needed. Please use v3 if it's acceptable.
> >
>
> LGTM. Sawada-San, feel free to review and push.

Thank you for creating and reviewing the patch. The patch looks good
to me too. I'll push it on early next week.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


Re: [PG19] Promotion hangs behind a backend blocked on a stuck client

От:
Masahiko Sawada <sawada.mshk@gmail.com>
Дата:
On Fri, Oct 23, 2026 at 10:17 PM Masahiko Sawada  wrote:
>
> On Thu, Oct 22, 2026 at 2:07 AM Amit Kapila  wrote:
> >
> > On Thu, Oct 22, 2026 at 12:23 PM Hayato Kuroda (Fujitsu)
> >  wrote:
> > >
> > > > Okay, PFA the patch with comments addressed.
> > >
> > > ```
> > > +     replica that has a valid (not invalidated) logical
> > > ```
> > >
> > > We have already had a term "valid replication slot", in protocol.sgml. So I think
> > > the part () may not be needed. Please use v3 if it's acceptable.
> > >
> >
> > LGTM. Sawada-San, feel free to review and push.
>
> Thank you for creating and reviewing the patch. The patch looks good
> to me too. I'll push it on early next week.

Pushed.

Regards,

-- 
Masahiko Sawada
Amazon Web Services: https://aws.amazon.com


FAQ