Deadlock detector fails to activate on a hot standby replica
Deadlock detector fails to activate on a hot standby replica
Dear Hackers, The deadlock detection mechanism fails to activate when a deadlock occurs between startup and backend processes on a hot standby replica, resulting in unforeseen delays in the recovery. The deadlock may happen, when processing XLOG_HEAP2_PRUNE_* messages. Automatic resolution of deadlocks remains possible when reaching the specified max_standby_streaming_delay value, if it is set. Sometimes this value is set to -1 which disables this timeout. This issue appears consistently in versions 15 and later, when log_startup_progress_interval was introduced. The startup process notify the conflicting backend process to check for deadlocks when deadlock_timeout is reached. It works in general, but doesn't work in some scenarios. If to set deadlock_timeout to be greater than log_startup_progress_interval, the deadlock detector will never be triggered, but the startup process will wait for the the deadlock resolution until max_standby_streaming_delay timeout is reached (if it is set). It is reproducible with the attached tap test 900_startup_backend_deadlock.pl. To reproduce, just copy this test into src/test/recovery/t and run it. The problem seems to appear in timeout.c functionality, or in ResolveRecoveryConflictWithBufferPin depending on how to understand the semantics of the timeout api. The root cause - handle_sig_alarm (SIGALRM handler) may be called when no active timeouts are reached. It sets the process latch unconditionally, this, waking up the process. The problem may be in an optimization when setitimer may not be called, when the closest final time of active timeouts is greater than already set time. The SIGARLM handler may be called when no active timeouts are reached. Below is the scenatio when deadlock timeout is not activated: (1) The startup process sets startup_progress_interval to 1000ms and continues with the recovery of the received WAL. (2) When processing XLOG_HEAP2_PRUNE_*, the startup process tries to lock the buffer using LockBufferForCleanup that calls ResolveRecoveryConflictWithBufferPin. The deadlock of startup and backend processes is possible (see src/test/recovery/t/031_recovery_conflict.pl test). Image, we come to the deadlock. (3) ResolveRecoveryConflictWithBufferPin sets deadlock timeout to 3000 ms and waits for buffer pin to be unlocked or for the timeout using ProcWaitForSignal. (4) When the startup process in ProcWaitForSignal, handle_sig_alarm is called because startup_progress_interval is reached (the timeout was disabled, but the real timer was not reset). It sets the process latch unconditionally and reschedules timers - the current active timer will be rescheduled in ~2000 ms in our case, if XLOG_HEAP2_PRUNE_ was received right after step (1). It means, the next call of handle_sig_alarm will be in 2000 ms. (5) ResolveRecoveryConflictWithBufferPin continues after ProcWaitForSignal, disables all active timeouts and returns. LockBufferForCleanup sees that the buffer is still locked and calls ResolveRecoveryConflictWithBufferPin again. (6) ResolveRecoveryConflictWithBufferPin sets deadlock timeout to 3000 ms, but the real timer is not changed - it will be triggered in 2000 ms. And, then, wits for timeout in ProcWaitForSignal. (7) The SIGALRM handler (handle_sig_alarm) is called in 2000 ms, it sets the process latch, but the deadlock timeout is not yet reached. Once, it is not reached, the startup process will not signal to the conflicting backend to check for deadlocks. ResolveRecoveryConflictWithBufferPin resets all timeouts again and transfer control to LockBufferForCleanup. The buffer is still locked, it calls ResolveRecoveryConflictWithBufferPin again. (8) And so on... The startup process will run forever. It will loop in LockBufferForCleanup without any progress in recovery. The problem is here - if an unforeseen SIGALRM is received before deadlock timeout, it can lead to infinite loop in LockBufferForCleanup. I see a couple of possible solutions: 1. Call seitimer every time when needed (see the demo patch [1]). 2. Redesign LockBufferForCleanup logic to support the cases when SIGALRM may come unexpectedly. 3. Call SetLatch in handle_sig_alarm only if some timeout is reached. The solution 1 is a simpler one, but it can not guarantee that some other functionaly will set a timeout and will affect LockBufferForCleanup. The solution 2 seems to be more robust, but it is harder to implement. Furthermore, I can not exclude some other places, where the timeout functionality is used in a wrong way. Solution 3 seems to be the simplest but there is an opinion, that any SIGALRM should wake up the process (set the latch). Any ideas? [1] 900_startup_backend_deadlock.pl [2] 0001-Fix-deadlock-detector-activation-in-startup-process.patch
Re: Deadlock detector fails to activate on a hot standby replica
Dear Hackers, I would like to propose a patch that fixes the problem, which has the roots in the possibility of spontaneous SIGALRM signals when waiting for some timeouts. The idea of the patch - ignore spontaneous SIGALRM signals and continue waiting for expected timeouts or buffer unpinning by the conflicting backend. This patch is not a final version. I plan to add a tap-test for this case. I'm in doubt to put the calls of some page buffer specific functions into ResolveRecoveryConflictWithBufferPin (standby.c), but otherwise we have to do more changes in LockBufferForCleanup and ResolveRecoveryConflictWithBufferPin. I also think, we have to add some description of the found problem in timeout.c, because the implemented optimization of setitimer calls leads to some not evident consequences. The optimization seems to be implemented in the commit: 09cf1d52267644cdbdb734294012cf1228745aaa With best regards, Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
Dear Fujii Masao, Thank you for the review of the patch. Based on your comments I propose a new version of the patch. > +#include "storage/buf_internals.h" > This include should be placed in alphabetical order. I removed the include of the header file. I'm not sure, that it is a good way to expose buffer internals here. Instead, I implemented a new function BufferGetRefCount to be used in standby.c. > + uint32 buf_refcount = BUF_STATE_GET_REFCOUNT(buf_state); > > + if (buf_refcount > 1) > + continue; > > Wouldn't it be better to check explicitly whether we're still the waiter, > instead of using BUF_STATE_GET_REFCOUNT()? > > (buf_state & BM_PIN_COUNT_WAITER) != 0 && > bufHdr->wait_backend_pgprocno == MyProcNumber This is a precondition for the ResolveRecoveryConflictWithBufferPin function that the current process should be a waiter process. See LockBufferForCleanup where this state is set before the call of ResolveRecoveryConflictWithBufferPin. I believe, there is no sense to check the waiter state because it doesn't change in this function. Instead, I think, it is enough to just check for refcount. One of the suggestions is to add an assert to check that the current process is a waiter process, but I'm not sure about it. Let me know please if I missed anything. > The current control flow in the loop feels a bit hard to follow. > Would something like the following be simpler? I reorganized the control flow as well. I also added a new tap-test as a part of the patch. I did some changes in the tap test to make it stable. Let me know, please, if it should be in a separate commit. With best regards, Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Mon, May 25, 2026 at 11:20 PM Vitaly Davydov
wrote:
>
> Dear Fujii Masao,
>
> Thank you for the review of the patch. Based on your comments I propose
> a new version of the patch.
Thanks for updating the patch!
+ if (got_standby_delay_timeout)
+ SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
+ else if (got_standby_deadlock_timeout)
+ {
Shouldn't we break out of the loop when either got_standby_delay_timeout or
got_standby_deadlock_timeout becomes true? Otherwise, the loop continues with
those flags still set, which could cause SendRecoveryConflictWithBufferPin() to
be called unnecessarily in the subsequent cycles.
+ if (BufferGetRefCount(buffer) <= 1)
Should this be "BufferGetRefCount(buffer) == 1" instead? I don't think
BufferGetRefCount(buffer) should ever return 0 here. If that's correct,
would it make sense to explicitly detect that case, for example:
-----------------
uint32 refcount = BufferGetRefCount(buffer);
Assert(refcount > 0);
if (refcount == 0)
elog(ERROR, "buffer refcount dropped to zero while waiting for
cleanup lock");
if (refcount == 1)
break;
-----------------
> I also added a new tap-test as a part of the patch. I did some changes in the
> tap test to make it stable. Let me know, please, if it should be in a separate
> commit.
Do we really need a new TAP test file for this? We already have
a startup/backend deadlock test in t/031_recovery_conflict.pl. Extending
the deadlock section there to cover this test case seems simpler and easier to
follow than introducing a new t/053_* test.
Regards,
--
Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
On Wed, Jun 10, 2026 at 1:18 AM Vitaly Davydov wrote: > > On 6/5/26 14:58, Fujii Masao wrote: > > I've updated the patch based on these comments. > > Attached is the latest version. > > > > I removed the TAP test from this patch for now. I'll consider adding > > a test for this separately later. > > Thank you again for your assistance. I agree with the code changes you've > proposed. I've updated 031_recovery_conflict.pl to include the deadlock > test, instead of creating a separate TAP test. The attached patch contains > these changes in its second commit. I've kept the patch version as v3 since > the original fix remains unchanged; this update only adds new tests. Thanks for updating the regression test patch! I reviewed both patches and found a few issues, so I fixed them and attached updated v4 versions. For v3-0001, when the startup process wakes up from ProcWaitForSignal() and finds the pin count is still not 1, it waits again. However, before waiting again, it must set BM_PIN_COUNT_WAITER again. Otherwise, a backend releasing the pin cannot signal the startup process because the flag was already cleared. For example: 1. Backend A releases the pin, signals the startup process, and clears BM_PIN_COUNT_WAITER. 2. The startup process wakes up from ProcWaitForSignal(). 3. Before it rechecks the pin count, backend B acquires a pin. 4. The startup process sees the pin count is still 2. 5. The startup process waits again. At step 5, BM_PIN_COUNT_WAITER is already cleared, so backend B will not signal the startup process when releasing the pin. This race is unlikely in practice, but it is still possible. So in v4-0001, I fixed this by re-registering the startup process as the waiter before waiting again. For v3-0002, the two deadlock tests contained very similar scenarios. I think it's simpler to move the common logic into a shared subroutine. So in v4-0002, I added a helper routine for testing the deadlock between the startup process and a backend, and both tests now use it. Could you review the v4 patches? Regards, -- Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Fri, Jun 12, 2026 at 3:00 PM Vitaly Davydov wrote: > > Dear Fujii Masao, > > On 6/10/26 11:42, Fujii Masao wrote: > > Could you review the v4 patches? > > I've got the issue with BM_PIN_COUNT_WAITER. The origin of the issue is that > the other backend resets the flag before sending the notification (signal) > to the waiter. I agree with your changes where this flag is set again. > > I would like to propose BufferIsReadyForCleanup function name instead of > BufferShouldWaitForCleanupLockForStandby (and change the returning value > semantics). There are other possible alternatives: BufferIsReadyForWriting, > BufferIsReadyForExclusiveAccess or something else. The code will look like > below: > > if (BufferIsReadyForCleanup(bufid + 1)) > break; Okay. > I've also found strange email in the commit messages like below: > Author: masao.fujii That's my mistake. Sorry. I'll fix it in the next version of the patch. > I tried the modified 031 tap test but I do not see that it reproduces the issue > on the version without the fix. My version of 031 tap test hangs without the > fix. I haven't yet reviewed the tap test code at the moment, but I'm going to do > it as well. I retried the modified 031 TAP test on my side without the fix, and the test actually passed, so the test did not reliably reproduce the issue. However, after increasing deadlock_timeout to 10s, the test hung without the fix as expected, while it passed with the fix. Based on this, I suspect the behavior depends on timing interactions between deadlock_timeout and SIGALRM delivery caused by log_startup_progress_interval. My test changes may simply have altered the timing of those SIGALRM deliveries. Also, the current test assumes that log_startup_progress_interval is effective during standby WAL replay. But as discussed in [1], that assumption may actually be wrong. It seems to work today, but that could just be accidental and might change in the future. So I think we should consider a testing approach that does not depend on that assumption. At the moment, the only alternative I can think of is to send SIGALRM periodically to the startup process directly from the test, though I'm not sure that's a good approach either... > Below one more note that is not directly related to the fix but may probably > improve the code readability. I agree that some refactoring along those lines should be possible. However, for backpatching to older branches, I'd prefer to avoid more code churn than necessary for the bug fix itself. So I think it would be better to commit the bug fix first, and then consider a refactoring version separately for v20dev. Regards, [1] https://www.postgresql.org/message-id/flat/CAHGQGwFJixYTymPZ6dwOO-G0VdjO1AgZTma6CtJgc0Ptxfz3BA%40mail.gmail.com -- Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
On Fri, Jun 12, 2026 at 6:23 PM Fujii Masao wrote: > > On Fri, Jun 12, 2026 at 3:00 PM Vitaly Davydov wrote: > > > > Dear Fujii Masao, > > > > On 6/10/26 11:42, Fujii Masao wrote: > > > Could you review the v4 patches? > > > > I've got the issue with BM_PIN_COUNT_WAITER. The origin of the issue is that > > the other backend resets the flag before sending the notification (signal) > > to the waiter. I agree with your changes where this flag is set again. > > > > I would like to propose BufferIsReadyForCleanup function name instead of > > BufferShouldWaitForCleanupLockForStandby (and change the returning value > > semantics). There are other possible alternatives: BufferIsReadyForWriting, > > BufferIsReadyForExclusiveAccess or something else. The code will look like > > below: > > > > if (BufferIsReadyForCleanup(bufid + 1)) > > break; > > Okay. I've updated the patch accordingly. > Also, the current test assumes that > log_startup_progress_interval is effective during standby WAL replay. > But as discussed in [1], that assumption may actually be wrong. It > seems to work today, but that could just be accidental and might > change in the future. So I think we should consider a testing approach > that does not depend on that assumption. > > At the moment, the only alternative I can think of is to send SIGALRM > periodically to the startup process directly from the test, though I'm > not sure that's a good approach either... I still haven't come up with a good way to test this without depending on log_startup_progress_interval being active during standby WAL replay. Even so, I think the fix is still worth committing because it addresses a real issue. So how about committing 0001 patch first, even without a regression test? Regards, -- Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
От:
Vitaly Davydov <v.davydov@postgrespro.ru>
Дата:
Dear Fujii Masao, Thank you for the v5 patch. It looks good for me. > I still haven't come up with a good way to test this without depending on > log_startup_progress_interval being active during standby WAL replay. > Even so, I think the fix is still worth committing because it addresses > a real issue. So how about committing 0001 patch first, even without > a regression test? I have no objections to commit the v5 patch without the tap-test. Once, it is the bug fix, should we prepare the fix for other major branches? I'm ready to prepare the patches based on the v5 version. I looked at the tap test and found the reason why the test doesn't reproduce the issue. The function adjust_conf in Cluster.pm changes the existing parameter but doesn't add new new parameter to the configuration file if it is missed. It doesn't report any errors as well. If to use the append_conf method the test starts to reproduce the issue pretty stable, because the parameter is actually added to the configuration file. One more note - in my original test I set autovacuum = off for all nodes, but in modified 031 test autovacuum seems to be enabled. Disabling autovacuum may make the test more stable. With best regards, Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Thu, Jun 18, 2026 at 10:11 PM Vitaly Davydov wrote: > > Dear Fujii Masao, > > Thank you for the v5 patch. It looks good for me. Thanks for the review! > I have no objections to commit the v5 patch without the tap-test. Once, it is > the bug fix, should we prepare the fix for other major branches? I'm ready to > prepare the patches based on the v5 version. Yes, it's really helpful if you prepare the patches for stable versions. > I looked at the tap test and found the reason why the test doesn't reproduce > the issue. The function adjust_conf in Cluster.pm changes the existing > parameter but doesn't add new new parameter to the configuration file if it is > missed. It doesn't report any errors as well. If to use the append_conf method > the test starts to reproduce the issue pretty stable, because the parameter is > actually added to the configuration file. > > One more note - in my original test I set autovacuum = off for all nodes, but > in modified 031 test autovacuum seems to be enabled. Disabling autovacuum may > make the test more stable. Thanks for the analysis! Regards, -- Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
От:
Vitaly Davydov <v.davydov@postgrespro.ru>
Дата:
Dear Fujii Masao, All
While working on porting the patch to other majors, I've found that, the code
in RegisterPinCountWaiter() (see below) should be improved because it doesn't
unlock the bufHdr when the error is raised, as in LockBufferForCleanup().
I guess it works, but it keeps the locks a bit longer.
RegisterPinCountWaiter v5 patch code:
...
if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
bufHdr->wait_backend_pgprocno != MyProcNumber)
elog(ERROR, "multiple processes attempting to wait for pincount 1");
RegisterPinCountWaiter proposed changes:
...
if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
bufHdr->wait_backend_pgprocno != MyProcNumber)
{
UnlockBufHdr(bufHdr);
elog(ERROR, "multiple processes attempting to wait for pincount 1");
}
What do you think?
With best regards,
Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
Dear Fujii Masao I've prepared patches of v6 for other majors. I hope, it will help. I will also think of a better approach for tap-test patch as well. With best regards, Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
От:
Fujii Masao <masao.fujii@gmail.com>
Дата:
On Thu, Jun 25, 2026 at 12:16 AM Vitaly Davydov wrote: > > Dear Fujii Masao > > I've prepared patches of v6 for other majors. I hope, it will help. Thanks for the patches for the stable branches! I noticed that you added "buf_state &= ~BM_PIN_COUNT_WAITER;" to BufferIsReadyForCleanup(). Could you tell me why that's necessary? My understanding was that LockBufferForCleanup() is responsible for clearing that flag, so I didn't think it was needed here. But if it is necessary, I'd like to make the same change in master as well, to keep the code as consistent as possible between master and the stable branches. > I will also think of a better approach for tap-test patch as well. Thanks! Regards, -- Fujii Masao
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
Hi Fujii-san, Vitaly, On Thu, Jun 25, 2026 at 8:14 PM Fujii Masao wrote: > > On Thu, Jun 25, 2026 at 12:16 AM Vitaly Davydov > wrote: > > > > Dear Fujii Masao > > > > I've prepared patches of v6 for other majors. I hope, it will help. Thanks for working on this. I haven't looked into the patch in detail yet. The overall direction seems good to me. Here are two comments on the first look: 1) It looks that this patch is doing some refactoring around LockBufferForCleanup. The part being touched seems flaky itself on HEAD, should we fix the issue in the buffer side first? [1] > Thanks for the patches for the stable branches! > > I noticed that you added "buf_state &= ~BM_PIN_COUNT_WAITER;" to > BufferIsReadyForCleanup(). Could you tell me why that's necessary? My > understanding was that LockBufferForCleanup() is responsible for > clearing that flag, so I didn't think it was needed here. > > But if it is necessary, I'd like to make the same change in master as > well, to keep the code as consistent as possible between master and > the stable branches. 2) buf_state &= ~BM_PIN_COUNT_WAITER in stable versions seems not necessary to me as LockBufferForCleanup will handle the clearing for us. [1] https://www.postgresql.org/message-id/flat/7685519a-0bf9-4e17-93ca-7e3aa10fa29c%40gmail.com -- Regards, Xuneng Zhou HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
Hi Fujii-san, Xuneng Zhou, > 1) It looks that this patch is doing some refactoring around > LockBufferForCleanup. The part being touched seems flaky itself on > HEAD, should we fix the issue in the buffer side first? [1] Thank you for mentioning it. It seems, there is a conflict with the another patch due to the introduction of RegisterPinCountWaiter function, that can not be resolved automatically. I'm ok to wait for the conflicting fix to be released. It seems, our patch should be reconsidered after the conflicting patch release. > 2) buf_state &= ~BM_PIN_COUNT_WAITER in stable versions seems not > necessary to me as LockBufferForCleanup will handle the clearing for > us. It seems it was my mistake when I resolved conflicts when cherry-picking the changes from other branches. I removed this line in my recent v 6.1 attached patches. Thank you for catching it. With best regards, Vitaly
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
On Fri, Jun 26, 2026 at 5:31 PM Vitaly Davydov wrote:
>
> Hi Fujii-san, Xuneng Zhou,
>
> > 1) It looks that this patch is doing some refactoring around
> > LockBufferForCleanup. The part being touched seems flaky itself on
> > HEAD, should we fix the issue in the buffer side first? [1]
>
> Thank you for mentioning it. It seems, there is a conflict with
> the another patch due to the introduction of RegisterPinCountWaiter
> function, that can not be resolved automatically. I'm ok to wait for
> the conflicting fix to be released. It seems, our patch should be
> reconsidered after the conflicting patch release.
OK.
> > 2) buf_state &= ~BM_PIN_COUNT_WAITER in stable versions seems not
> > necessary to me as LockBufferForCleanup will handle the clearing for
> > us.
>
> It seems it was my mistake when I resolved conflicts when cherry-picking
> the changes from other branches. I removed this line in my recent v 6.1
> attached patches. Thank you for catching it.
Thanks.
Here are some additional comments after further review:
3) should we let RegisterPinCountWaiter do less?
Currently, the function does a lot like:
RegisterPinCountWaiter()
{
check other waiter;
maybe unlock;
maybe elog(ERROR);
register;
unlock header;
}
We need to handle the unlock & elog for two
callers(BufferIsReadyForCleanup and LockBufferForCleanup) with
different needs, which could be error-prone sometimes.
+ Assert((buf_state & BM_PIN_COUNT_WAITER) == 0 ||
+ bufHdr->wait_backend_pgprocno == MyProcNumber);
+
+ if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
+ bufHdr->wait_backend_pgprocno != MyProcNumber)
+ {
+ UnlockBufHdr(bufHdr);
+ elog(ERROR, "multiple processes attempting to wait for pincount 1");
+ }
+
For example, unlocking the header lock only is sufficient for
BufferIsReadyForCleanup but not for LockBufferForCleanup as we hold
the extra content lock. For LockBufferForCleanup, the check seems
duplicated as we already did it before invoking this function. So to
make this work, we may need to distinguish these two callers.
Another potential issue of doing safe checks here is the order of
assert and error out:
In assert build, if the condition is true, then the header lock and
content lock would not be released properly. So we may need to adjust
the order.
This leads me to wonder -- would it be better to let this help
function to do less, like just for registration and let the callers to
handle others.
4) the already-expired standby-delay path may not wake new pin holders
If ltime has already passed, the patch sends
RECOVERY_CONFLICT_BUFFERPIN once before entering the loop, then waits
inside the new loop. What if another backend pins the buffer after
that broadcast?
Before the patch, this seems fine because we return to
BufferIsReadyForCleanup and enter the function
ResolveRecoveryConflictWithBufferPin to do the re-check of ltime and
send the conflict signal once more.
With the new inner loop, BufferIsReadyForCleanup() can re-register and
continue waiting, but no timeout is active and no new cancelling
request is sent. So recovery can continue waiting for a buffer pin
even though max_standby_*_delay has already expired.
To fix this, should we add an in-loop check: if ltime != 0 &&
GetCurrentTimestamp() >= ltime in here:
+ if (got_standby_delay_timeout)
+ {
+ SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
+ break;
+ }
5) The name of BufferIsReadyForCleanup seems broader than the actual protocol.
The function name seems not align with the intended use of it as the
comment suggested:
*
* This is only for the hot-standby path in LockBufferForCleanup(), via
* ResolveRecoveryConflictWithBufferPin(), after ProcWaitForSignal() returns.
* The caller must already be registered as the shared buffer's
* BM_PIN_COUNT_WAITER.
Would it be better to rename it to something like
RecheckCleanupLockPinWait or RecheckBufferPinWaiter?
--
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
On Sat, Jun 27, 2026 at 2:11 PM Xuneng Zhou wrote:
>
> On Fri, Jun 26, 2026 at 5:31 PM Vitaly Davydov wrote:
> >
> > Hi Fujii-san, Xuneng Zhou,
> >
> > > 1) It looks that this patch is doing some refactoring around
> > > LockBufferForCleanup. The part being touched seems flaky itself on
> > > HEAD, should we fix the issue in the buffer side first? [1]
> >
> > Thank you for mentioning it. It seems, there is a conflict with
> > the another patch due to the introduction of RegisterPinCountWaiter
> > function, that can not be resolved automatically. I'm ok to wait for
> > the conflicting fix to be released. It seems, our patch should be
> > reconsidered after the conflicting patch release.
>
> OK.
>
> > > 2) buf_state &= ~BM_PIN_COUNT_WAITER in stable versions seems not
> > > necessary to me as LockBufferForCleanup will handle the clearing for
> > > us.
> >
> > It seems it was my mistake when I resolved conflicts when cherry-picking
> > the changes from other branches. I removed this line in my recent v 6.1
> > attached patches. Thank you for catching it.
>
> Thanks.
>
> Here are some additional comments after further review:
>
> 3) should we let RegisterPinCountWaiter do less?
>
> Currently, the function does a lot like:
> RegisterPinCountWaiter()
> {
> check other waiter;
> maybe unlock;
> maybe elog(ERROR);
> register;
> unlock header;
> }
>
> We need to handle the unlock & elog for two
> callers(BufferIsReadyForCleanup and LockBufferForCleanup) with
> different needs, which could be error-prone sometimes.
>
> + Assert((buf_state & BM_PIN_COUNT_WAITER) == 0 ||
> + bufHdr->wait_backend_pgprocno == MyProcNumber);
> +
> + if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
> + bufHdr->wait_backend_pgprocno != MyProcNumber)
> + {
> + UnlockBufHdr(bufHdr);
> + elog(ERROR, "multiple processes attempting to wait for pincount 1");
> + }
> +
>
> For example, unlocking the header lock only is sufficient for
> BufferIsReadyForCleanup but not for LockBufferForCleanup as we hold
> the extra content lock. For LockBufferForCleanup, the check seems
> duplicated as we already did it before invoking this function. So to
> make this work, we may need to distinguish these two callers.
>
> Another potential issue of doing safe checks here is the order of
> assert and error out:
> In assert build, if the condition is true, then the header lock and
> content lock would not be released properly. So we may need to adjust
> the order.
>
> This leads me to wonder -- would it be better to let this help
> function to do less, like just for registration and let the callers to
> handle others.
>
> 4) the already-expired standby-delay path may not wake new pin holders
>
> If ltime has already passed, the patch sends
> RECOVERY_CONFLICT_BUFFERPIN once before entering the loop, then waits
> inside the new loop. What if another backend pins the buffer after
> that broadcast?
>
> Before the patch, this seems fine because we return to
> BufferIsReadyForCleanup and enter the function
> ResolveRecoveryConflictWithBufferPin to do the re-check of ltime and
> send the conflict signal once more.
>
> With the new inner loop, BufferIsReadyForCleanup() can re-register and
> continue waiting, but no timeout is active and no new cancelling
> request is sent. So recovery can continue waiting for a buffer pin
> even though max_standby_*_delay has already expired.
>
> To fix this, should we add an in-loop check: if ltime != 0 &&
> GetCurrentTimestamp() >= ltime in here:
>
> + if (got_standby_delay_timeout)
> + {
> + SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
> + break;
> + }
>
> 5) The name of BufferIsReadyForCleanup seems broader than the actual protocol.
>
> The function name seems not align with the intended use of it as the
> comment suggested:
>
> *
> * This is only for the hot-standby path in LockBufferForCleanup(), via
> * ResolveRecoveryConflictWithBufferPin(), after ProcWaitForSignal() returns.
> * The caller must already be registered as the shared buffer's
> * BM_PIN_COUNT_WAITER.
>
> Would it be better to rename it to something like
> RecheckCleanupLockPinWait or RecheckBufferPinWaiter?
I took another look at the patch. Here is an another thought:
6) We might want to be more elaborative on the commit message
From personal experience, the message seems a bit hard to follow if
one does not read the related discussion. I like your analysis of the
problem at the start of this thread [1]. Would it be sensible to
summarize and reuse some part of it for the message?
The motivation of this patch is to fix deadlock detector activation,
but the wait-loop change has a slightly broader benefit. It also
improves the standby timeout path indirectly by avoiding needless
timeout teardown and re-entry on unrelated wakeups, and by keeping any
already-fired timeout state until the loop handles it. Should we
mention this as an additional benefit, or even frame the message
broader like:
Fix the buffer-pin recovery-conflict wait loop.
[1] https://www.postgresql.org/message-id/44c24dcf-5710-410f-b1b6-d10b315f3d51%40postgrespro.ru
--
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
On Wed, Jul 1, 2026 at 11:58 PM Vitaly Davydov wrote: > > Dear Xuneng Zhou > > Thank you very much for such a comprehensive feedback. > > On 6/30/26 06:14, Xuneng Zhou wrote: > > 3) > > > Another potential issue of doing safe checks here is the order of > > assert and error out: > > In assert build, if the condition is true, then the header lock and > > content lock would not be released properly. So we may need to adjust > > the order. > > > This leads me to wonder -- would it be better to let this help > > function to do less, like just for registration and let the callers to > > handle others. > > I agree with your comment. Furthermore, I do not like the approach with > locking and unlocking in different functions. But, I see this approach > is used in some other places in the code. I should think how to improve it. > > I have some doubts about the code where LockBufferForCleanup (bufmgr.c) > calls ResolveRecoveryConflictWithBufferPin (standby.c), but the latter > function calls BufferIsReadyForCleanup (bufmgr.c). There is an idea to > refactor it in the future, because these functions are closely coupled. > May be unite them or move ResolveRecoveryConflictWithBufferPin into > bufmgr.c... I agree that letting the resolver own the wait for loop is not very ideal. The ideal design would be the code that owns the wait predicate owns the wait loop(bufmgr). But there seems no easy way to do it. > 4) the already-expired standby-delay path may not wake new pin holders > > Agree, thank you. It seems it is a kind of an optimization to avoid > activation of timeouts. Is it enought to return after > SendRecoveryConflictWithBufferPin, once we sent a signal to a conflicting > backend? Not sure, we have to wait with ProcWaitForSignal. Of course, the > same check should be in the loop, when timeouts are already activated. If > another backend pins the buffer after the broadcast, it will be handled > in the parent function. Yeah, returning right away after the initial SendRecoveryConflictWithBufferPin() is a possible way to fix the issue, but it may cause repeated broadcasts / busy retrying with the current design. > 5) The name of BufferIsReadyForCleanup seems broader than the actual protocol. > > What about to move RegisterPinCountWaiter out of this function? May be, rename > it into BufferGetRefCount() or something else like it? In this case, its > semantics will be simple and well-defined, and it can be re-used in some other > places. Another thing is to add a secong function argument like > doRegisterWaiter. > > We may also remove BufferIsReadyForCleanup but put its code into > ResolveRecoveryConflictWithBufferPin. > > I have no good solution right now. Let me please think about it. > > 6) > > > From personal experience, the message seems a bit hard to follow if > > one does not read the related discussion. I like your analysis of the > > problem at the start of this thread [1]. Would it be sensible to > > summarize and reuse some part of it for the message? > > > The motivation of this patch is to fix deadlock detector activation, > > but the wait-loop change has a slightly broader benefit. It also > > improves the standby timeout path indirectly by avoiding needless > > timeout teardown and re-entry on unrelated wakeups, and by keeping any > > already-fired timeout state until the loop handles it. Should we > > mention this as an additional benefit, or even frame the message > > broader like: > > Fix the buffer-pin recovery-conflict wait loop. > > Thank you for such a detailed comment. I would like to propose the following > commit message: This version seems better to me in general. > Fix recovery-conflict wait loop for buffer pins on hot standby > > When a deadlock occurs between the startup process and a backend during > recovery on a hot standby, the deadlock detector may fail to activate if > deadlock_timeout exceeds log_startup_progress_interval. Due to an > optimization in timeout.c that avoids redundant setitimer() calls, > periodic SIGALRM signals from the progress timer can arrive before the > deadlock timeout expires. These signals wake the startup process > prematurely, causing ResolveRecoveryConflictWithBufferPin to reset all > timeouts and retry without ever triggering the deadlock detector. This > results in an infinite loop in LockBufferForCleanup and stalls recovery > indefinitely, particularly when max_standby_streaming_delay = -1. > > The timeout.c subsystem uses an optimization that avoids redundant > setitimer() calls when the nearest active timeout's expiration time is > later than the currently armed timer. As a result, a SIGALRM from a > previously set timer (e.g., log_startup_progress_interval) can fire when > no currently active timeout has actually been reached. This periodic > signal wakes ResolveRecoveryConflictWithBufferPin prematurely, resetting > the timeout loop without ever triggering the deadlock detector at > deadlock_timeout. The deadlock timeout is perpetually re-armed but never > fires because each periodic SIGALRM arrives before it expires. These two paras seem repetitive to state the same thing. We might want to consolidate them. Another thing is should we focus less on the specific issue of log_startup_progress_interval? It's one of the sources that generate unrelated wake-ups that lead to this issue. The deeper issue is the buffer-pin wait code treats any latch wakeup as if it were a relevant buffer-pin wait event. > This patch fixes the issue by making ResolveRecoveryConflictWithBufferPin > ignore unintended SIGALRM signals that do not correspond to any currently > enabled timeout, ensuring the deadlock timeout fires correctly and the > conflicting backend is signaled to check for deadlocks. Unintended SIGALRM signals are the thing we try to ignore. It looks more like the end rather than the means. What we do seems broader: we ignore all unrelated latch wake-ups and only react to the genuine ready signal we care about. > It improves the standby timeout path by reducing unnecessary timeout > teardown and re-arming on unrelated wakeups, preserving the activated > timer state until the wait loop completes. This makes the deadlock > timeout behavior consistent with user expectations. > > > It seems, the patch should be completely rewritten. I will try to > prepare a new patch version. Thanks for that. -- Regards, Xuneng Zhou HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
JoongHyuk Shin <sjh910805@gmail.com>
Дата:
On Thu, Jul 2, 2026 at 12:57 AM Vitaly Davydov <v.davydov@postgrespro.ru> wrote:
> It seems, the patch should be completely rewritten. I will try to
> prepare a new patch version.
Hi Vitaly,
Any update on the new version you mentioned in your last message?
I ask because my patch at [1] reworks the same dispatch block in
ResolveRecoveryConflictWithBufferPin, and I plan to rebase it on top of
your rewrite, so I would like to time that.
Happy to help with testing if that is useful.
[1] https://www.postgresql.org/message-id/flat/CACSdjfO3ox8i8N3KxGf3HThzX1vnRRkY2kq1m5qsvGxjcuM1jg%40mail.gmail.com
--
JH Shin
> It seems, the patch should be completely rewritten. I will try to
> prepare a new patch version.
Hi Vitaly,
Any update on the new version you mentioned in your last message?
I ask because my patch at [1] reworks the same dispatch block in
ResolveRecoveryConflictWithBufferPin, and I plan to rebase it on top of
your rewrite, so I would like to time that.
Happy to help with testing if that is useful.
[1] https://www.postgresql.org/message-id/flat/CACSdjfO3ox8i8N3KxGf3HThzX1vnRRkY2kq1m5qsvGxjcuM1jg%40mail.gmail.com
--
JH Shin
Re: Deadlock detector fails to activate on a hot standby replica
On Tue, Aug 4, 2026 at 7:16 PM Vitaly Davydov wrote: > > Hi JH Shin, > > On 8/4/26 08:30, JoongHyuk Shin wrote: > > On Thu, Jul 2, 2026 at 12:57 AM Vitaly Davydov > > wrote: > >> It seems, the patch should be completely rewritten. I will try to > >> prepare a new patch version. > > > > Hi Vitaly, > > > > Any update on the new version you mentioned in your last message? > > I can't give you an exact time right now because of the issues highlighted > in the last review that need to be elaborated on. Sorry, I've just started > looking at it again. It might take a week or two. If your patch is ready for > commit, please go ahead with it. As I see it, the main change in your patch > avoids periodic message logging by passing the log_recovery_conflict variable > from the caller. Once your changes are committed, I don't foresee any problems > merging them into my patch. Personally, I still think the patch by JoongHyuk should be deferred until the one in the current thread is applied, because the imagined race case [1] still seems possible to me in a refreshed look. That potential race might be fixed in standalone beforehand but the potential fix seems not elegant to me. Sure the decision of pulling the trigger or not is up to Fujii-san or other committers. There seems to be some additional threads/issues piled up in this area [2]. Haven't checked the dependency among them yet. I'd like to help if you don't have time, but I won't be able to do so in this or next week since I've been wrestling with some subtle bugs which better be reported/fixed before the upcoming GA. [1] https://www.postgresql.org/message-id/CABPTF7VCdsfmvZpvXtuNHYhBYK4ivnfPAAM=vFXsgqYv2p2eyA@mail.gmail.com [2] https://www.postgresql.org/message-id/CAHg+QDf3NcB3vOAqQ5EFcV5DYYUZ9snCSJAU-x1JDbtcjK3eBQ@mail.gmail.com -- Regards, Xuneng Zhou HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
On Fri, Aug 14, 2026 at 1:35 AM Vitaly Davydov wrote: > > Dear Xuneng Zhou, All > > Sorry for the delay. Starting from this moment I will use my personal email > vitprof@gmail.com instead of vdavydov(at)postgrespro(dot)ru. > > On 8/8/26 16:51, Xuneng Zhou wrote: > > I haven't looked into the details yet. This version seems not resolve > > the awkwardness of dependency you pointed out earlier. Just wondering > > the reason for not aiming higher. It seems not trivial but still > > feasible. Do you think we better try to land the bug fix first and do > > further refactoring based on that? > > Yes, I haven't refactored the dependency. I think to fix the bug first > to continue progress, but refactor it later. I think the future > discussions about refactored versions may take a while. > > > "I agree with your comment. Furthermore, I do not like the approach of > > locking and unlocking in different functions. But, I see this approach > > is used in some other places in the code. I should think about how to improve it. > > > > I have some doubts about the code where LockBufferForCleanup (bufmgr.c) > > calls ResolveRecoveryConflictWithBufferPin (standby.c), but the latter > > function calls BufferIsReadyForCleanup (bufmgr.c). There is an idea to > > refactor it in the future, because these functions are closely coupled. > > May be unite them or move ResolveRecoveryConflictWithBufferPin into > > bufmgr.c..." > > I agree, it should be refactored. The problem is that BufferIsReadyForCleanup > uses some static variables from bufmgr.c. Moving > ResolveRecoveryConflictWithBufferPin > into bufmgr.c helps to break this dependency and looks good for me. > > I have some thoughts about the term 'pin count waiter'. I think it is a > confusing name. There is an idea to name it as buffer writer, once > multiple-readers-single-writer lock is implemented here. Pin count waiter > is just another term for a buffer writer, I think. > > I propose to go further with the current change to speed up the progress > because other contributors wait for it. +1 for the maneuver. I'll review the latest offering. -- Regards, Xuneng Zhou HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
Vitaly Davydov <vitprof@gmail.com>
Дата:
Hi Xuneng Zhou,
> * The caller must already be registered as the shared buffer's
> + * BM_PIN_COUNT_WAITER.
> This line of comment for PinCountWaiterCheckReadyForCleanup in v8
> seems not accurate to me. RegisterPinCountWaiter() explicitly permits
> the shared bit BM_PIN_COUNT_WAITER to be absent.
Agreed, thank you. Your edits to the comment for
PinCountWaiterCheckReadyForCleanup() look great.
> The invariante seems to be: Assert(PinCountWaitBuf == bufHdr);
> This process owns the logical cleanup wait for this buffer.
Yes, this invariant is checked in PinCountWaiterCheckReadyForCleanup().
> Updated this, and extended the commit message like we discussed
> earlier though it might not get used at the end.
Thank you very much for such an excellent commit message. Prior to it
we discussed to unite the explanation in one single paragraph. It seems,
I did poorly and I missed the description of changes. Your commit looks
very descriptive and complete.
One note about the commit message is the combining of words with a hyphen.
I see, that hot-standby appears in commit messages, but the hyphen in
buffer-pin, recovery-conflict or startup-progress seems excessive.
I'm not sure, but the commit title ("Fix premature wakeups...") might
suggest
that the wakeups are being prevented entirely, rather than fixing how they
are handled.
> The timeout para in that message is basically a summary of the first
email
> in this thread. I am not that familiar with it and too tired to
proof-read it.
> Can you do me a favor?
The paragraph looks technically sound and explains the core issue in detail.
Previously, a hang could occur after just a single premature wake-up.
This is
now stated clearly. While interference from multiple active timeouts can
lead
to more complex behavior, the fundamental problem remains unchanged.
> Just wondering whether we need a test for it.
I have a test for issue reproduction that is attached to the first email and
the patch in [1] where test/recovery/t/031_recovery_conflict.pl was
updated to reproduce the issue. But it uses log_startup_progress_interval
to activate a premature wakeup. There is an opinion in [2] that
log_startup_progress_interval behaviour may be changed, that invalidates
the test. I have no ideas about other simple alternative ways to trigger
premature wakeups. May be, injection points may help.
There is a concern in [2] that changes to the behavior of
log_startup_progress_interval will invalidate the test. I cannot think of
other simple ways to trigger premature wakeups. Perhaps injection points
could help here.
[1]
https://www.postgresql.org/message-id/CAHGQGwFED52rRVb_a%3DbVSdbOA%3DoARVOUyw381GC_6uKoNWJAtQ%40mail.gmail.com
[2]
https://www.postgresql.org/message-id/CAHGQGwHh5j%3DsG3AZh%3DHyuXtPM6cmymp6MJkRAMJcJUyN2qpHrQ%40mail.gmail.com
With best regards,
Vitaly Davydov
vitprof@gmail.com (aka v.davydov@postgrespro.ru)
vitcpp@mail.ru
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
Hi,
On Fri, Jun 5, 2026 at 7:58 PM Fujii Masao wrote:
>
> On Wed, May 27, 2026 at 12:01 AM Fujii Masao wrote:
> > + if (got_standby_delay_timeout)
> > + SendRecoveryConflictWithBufferPin(RECOVERY_CONFLICT_BUFFERPIN);
> > + else if (got_standby_deadlock_timeout)
> > + {
> >
> > Shouldn't we break out of the loop when either got_standby_delay_timeout or
> > got_standby_deadlock_timeout becomes true? Otherwise, the loop continues with
> > those flags still set, which could cause SendRecoveryConflictWithBufferPin() to
> > be called unnecessarily in the subsequent cycles.
> >
> >
> > + if (BufferGetRefCount(buffer) <= 1)
> >
> > Should this be "BufferGetRefCount(buffer) == 1" instead? I don't think
> > BufferGetRefCount(buffer) should ever return 0 here. If that's correct,
> > would it make sense to explicitly detect that case, for example:
> >
> > -----------------
> > uint32 refcount = BufferGetRefCount(buffer);
> >
> > Assert(refcount > 0);
> >
> > if (refcount == 0)
> > elog(ERROR, "buffer refcount dropped to zero while waiting for
> > cleanup lock");
> >
> > if (refcount == 1)
> > break;
> > -----------------
>
> I've updated the patch based on these comments.
> Attached is the latest version.
>
> I removed the TAP test from this patch for now. I'll consider adding
> a test for this separately later.
>
> BTW, I'm just wondering whether ResolveRecoveryConflictWithLock()
> might have the same issue. I need to investigate that further.
While working on something closely related, I revisited this thread.
ResolveRecoveryConflictWithLock seems to also suffer from the same
issue per investigation. I'll share some findings later.
--
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
Hi Vitaly,
On Fri, Sep 4, 2026 at 10:16 PM Vitaly Davydov wrote:
>
> Hi Xuneng Zhou,
>
> > * The caller must already be registered as the shared buffer's
> > + * BM_PIN_COUNT_WAITER.
> > This line of comment for PinCountWaiterCheckReadyForCleanup in v8
> > seems not accurate to me. RegisterPinCountWaiter() explicitly permits
> > the shared bit BM_PIN_COUNT_WAITER to be absent.
>
> Agreed, thank you. Your edits to the comment for
> PinCountWaiterCheckReadyForCleanup() look great.
>
> > The invariante seems to be: Assert(PinCountWaitBuf == bufHdr);
> > This process owns the logical cleanup wait for this buffer.
>
> Yes, this invariant is checked in PinCountWaiterCheckReadyForCleanup().
>
> > Updated this, and extended the commit message like we discussed
> > earlier though it might not get used at the end.
>
> Thank you very much for such an excellent commit message. Prior to it
> we discussed to unite the explanation in one single paragraph. It seems,
> I did poorly and I missed the description of changes. Your commit looks
> very descriptive and complete.
Thanks for proof-reading it!
> One note about the commit message is the combining of words with a hyphen.
> I see, that hot-standby appears in commit messages, but the hyphen in
> buffer-pin, recovery-conflict or startup-progress seems excessive.
>
> I'm not sure, but the commit title ("Fix premature wakeups...") might
> suggest
> that the wakeups are being prevented entirely, rather than fixing how they
> are handled.
Ok, that's right. Agreed that the header line is somewhat misleading
and needs to be softened. We did not *prevent* the general unrelated
premature wakeups in ProcWaitForSignal. And those hyphens are
unnecessary, they are removed. I also made some minor adjustments to
the patch. Add timeouts_armed flag to tell the already expired timeout
to avoid the extra round of cancellation request without
re-introducing the original problem. If it is set, break the for loop,
let the resolver send another cancellation request if the conflict is
still there.
There's another counterpart case for ResolveRecoveryConflictWithLock
as the attached reproducer 913 shows. The startup process waits for a
lock held by a standby session, which in turn waits for another lock
held by the startup process. An unrelated wakeup before the set
deadlock timeout causes the same kernel timeout rearming issue,
preventing the startup process from detecting and breaking the cycle.
> > The timeout para in that message is basically a summary of the first
> email
> > in this thread. I am not that familiar with it and too tired to
> proof-read it.
> > Can you do me a favor?
>
> The paragraph looks technically sound and explains the core issue in detail.
> Previously, a hang could occur after just a single premature wake-up.
> This is
> now stated clearly. While interference from multiple active timeouts can
> lead
> to more complex behavior, the fundamental problem remains unchanged.
> > Just wondering whether we need a test for it.
>
> I have a test for issue reproduction that is attached to the first email and
> the patch in [1] where test/recovery/t/031_recovery_conflict.pl was
> updated to reproduce the issue. But it uses log_startup_progress_interval
> to activate a premature wakeup. There is an opinion in [2] that
> log_startup_progress_interval behaviour may be changed, that invalidates
> the test. I have no ideas about other simple alternative ways to trigger
> premature wakeups. May be, injection points may help.
>
> There is a concern in [2] that changes to the behavior of
> log_startup_progress_interval will invalidate the test. I cannot think of
> other simple ways to trigger premature wakeups. Perhaps injection points
> could help here.
>
> [1]
> https://www.postgresql.org/message-id/CAHGQGwFED52rRVb_a%3DbVSdbOA%3DoARVOUyw381GC_6uKoNWJAtQ%40mail.gmail.com
> [2]
> https://www.postgresql.org/message-id/CAHGQGwHh5j%3DsG3AZh%3DHyuXtPM6cmymp6MJkRAMJcJUyN2qpHrQ%40mail.gmail.com
pg_log_backend_memory_contexts seems able to trigger the premature
wakeups for the startup. V10 adds two tests(lock/buffer pin) based on
that. As usual, the hard part is to make it deterministic end-to-end.
To make the stall occur, we need this sequence:
1) Startup sets a deadlock deadline and a kernel alarm for it.
2) An unrelated wakeup makes broken code move the deadline later,
leaving the old alarm pending.
3) If startup handles that alarm before the new deadline, the handler
wakes startup and schedules another alarm without firing the deadlock
timeout.
4) Broken code moves the deadline later again, leaving that alarm pending.
5) Steps 3–4 can repeat indefinitely.
The tricky part is in step 3. If there's some delay for the startup
handling the alarm due to scheduling or other factors, the woken
process would possibly find that the logical deadline has expired,
subsequently, the handler would fire the deadlock timeout to send the
cancellation request to break the cycle. There's no facility in the
tree to simulate the time to let it 'pause' until the startup handles
the alarm. Therefore, the added test exercises the mechanism rather
than the behavior -- the timeout would not be rearmed after unrelated
wakeups.
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
On Sat, Oct 10, 2026 at 5:24 PM Xuneng Zhou wrote:
>
> Hi Vitaly,
>
> On Fri, Sep 4, 2026 at 10:16 PM Vitaly Davydov wrote:
> >
> > Hi Xuneng Zhou,
> >
> > > * The caller must already be registered as the shared buffer's
> > > + * BM_PIN_COUNT_WAITER.
> > > This line of comment for PinCountWaiterCheckReadyForCleanup in v8
> > > seems not accurate to me. RegisterPinCountWaiter() explicitly permits
> > > the shared bit BM_PIN_COUNT_WAITER to be absent.
> >
> > Agreed, thank you. Your edits to the comment for
> > PinCountWaiterCheckReadyForCleanup() look great.
> >
> > > The invariante seems to be: Assert(PinCountWaitBuf == bufHdr);
> > > This process owns the logical cleanup wait for this buffer.
> >
> > Yes, this invariant is checked in PinCountWaiterCheckReadyForCleanup().
> >
> > > Updated this, and extended the commit message like we discussed
> > > earlier though it might not get used at the end.
> >
> > Thank you very much for such an excellent commit message. Prior to it
> > we discussed to unite the explanation in one single paragraph. It seems,
> > I did poorly and I missed the description of changes. Your commit looks
> > very descriptive and complete.
>
> Thanks for proof-reading it!
>
> > One note about the commit message is the combining of words with a hyphen.
> > I see, that hot-standby appears in commit messages, but the hyphen in
> > buffer-pin, recovery-conflict or startup-progress seems excessive.
> >
> > I'm not sure, but the commit title ("Fix premature wakeups...") might
> > suggest
> > that the wakeups are being prevented entirely, rather than fixing how they
> > are handled.
>
> Ok, that's right. Agreed that the header line is somewhat misleading
> and needs to be softened. We did not *prevent* the general unrelated
> premature wakeups in ProcWaitForSignal. And those hyphens are
> unnecessary, they are removed. I also made some minor adjustments to
> the patch. Add timeouts_armed flag to tell the already expired timeout
> to avoid the extra round of cancellation request without
> re-introducing the original problem. If it is set, break the for loop,
> let the resolver send another cancellation request if the conflict is
> still there.
>
> There's another counterpart case for ResolveRecoveryConflictWithLock
> as the attached reproducer 913 shows. The startup process waits for a
> lock held by a standby session, which in turn waits for another lock
> held by the startup process. An unrelated wakeup before the set
> deadlock timeout causes the same kernel timeout rearming issue,
> preventing the startup process from detecting and breaking the cycle.
>
> > > The timeout para in that message is basically a summary of the first
> > email
> > > in this thread. I am not that familiar with it and too tired to
> > proof-read it.
> > > Can you do me a favor?
> >
> > The paragraph looks technically sound and explains the core issue in detail.
> > Previously, a hang could occur after just a single premature wake-up.
> > This is
> > now stated clearly. While interference from multiple active timeouts can
> > lead
> > to more complex behavior, the fundamental problem remains unchanged.
>
>
>
> > > Just wondering whether we need a test for it.
> >
> > I have a test for issue reproduction that is attached to the first email and
> > the patch in [1] where test/recovery/t/031_recovery_conflict.pl was
> > updated to reproduce the issue. But it uses log_startup_progress_interval
> > to activate a premature wakeup. There is an opinion in [2] that
> > log_startup_progress_interval behaviour may be changed, that invalidates
> > the test. I have no ideas about other simple alternative ways to trigger
> > premature wakeups. May be, injection points may help.
> >
> > There is a concern in [2] that changes to the behavior of
> > log_startup_progress_interval will invalidate the test. I cannot think of
> > other simple ways to trigger premature wakeups. Perhaps injection points
> > could help here.
> >
> > [1]
> > https://www.postgresql.org/message-id/CAHGQGwFED52rRVb_a%3DbVSdbOA%3DoARVOUyw381GC_6uKoNWJAtQ%40mail.gmail.com
> > [2]
> > https://www.postgresql.org/message-id/CAHGQGwHh5j%3DsG3AZh%3DHyuXtPM6cmymp6MJkRAMJcJUyN2qpHrQ%40mail.gmail.com
>
> pg_log_backend_memory_contexts seems able to trigger the premature
> wakeups for the startup. V10 adds two tests(lock/buffer pin) based on
> that. As usual, the hard part is to make it deterministic end-to-end.
>
> To make the stall occur, we need this sequence:
>
> 1) Startup sets a deadlock deadline and a kernel alarm for it.
> 2) An unrelated wakeup makes broken code move the deadline later,
> leaving the old alarm pending.
> 3) If startup handles that alarm before the new deadline, the handler
> wakes startup and schedules another alarm without firing the deadlock
> timeout.
> 4) Broken code moves the deadline later again, leaving that alarm pending.
> 5) Steps 3–4 can repeat indefinitely.
>
> The tricky part is in step 3. If there's some delay for the startup
> handling the alarm due to scheduling or other factors, the woken
> process would possibly find that the logical deadline has expired,
> subsequently, the handler would fire the deadlock timeout to send the
> cancellation request to break the cycle. There's no facility in the
> tree to simulate the time to let it 'pause' until the startup handles
> the alarm. Therefore, the added test exercises the mechanism rather
> than the behavior -- the timeout would not be rearmed after unrelated
> wakeups.
Sorry for the missing reproducer.
--
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
On Sat, Oct 10, 2026 at 5:27 PM Xuneng Zhou wrote:
>
> On Sat, Oct 10, 2026 at 5:24 PM Xuneng Zhou wrote:
> >
> > Hi Vitaly,
> >
> > On Fri, Sep 4, 2026 at 10:16 PM Vitaly Davydov wrote:
> > >
> > > Hi Xuneng Zhou,
> > >
> > > > * The caller must already be registered as the shared buffer's
> > > > + * BM_PIN_COUNT_WAITER.
> > > > This line of comment for PinCountWaiterCheckReadyForCleanup in v8
> > > > seems not accurate to me. RegisterPinCountWaiter() explicitly permits
> > > > the shared bit BM_PIN_COUNT_WAITER to be absent.
> > >
> > > Agreed, thank you. Your edits to the comment for
> > > PinCountWaiterCheckReadyForCleanup() look great.
> > >
> > > > The invariante seems to be: Assert(PinCountWaitBuf == bufHdr);
> > > > This process owns the logical cleanup wait for this buffer.
> > >
> > > Yes, this invariant is checked in PinCountWaiterCheckReadyForCleanup().
> > >
> > > > Updated this, and extended the commit message like we discussed
> > > > earlier though it might not get used at the end.
> > >
> > > Thank you very much for such an excellent commit message. Prior to it
> > > we discussed to unite the explanation in one single paragraph. It seems,
> > > I did poorly and I missed the description of changes. Your commit looks
> > > very descriptive and complete.
> >
> > Thanks for proof-reading it!
> >
> > > One note about the commit message is the combining of words with a hyphen.
> > > I see, that hot-standby appears in commit messages, but the hyphen in
> > > buffer-pin, recovery-conflict or startup-progress seems excessive.
> > >
> > > I'm not sure, but the commit title ("Fix premature wakeups...") might
> > > suggest
> > > that the wakeups are being prevented entirely, rather than fixing how they
> > > are handled.
> >
> > Ok, that's right. Agreed that the header line is somewhat misleading
> > and needs to be softened. We did not *prevent* the general unrelated
> > premature wakeups in ProcWaitForSignal. And those hyphens are
> > unnecessary, they are removed. I also made some minor adjustments to
> > the patch. Add timeouts_armed flag to tell the already expired timeout
> > to avoid the extra round of cancellation request without
> > re-introducing the original problem. If it is set, break the for loop,
> > let the resolver send another cancellation request if the conflict is
> > still there.
> >
> > There's another counterpart case for ResolveRecoveryConflictWithLock
> > as the attached reproducer 913 shows. The startup process waits for a
> > lock held by a standby session, which in turn waits for another lock
> > held by the startup process. An unrelated wakeup before the set
> > deadlock timeout causes the same kernel timeout rearming issue,
> > preventing the startup process from detecting and breaking the cycle.
> >
> > > > The timeout para in that message is basically a summary of the first
> > > email
> > > > in this thread. I am not that familiar with it and too tired to
> > > proof-read it.
> > > > Can you do me a favor?
> > >
> > > The paragraph looks technically sound and explains the core issue in detail.
> > > Previously, a hang could occur after just a single premature wake-up.
> > > This is
> > > now stated clearly. While interference from multiple active timeouts can
> > > lead
> > > to more complex behavior, the fundamental problem remains unchanged.
> >
> >
> >
> > > > Just wondering whether we need a test for it.
> > >
> > > I have a test for issue reproduction that is attached to the first email and
> > > the patch in [1] where test/recovery/t/031_recovery_conflict.pl was
> > > updated to reproduce the issue. But it uses log_startup_progress_interval
> > > to activate a premature wakeup. There is an opinion in [2] that
> > > log_startup_progress_interval behaviour may be changed, that invalidates
> > > the test. I have no ideas about other simple alternative ways to trigger
> > > premature wakeups. May be, injection points may help.
> > >
> > > There is a concern in [2] that changes to the behavior of
> > > log_startup_progress_interval will invalidate the test. I cannot think of
> > > other simple ways to trigger premature wakeups. Perhaps injection points
> > > could help here.
> > >
> > > [1]
> > > https://www.postgresql.org/message-id/CAHGQGwFED52rRVb_a%3DbVSdbOA%3DoARVOUyw381GC_6uKoNWJAtQ%40mail.gmail.com
> > > [2]
> > > https://www.postgresql.org/message-id/CAHGQGwHh5j%3DsG3AZh%3DHyuXtPM6cmymp6MJkRAMJcJUyN2qpHrQ%40mail.gmail.com
> >
> > pg_log_backend_memory_contexts seems able to trigger the premature
> > wakeups for the startup. V10 adds two tests(lock/buffer pin) based on
> > that. As usual, the hard part is to make it deterministic end-to-end.
> >
> > To make the stall occur, we need this sequence:
> >
> > 1) Startup sets a deadlock deadline and a kernel alarm for it.
> > 2) An unrelated wakeup makes broken code move the deadline later,
> > leaving the old alarm pending.
> > 3) If startup handles that alarm before the new deadline, the handler
> > wakes startup and schedules another alarm without firing the deadlock
> > timeout.
> > 4) Broken code moves the deadline later again, leaving that alarm pending.
> > 5) Steps 3–4 can repeat indefinitely.
> >
> > The tricky part is in step 3. If there's some delay for the startup
> > handling the alarm due to scheduling or other factors, the woken
> > process would possibly find that the logical deadline has expired,
> > subsequently, the handler would fire the deadlock timeout to send the
> > cancellation request to break the cycle. There's no facility in the
> > tree to simulate the time to let it 'pause' until the startup handles
> > the alarm. Therefore, the added test exercises the mechanism rather
> > than the behavior -- the timeout would not be rearmed after unrelated
> > wakeups.
>
> Sorry for the missing reproducer.
Add them to the commifest [1]. Attach again to let the cfbots do their work.
[1] https://commitfest.postgresql.org/patch/7372/
--
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Xuneng,
Thanks for v10 and for finding the lock case. I tested it and have
a few notes.
there.
Thanks for v10 and for finding the lock case. I tested it and have
a few notes.
1. I am able to reproduce the case with your code and when
it passed deadlock_timeout. And your V10 is able to cancel the
deadlocked query.
2. V10 leaves the case where the delay has already passed as it was,
one wait with no timeout. So the problem in CF 6445 [1] is stillthere.
I think this patch is LGTM.
Thanks,
Shihao
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
Hi shihao,
On Wed, Oct 28, 2026 at 10:16 AM shihao zhong <zhong950419@gmail.com> wrote:
Hi Xuneng,
Thanks for v10 and for finding the lock case. I tested it and have
a few notes.1. I am able to reproduce the case with your code and whenit passed deadlock_timeout. And your V10 is able to cancel thedeadlocked query.2. V10 leaves the case where the delay has already passed as it was,one wait with no timeout. So the problem in CF 6445 [1] is still
there.I think this patch is LGTM.
Thanks for your review! I am aware of the patch you referred to and plan to take a look soon.
Regards,
Xuneng Zhou
HighGo Software Co., Ltd.
Xuneng Zhou
HighGo Software Co., Ltd.
Re: Deadlock detector fails to activate on a hot standby replica
От:
JoongHyuk Shin <sjh910805@gmail.com>
Дата:
Hi Xuneng, Vitaly,
I tested v10 on master 48938780c35, built with --enable-cassert
--enable-debug --enable-tap-tests --enable-injection-points. The patches
apply and build without warnings, and src/test/recovery passes. On
master with only the injection points added, the two new
unrelated-wakeup tests fail.
I also woke startup with pg_log_backend_memory_contexts() during a
buffer pin deadlock and a lock deadlock, with
max_standby_streaming_delay = -1. On master, 7 of 8 runs (2 of 2 buffer
pin, 5 of 6 lock) were still stuck 10 to 15 seconds later. v10 resolved
all of them at about the same time as with no wakeup.
The race I reported on v7 is fixed too. I checked it by stopping
startup in gdb inside the window.
LGTM. I'll mark it Ready for Committer.
--
JoongHyuk Shin
I tested v10 on master 48938780c35, built with --enable-cassert
--enable-debug --enable-tap-tests --enable-injection-points. The patches
apply and build without warnings, and src/test/recovery passes. On
master with only the injection points added, the two new
unrelated-wakeup tests fail.
I also woke startup with pg_log_backend_memory_contexts() during a
buffer pin deadlock and a lock deadlock, with
max_standby_streaming_delay = -1. On master, 7 of 8 runs (2 of 2 buffer
pin, 5 of 6 lock) were still stuck 10 to 15 seconds later. v10 resolved
all of them at about the same time as with no wakeup.
The race I reported on v7 is fixed too. I checked it by stopping
startup in gdb inside the window.
LGTM. I'll mark it Ready for Committer.
--
JoongHyuk Shin
Re: Deadlock detector fails to activate on a hot standby replica
От:
Xuneng Zhou <xunengzhou@gmail.com>
Дата:
Hi JoongHyuk, Thanks for double-checking this. On Fri, Nov 13, 2026 at 10:50 AM JoongHyuk Shin wrote: > > Hi Xuneng, Vitaly, > > I tested v10 on master 48938780c35, built with --enable-cassert > --enable-debug --enable-tap-tests --enable-injection-points. The patches > apply and build without warnings, and src/test/recovery passes. On > master with only the injection points added, the two new > unrelated-wakeup tests fail. > I also woke startup with pg_log_backend_memory_contexts() during a > buffer pin deadlock and a lock deadlock, with > max_standby_streaming_delay = -1. On master, 7 of 8 runs (2 of 2 buffer > pin, 5 of 6 lock) were still stuck 10 to 15 seconds later. v10 resolved > all of them at about the same time as with no wakeup. Good to hear. What I'm unsure of is the use of pg_log_backend_memory_contexts as the trigger for the premature wake-up. It works but seems somewhat hacky. Unfortunately, the test is built on this, so it might be unfavored at the end. But it still has its value for proving whether the fix works or not indirectly. BTW, I've been coping with lots of issues related to the $subject recently. It seems that replay could be held unwantedly for various reasons spanning from features/bugs. What the fixes of them require unanimously is a well-working deadlock checking protocol, which the current thread contributed partly to. In production, a configured max_standby_*_delay would cance players stalling the replay eventually, even if the deadlock checking does not work well or their dependency on replay is invisible to that checking. However, this still seems undesirable, because it makes no sense to wait for the backends which have already formed cycles with the startup -- they would not progress and could consume most of, if not all, the budget that other normal backends share, hence impacting the overall availability. > The race I reported on v7 is fixed too. I checked it by stopping > startup in gdb inside the window. > > LGTM. I'll mark it Ready for Committer. v10 has been green with CFBots for a while. +1 for the move. -- Regards, Xuneng Zhou HighGo Software Co., Ltd.