[13.x] Resume sleeping when Sleep is interrupted by a signal - #60615
[13.x] Resume sleeping when Sleep is interrupted by a signal#60615dhrupo wants to merge 1 commit into
Conversation
Sleep::goodnight() called sleep($seconds) but ignored its return value. PHP's sleep() returns the number of seconds left to sleep when it is interrupted by a signal, and queue workers (e.g. Horizon) routinely deliver pcntl signals. As a result a Sleep::for(...)->seconds() call inside a job could wake up early after being interrupted, having slept less than the requested duration. Keep sleeping with the remaining seconds returned by sleep() until the full duration has elapsed. sleep() returns 0 on success and false on error, both of which end the loop, so an uninterrupted sleep behaves exactly as before. Fixes laravel#56647
|
What is the behavior if it receives a SIGTERM? |
|
That's the weak spot here. The worker's SIGTERM handler only sets So resuming on every signal is wrong for termination signals specifically. It really needs to bail on SIGTERM/SIGINT (and the job timeout SIGALRM) and only resume on the benign ones, rather than the blanket loop I have here. I'll rework it that way if you think it's worth pursuing, otherwise happy to close it. |
|
https://www.php.net/manual/en/function.sleep.php#refsect1-function.sleep-returnvalues
I guess we should handle the Windows-specific return so a call to sleep won't sleep for an additional 192 seconds on every interrupt. |
Fixes #56647
The problem
Calling
Sleepinside a queued job can wake up early. For example:The job logs "Should be awake now" before the full 60 seconds have passed. The same code sleeps correctly outside of a queue worker.
Root cause
Sleep::goodnight()performs the actual sleeping:PHP's
sleep()returns the number of seconds left to sleep if the call is interrupted by a signal (otherwise it returns0). Queue workers — Horizon in the reported case — routinely deliverpcntlsignals (timeout alarms, restart/termination signals, etc.). When one arrives mid-sleep,sleep()returns early, butgoodnight()ignores the return value and assumes the whole duration was slept, so the remaining time is silently skipped.This is straightforward to reproduce: an alarm scheduled with
pcntl_alarm(1)interruptssleep(3), which then returns2and elapses only one second.The fix
Keep sleeping with the seconds that
sleep()reports as remaining until the full duration has actually elapsed:sleep()returns0on success andfalseon error — both end the loop — so an uninterrupted sleep behaves exactly as before. Only the interrupted case changes: it now resumes instead of returning early.Tests
Added
testItKeepsSleepingWhenInterruptedBySignal, which schedules a signal to interrupt a two-second sleep after one second and asserts the total elapsed time is still at least two seconds. It fails before this change (wakes after ~1s) and passes after it. The test skips automatically when thepcntlextension is unavailable.The full
tests/Supportsuite passes.