Review
Deadlock detector fails to activate on a hot standby replica
- Proposal version
- 10
- CommitFest entry
- 7372
- Base commit
- 1c4628d0b3c5d38b7a965f686aa69fe579038b3d
Summary
Reviewed v10 of "Deadlock detector fails to activate on a hot standby
replica": three patches, the fix (0001), the tests (0002) and a small
refactor of LockBufferForCleanup() (0003). They apply cleanly with
git am on master 1c4628d0b3c5d38b7a965f686aa69fe579038b3d and build
with cassert, debug, injection points and TAP tests enabled. The meson
setup, regress, isolation and recovery suites pass (65 of 65).
In 031_recovery_conflict.pl, the new lock-deadlock case and both
unrelated-wakeup cases pass.
This is a well-motivated fix for a real recovery stall. The approach matches how ordinary lock waits already handle spurious wakeups. I did not find a correctness problem. My remaining comments concern back-branches, how the test triggers the wakeup, and some small points.
Reproduction
I confirmed the bug and the fix:
- On master at the base commit, with only the injection points from
0002 and the updated
031_recovery_conflict.pl, both new "unrelated wakeup did not restart the deadlock timer" checks fail, for the buffer pin case and the lock case. - I ran the lock-deadlock reproducer posted in the thread on both
builds. It sets
max_standby_streaming_delay = -1anddeadlock_timeout = 3s, then wakes startup once withpg_log_backend_memory_contexts(). Startup and the session are waiting on each other in a lock cycle. On master the cycle is still there 10 seconds later and no deadlock is reported. With v10 the session gets "deadlock detected" and recovery reports it waited about 3000 ms, so the cycle is broken oncedeadlock_timeouthas elapsed. The script's assertions describe the broken behavior, so it passes on master and fails on the patched build, as intended.
Motivation and analysis
ResolveRecoveryConflictWithBufferPin() and
ResolveRecoveryConflictWithLock() arm a deadlock timeout and, if the
delay limit applies, a standby-delay timeout. They then call
ProcWaitForSignal() once. On any wakeup they disable all timeouts and
return. If the conflict is still there, the caller calls them again,
and they arm a new deadlock timeout with a later deadline.
timeout.c does not necessarily cancel the kernel timer when the
logical timeouts are disabled. A leftover alarm can therefore fire
before the new deadline. The handler sets the latch and re-arms for the
new deadline, which wakes startup "unrelatedly" again. Startup then
pushes the deadline out once more, and this can repeat forever. With
the delay limit at -1, nothing else breaks the cycle: the deadlock
check request is never sent, and replay stays stuck. One unrelated
wakeup is enough to start this, for example a ProcSignal-driven request
or another timer.
The fix keeps the existing timeouts armed across wakeups that do not end the wait:
- Buffer pin:
PinCountWaiterCheckReadyForCleanup()rechecks whether only startup's own pin is left. If not, it registers startup again as the pin-count waiter and goes back to waiting. - Lock: the loop rechecks
MyProc->waitStatusand keeps waiting while the lock is still pending. - If the delay limit had already passed and no timeouts were armed, the old behavior is kept: return after any wakeup.
Ordinary backends in ProcSleep() already work this way. They arm
the deadlock timeout once and loop on spurious wakeups, so this change
brings the two standby resolvers into line with that pattern.
Correctness notes
- Lost wakeups. Lock grants and
WakePinCountWaiter()both set the process latch. A grant or unpin that happens between the recheck and the nextProcWaitForSignal()leaves the latch set, so the next wait returns at once. No wakeup is lost. - Re-registration race.
RegisterPinCountWaiter()publishesBM_PIN_COUNT_WAITERwith an atomic OR, then rechecks the refcount while the header is still locked. If the last other pin was dropped in between, it clears the flag throughUnlockBufHdrExt(), which uses a CAS loop, so a concurrent decrement is not lost. This closes the window raised in the thread, where the last pin could be dropped between the refcount check and setting the flag. - Caller cleanup.
PinCountWaiterCheckReadyForCleanup()returns true without holding the content lock.LockBufferForCleanup()then clears the waiter flag if it is still ours, takes the content lock again and rechecks the pin count. A pin taken in that gap is handled by the outer loop, as before. - Lock-path order. On each wakeup, the lock path checks, in order:
lock granted, delay timeout, deadlock timeout. After the deadlock
branch sends its request, it keeps the old "wait once more, then
return" behavior. An unrelated wakeup during that extra wait returns
to
ProcSleep(), which arms a fresh deadlock timeout. That costs at most one extra deadlock-check request. It cannot bring back the stall, because the new wait is again protected by the loop. - Conflict logging. When
logging_conflictis set, the loop still returns once the deadlock timeout has fired, so "still waiting" messages appear at the same point as before. For buffer pins they are emitted inLockBufferForCleanup()between resolver calls. That only happens on real timeouts now, which matches the old timing. - Interrupts.
ProcWaitForSignal()still runsCHECK_FOR_INTERRUPTS()on every pass through the loop, so ProcSignal barriers and memory-context requests are still handled while startup waits.
Comments
-
Back-branches. The CF entry targets stable branches, but v10 contains only a master patch. The comment in
RegisterPinCountWaiter()relies on master's behavior: the shared refcount can be decremented whileBM_LOCKEDis set. In released branches, unpinning waits for the header lock to be released, so the recheck there is just a harmless extra step. Either way the back-branch versions will need their own patch and comment. The earlier per-branch patches in the thread predate the loop redesign and should not be reused as they are. -
The test's wakeup trigger. The unrelated wakeup is produced with
pg_log_backend_memory_contexts(). The thread already notes that this is somewhat indirect, and that the test checks the mechanism (the timer is not re-armed) rather than the end behavior (the deadlock is detected). I think checking the mechanism is the right choice: the end behavior depends on when the timer fires relative to scheduling, and would be flaky. A dedicated injection point that sets startup's latch would be more explicit than relying on a side effect of memory-context logging, but the current approach works and is deterministic. The sequence it relies on is: the log line appears, then the wait event shows up again, then the log is checked for the injection point notice. That ordering holds because the wait event is cleared beforeCHECK_FOR_INTERRUPTS()runs. -
Unrelated test churn. 0002 also drops an
ok(1, ...)placeholder and an unused$resassignment, and renumbers the sections. These are harmless, but they belong in a separate cleanup or should at least be mentioned in the commit message. -
Lock-deadlock test. This test needs a restart, with
log_startup_progress_interval = 0, to "clear any alarm left by the buffer pin test". That shows how sensitive the old behavior was to stale timers. It deserves a one-line note that, with the fix, the restart only keeps the test independent of earlier timer state; correctness does not depend on it. -
Already-expired delay. If the delay limit has already passed, the buffer pin path still sends one cancellation and then waits with no timer. A backend that pins the buffer after that broadcast is not cancelled until something else wakes startup. The thread points out that this case is tracked separately (CF 6445), and leaving it out of scope seems fine. A short comment at the
!timeouts_armedbreak that points to that limitation would help later readers. -
The root cause in
timeout.c. A spurious SIGALRM wakes the process and sets the latch even when no timeout has fired. That is the underlying amplifier. The fix rightly makes the waiters robust to any spurious wakeup instead of depending on timer internals. The commit message says this well. Any other code that waits withProcWaitForSignal()while timeouts are armed should use the same loop pattern. As far as I can see, the two functions in this patch are the only such waiters in the recovery-conflict code; the virtual-xid and database conflict paths poll instead. -
Minor: the moved
XXXcomment in the buffer pin path keeps the existing typo "basically no so long". Since it is being re-indented anyway, this is a good moment to fix it.
Discussion status
The thread is long and productive. The report came with a TAP reproducer. The early versions were reworked during review, including a separate pin-count helper and a fix for an already-expired-delay problem. A pin-count registration race was raised and then fixed in v8. The lock-wait case was added in v10 after being shown to suffer from the same timer behavior. Two reviewers have tested v10, one of them checking the race window under a debugger, and the entry is Ready for Committer. The questions still open are back-branch packaging and whether the memory-context-based test trigger is acceptable.
Verdict
The motivation is strong, the bug is reproducible, and the fix is
minimal, correct and in line with how ProcSleep() waits. With
back-branch versions and the small comment and test cleanups above, I
consider it ready to commit.