From b7ae12280f5983b3d2c84e839a12f3f880d27ec4 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:02:25 +0000 Subject: [PATCH 01/11] Handle queue control signals through the coroutine runtime Remove the process alarm and the liveness timer used to interrupt a blocked event loop. New Swoole versions reject process-wide signal setup inside coroutines. Register worker controls with the shared signal registry and release them when the daemon ends. Keep the timeout monitor and bounded cancellation for yielding jobs. If a worker is PID 1 and survives its own SIGKILL, replace the process so it exits with the requested status without resuming unfinished jobs. Document the need for an external restart if a job never yields. --- src/docs/porting-from-laravel.md | 4 +- src/docs/queues.md | 10 +- src/queue/README.md | 2 +- src/queue/composer.json | 2 + src/queue/src/Worker.php | 223 ++++-------------------- tests/Queue/Fixtures/timeout-worker.php | 54 +----- tests/Queue/WorkerTimeoutTest.php | 23 +-- 7 files changed, 59 insertions(+), 259 deletions(-) diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index 58122c3287..6ac79c92ae 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -357,6 +357,8 @@ Laravel's `DeferrableProvider` interface is not useful in Hypervel's long-runnin Coroutine safety is the most important part of a Laravel-to-Hypervel port. In Hypervel, multiple requests or jobs may run concurrently inside the same worker process. Any mutable state on a singleton, static property, manager, or service provider can be observed by another coroutine if it is not isolated correctly. +Process-wide PCNTL calls such as `pcntl_signal()`, `pcntl_sigprocmask()`, and `pcntl_alarm()` conflict with Swoole's coroutine runtime. Use [command signal traps](/docs/{{version}}/artisan#signal-handling) in Artisan commands and set timeouts on the operations a job waits for. + ### Request-Specific State @@ -957,7 +959,7 @@ When dispatching batched jobs to a queue such as Redis or SQS inside a transacti Custom queue drivers whose job classes implement `Hypervel\Contracts\Queue\Job` directly must also implement `Hypervel\Contracts\Queue\JobLifecycleCallbacks` to run jobs that use `CountCrashesAsExceptions`; extending `Hypervel\Queue\Jobs\Job` provides it. See [counting worker crashes](/docs/{{version}}/queues#counting-worker-crashes) for the callback requirements. -Timeouts unwind yielding job code with `Swoole\Coroutine\CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation from broad `catch (Exception)` or `catch (Throwable)` handlers. The worker gives canceled code a bounded wait; if the job is still unwinding when that wait ends, it terminates without waiting for cleanup or running the job's failure handling. `Worker::$killOnTimeout = false` instead waits for the job to unwind while other jobs continue. Failure callbacks receive `TimeoutExceededException`. See [worker timeouts](/docs/{{version}}/queues#worker-timeouts) for recovery behavior and limits. +Timeouts unwind yielding job code with `Swoole\Coroutine\CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation from broad `catch (Exception)` or `catch (Throwable)` handlers. The worker gives canceled code a bounded wait; if the job is still unwinding when that wait ends, it terminates without waiting for cleanup or running the job's failure handling. `Worker::$killOnTimeout = false` instead waits for the job to unwind while other jobs continue. Failure callbacks receive `TimeoutExceededException`. Laravel can interrupt a PHP loop with a process alarm. In Hypervel, a job that never yields blocks timeout checks for the entire worker. See [worker timeouts](/docs/{{version}}/queues#worker-timeouts). If you extend Horizon's `RedisQueue`, do not rely on `push()` calling your `pushRaw()` override. Override the protected `preparePayloadForPush()` method to prepare normal pushes, or `handlePayloadPushed()` to run code after Redis accepts the job. Direct calls to `pushRaw()` remain supported. diff --git a/src/docs/queues.md b/src/docs/queues.md index 1b527475e2..e5559deef7 100644 --- a/src/docs/queues.md +++ b/src/docs/queues.md @@ -2072,7 +2072,7 @@ php artisan queue:work --timeout=30 If the job exceeds its maximum attempts by continually timing out, it will be marked as failed. -Hypervel checks for timed out jobs using a coroutine timer. With PCNTL enabled, the worker can also recover when PHP code blocks that timer. See [worker timeouts](#worker-timeouts) for cancellation and recovery behavior. You may configure how often the worker checks running jobs using the `--monitor-interval` option: +Hypervel checks for timed out jobs using a coroutine timer. See [worker timeouts](#worker-timeouts) for cancellation and recovery behavior. You may configure how often the worker checks running jobs using the `--monitor-interval` option: ```shell php artisan queue:work --monitor-interval=1 @@ -2098,7 +2098,7 @@ class ProcessPodcast implements ShouldQueue Sometimes, IO blocking processes such as sockets or outgoing HTTP connections may not respect your specified timeout. Therefore, when using these features, you should always attempt to specify a timeout using their APIs as well. For example, when using [Guzzle](https://docs.guzzlephp.org), you should always specify a connection and request timeout value. > [!WARNING] -> A job's "timeout" value should always be less than its ["retry after"](#job-expiration) value, allowing time for detection and cleanup. Otherwise, the job may be re-attempted before it has actually finished executing or timed out. The `--timeout` option has no effect when the `queue:work` command is invoked with the `--once` option. The [PCNTL](https://www.php.net/manual/en/book.pcntl.php) PHP extension enables graceful process signals and timeout recovery when PHP code blocks the event loop. +> A job's "timeout" value should always be less than its ["retry after"](#job-expiration) value, allowing time for detection and cleanup. Otherwise, the job may be re-attempted before it has actually finished executing or timed out. The `--timeout` option has no effect when the `queue:work` command is invoked with the `--once` option. #### Failing on Timeout @@ -3186,7 +3186,7 @@ By default, a timeout stops the worker process, including its other running jobs Use `finally` for cleanup and rethrow cancellation if caught. `CanceledException` extends `Exception`, so a broad `catch (Exception)` also catches it. If job code catches cancellation and completes, releases, or fails the attempt during cleanup, the worker preserves that outcome. If the coroutine remains active after the wait, the worker terminates without running failure handling concurrently with it. A remaining reservation becomes available again normally, but `FailOnTimeout`, ordinary exception counting, and failure callbacks cannot run on that path. -When PHP code blocks the event loop, the PCNTL alarm suspends the blocking coroutine so the timeout monitor can run failure handling before terminating the worker. Recovery, including the job's `failed` method, has `max(1, monitorInterval) + 1` seconds to finish (two seconds by default). A second alarm terminates the process when that deadline expires, even if recovery blocks again. Native calls that block signal handling cannot be interrupted this way. Other jobs interrupted by process termination recover through their queue reservations. +A job that blocks the event loop also blocks timeout checks and every other job in that worker. While blocked, the worker cannot act on stop signals, `--max-time`, `--max-jobs`, or `queue:restart`. If a job never yields or finishes, the worker needs an external restart. Deployments that need automatic recovery should use a health check that detects a lack of progress. To cancel only the timed-out job and keep the worker running, set the following property during application boot: @@ -3196,7 +3196,7 @@ use Hypervel\Queue\Worker; Worker::$killOnTimeout = false; ``` -In this mode, the job also receives `Swoole\Coroutine\CanceledException`. Once its code unwinds, the worker handles the timeout using the job's normal retry, backoff, and failure settings, including `FailOnTimeout`, and reports a `Hypervel\Queue\TimeoutExceededException`. Other jobs continue running. Once job execution finishes, the worker's failure handling and completion listeners finish without further timeout cancellation. A job that swallows cancellation and continues running keeps its concurrency slot. This mode does not use the PCNTL recovery alarm: cancellation requires the job to yield, so CPU-bound code cannot be interrupted by the coroutine timer. +In this mode, the job also receives `Swoole\Coroutine\CanceledException`. Once its code unwinds, the worker handles the timeout using the job's normal retry, backoff, and failure settings, including `FailOnTimeout`, and reports a `Hypervel\Queue\TimeoutExceededException`. Other jobs continue running. Once job execution finishes, the worker's failure handling and completion listeners finish without further timeout cancellation. A job that swallows cancellation and continues running keeps its concurrency slot. > [!WARNING] > Keep `--timeout` comfortably shorter than `retry_after`, with room for the monitor interval, cancellation, and failure cleanup. A timeout is not a guarantee that cleanup or process termination finishes before the reservation expires. Jobs may be delivered again after a worker stops, so make jobs safe to retry and set timeouts on external calls as well. @@ -4242,7 +4242,7 @@ When an interrupting signal is delivered to running jobs, Hypervel dispatches a Queue workers also dispatch a `WorkerStopping` event before they stop. You may register a listener using `Queue::stopping` in the `boot` method of a service provider. Its `connectionName` and `queue` properties identify the worker, while `terminatesImmediately` is `true` when the process will be terminated as soon as the listeners return. In that case, listeners should not start cleanup that must finish after the listener returns. -When a job times out, the worker normally ends its own process with `SIGKILL`, so a process supervisor sees the signal rather than an exit status. If you need to control how the worker terminates, you may register a callback using `Hypervel\Queue\Worker::killUsing` in a service provider's `boot` method. The callback receives the worker's exit status after the `WorkerStopping` event is dispatched. If the callback returns, the worker is terminated as usual. Exceptions from stopping listeners or the callback are reported and do not prevent termination. During [blocked-loop recovery](#worker-timeouts), emergency termination can occur before stopping listeners or the callback finish. +When a job times out, the worker normally ends its own process with `SIGKILL`, so a process supervisor sees the signal. When the worker is the main process in a container (PID 1), it exits with the worker's exit status instead. If you need to control how the worker terminates, you may register a callback using `Hypervel\Queue\Worker::killUsing` in a service provider's `boot` method. The callback receives the worker's exit status after the `WorkerStopping` event is dispatched. If the callback returns, the worker is terminated as usual. Exceptions from stopping listeners or the callback are reported and do not prevent termination. ## Credits diff --git a/src/queue/README.md b/src/queue/README.md index 64abb4dc1c..c6cf9e9836 100644 --- a/src/queue/README.md +++ b/src/queue/README.md @@ -11,7 +11,7 @@ Documentation: https://hypervel.org/docs/queues - Daemon jobs own their database routing, log context and scoped-container state. Laravel's `Worker::$flushStickyConnections` setting and the worker constructor's `$resetScope` callback are omitted; a worker-wide reset could affect concurrent jobs. `JobAttempted::$memoryUsage` reports PHP's peak allocated memory across jobs in the worker. See [porting queues](https://hypervel.org/docs/porting-from-laravel#queues). - Laravel's DynamoDB failed-job provider is not provided. Use database or file storage for failed jobs. - Custom job implementations must support `JobLifecycleCallbacks` to use `CountCrashesAsExceptions`, so cleanup completes before a concurrent retry starts. The base `Jobs\Job` already implements it; the `Job` contract is unchanged. See [counting worker crashes](https://hypervel.org/docs/queues#counting-worker-crashes). -- Timeouts unwind yielding job code with Swoole's `CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation if caught. The worker stops after timeout handling by default, with a bounded wait for cleanup; `Worker::$killOnTimeout = false` keeps other jobs running. See [worker timeouts](https://hypervel.org/docs/queues#worker-timeouts) for cleanup and blocked-loop recovery. +- Timeouts unwind yielding job code with Swoole's `CanceledException`, starting its `catch` and `finally` blocks. Use `finally` for cleanup and rethrow cancellation if caught. The worker stops after timeout handling by default, with a bounded wait for cleanup; `Worker::$killOnTimeout = false` keeps other jobs running. Timeout checks require a responsive event loop. See [worker timeouts](https://hypervel.org/docs/queues#worker-timeouts). - The protected `enqueueUsing()` callback receives the queue that owns the operation as its first argument. This lets deferred work borrow a fresh pooled queue connection after a database transaction commits instead of retaining a connection for the lifetime of the transaction. - Positive per-message delays on SQS FIFO queues throw `LogicException`. Laravel silently omits the delay and sends the job immediately. - `RateLimited::releaseAfter(0)` requests an immediate retry. Laravel treats zero as absent and uses the limiter's computed retry delay. diff --git a/src/queue/composer.json b/src/queue/composer.json index 4f660dcfb2..b7490d6e82 100644 --- a/src/queue/composer.json +++ b/src/queue/composer.json @@ -24,6 +24,8 @@ }, "require": { "php": "^8.4", + "ext-pcntl": "*", + "ext-posix": "*", "hypervel/attributes": "^0.4", "hypervel/bus": "^0.4", "hypervel/cache": "^0.4", diff --git a/src/queue/src/Worker.php b/src/queue/src/Worker.php index 0ac4a99bfb..6cfd0ae956 100644 --- a/src/queue/src/Worker.php +++ b/src/queue/src/Worker.php @@ -4,6 +4,7 @@ namespace Hypervel\Queue; +use Hypervel\Container\Container; use Hypervel\Context\CoroutineContext; use Hypervel\Contracts\Cache\Repository as CacheContract; use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract; @@ -16,6 +17,7 @@ use Hypervel\Contracts\Queue\Queue as QueueContract; use Hypervel\Coordinator\Timer; use Hypervel\Coroutine\Coroutine as FrameworkCoroutine; +use Hypervel\Coroutine\SignalRegistry; use Hypervel\Coroutine\WaitConcurrent; use Hypervel\Coroutine\Waiter; use Hypervel\Coroutine\WaitGroup; @@ -51,7 +53,6 @@ use Hypervel\Support\Str; use LogicException; use PDOException; -use RuntimeException; use Swoole\Coroutine\CanceledException; use Throwable; @@ -113,7 +114,7 @@ class Worker /** * The timeout job IDs. * - * @var array + * @var array */ protected array $timeoutJobIds = []; @@ -129,36 +130,6 @@ class Worker */ protected ?int $monitorId = null; - /** - * The independent event-loop liveness timer. - */ - protected ?int $livenessTimerId = null; - - /** - * The last time the event loop made progress. - */ - protected float $lastLoopProgressAt = 0; - - /** - * Indicates whether this daemon owns the timeout alarm. - */ - protected bool $ownsTimeoutAlarm = false; - - /** - * The deadline currently armed with PCNTL. - */ - protected ?float $timeoutAlarmAt = null; - - /** - * Indicates that blocked-loop recovery has committed to terminating the worker. - */ - protected bool $recoveringBlockedLoop = false; - - /** - * The coroutine frozen by emergency recovery. - */ - protected ?int $parkedCoroutineId = null; - /** * The timer that owns the timeout monitor. */ @@ -175,7 +146,7 @@ class Worker protected ?float $lastJobProcessedAt = null; /** - * Signals awaiting delivery outside the asynchronous PCNTL handler. + * Worker control signals awaiting delivery in the daemon loop. * * @var list */ @@ -312,10 +283,7 @@ public function daemon(string $connectionName, string $queue, WorkerOptions $opt { $this->pendingSignals = []; - if ($this->supportsAsyncSignals()) { - $this->listenForSignals($connectionName, $queue, $options); - } - + $supportsAsyncSignals = $this->supportsAsyncSignals(); $startTime = $this->currentTime(); $jobsAdmitted = 0; @@ -329,25 +297,28 @@ public function daemon(string $connectionName, string $queue, WorkerOptions $opt $this->lastPolledQueues = null; $lifecycleWaiter = new Waiter(-1); - $lastRestart = $lifecycleWaiter->wait(fn (): ?int => $this->withCoroutineContext( - $options, - function () use ($connectionName, $queue, $options): ?int { - $lastRestart = $this->getTimestampOfLastQueueRestart(); - $this->raiseWorkerStartingEvent($connectionName, $queue, $options); - - return $lastRestart; - }, - )); - $popWaiter = $this->createPopWaiter(); $concurrent = new WaitConcurrent($options->concurrency); try { - $this->startTimeoutAlarm($options); + if ($supportsAsyncSignals) { + $this->listenForSignals($connectionName, $queue, $options); + } + + $lastRestart = $lifecycleWaiter->wait(fn (): ?int => $this->withCoroutineContext( + $options, + function () use ($connectionName, $queue, $options): ?int { + $lastRestart = $this->getTimestampOfLastQueueRestart(); + $this->raiseWorkerStartingEvent($connectionName, $queue, $options); + + return $lastRestart; + }, + )); + $this->monitorTimeoutJobs($options, $connectionName, $queue); while (true) { - if ($this->recoveringBlockedLoop || (static::$killOnTimeout && $this->hasTimeoutJobs())) { + if (static::$killOnTimeout && $this->hasTimeoutJobs()) { $this->sleep(self::SHUTDOWN_WAIT_SECONDS); continue; @@ -439,7 +410,7 @@ function () use ($connectionName, $queue, $options): ?JobContract { return $job; }, )); - if ($this->recoveringBlockedLoop || (static::$killOnTimeout && $this->hasTimeoutJobs())) { + if (static::$killOnTimeout && $this->hasTimeoutJobs()) { // Leave an already reserved job for its normal reservation expiry. continue; } @@ -501,16 +472,8 @@ function () use ($connectionName, $queue, $options): ?JobContract { try { $concurrent->cancel(); } finally { - if ($this->ownsTimeoutAlarm && ! $this->recoveringBlockedLoop) { - pcntl_alarm(0); - pcntl_signal(SIGALRM, SIG_DFL); - $this->ownsTimeoutAlarm = false; - $this->timeoutAlarmAt = null; - } - - if ($this->livenessTimerId !== null) { - $this->timer->clear($this->livenessTimerId); - $this->livenessTimerId = null; + if ($supportsAsyncSignals) { + Container::getInstance()->make(SignalRegistry::class)->unregister($this); } if ($this->monitorId !== null) { @@ -630,99 +593,13 @@ protected function monitorTimeoutJobs( } /** - * Allow a full monitor interval plus whole-second alarm granularity. + * Get the maximum time to wait for canceled job coroutines to finish. */ protected function timeoutGracePeriod(WorkerOptions $options): int { return max(1, $options->monitorInterval) + 1; } - /** - * Recover kill-mode timeouts when PHP code prevents the monitor from running. - */ - protected function startTimeoutAlarm(WorkerOptions $options): void - { - if (! static::$killOnTimeout || ! $this->supportsAsyncSignals()) { - return; - } - - $this->ownsTimeoutAlarm = true; - $this->lastLoopProgressAt = $this->currentTime(); - pcntl_signal(SIGALRM, fn () => $this->handleTimeoutAlarm($options)); - - if (! pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM])) { - throw new RuntimeException('Unable to unblock the queue worker timeout alarm.'); - } - - // The timeout monitor can itself wait on yielding failure callbacks. - // Track the loop independently so those callbacks retain time to finish. - $this->livenessTimerId = $this->timer->tick(max(1, $options->monitorInterval), function (): void { - $this->lastLoopProgressAt = $this->currentTime(); - }); - } - - /** - * Arm an earlier timeout check without scanning jobs on the admission path. - */ - protected function armTimeoutAlarm(float $deadline): void - { - if (! $this->ownsTimeoutAlarm || $this->recoveringBlockedLoop - || ($this->timeoutAlarmAt !== null && $this->timeoutAlarmAt <= $deadline)) { - return; - } - - $this->timeoutAlarmAt = $deadline; - pcntl_alarm(max(1, (int) ceil($deadline - $this->currentTime()))); - } - - /** - * Give the normal timeout handler a bounded chance to recover a blocked loop. - */ - protected function handleTimeoutAlarm(WorkerOptions $options): void - { - $this->timeoutAlarmAt = null; - $deadline = null; - - foreach ($this->runningJobs as $job) { - if ($job['expires_at'] !== null) { - $deadline = $deadline === null ? $job['expires_at'] : min($deadline, $job['expires_at']); - } - } - - foreach ($this->timeoutJobIds as $expiresAt) { - $deadline = $deadline === null ? $expiresAt : min($deadline, $expiresAt); - } - - if ($deadline === null) { - return; - } - - $grace = $this->timeoutGracePeriod($options); - $now = $this->currentTime(); - if ($now < $deadline + $grace || $now < $this->lastLoopProgressAt + $grace) { - $this->armTimeoutAlarm(max($deadline + $grace, $this->lastLoopProgressAt + $grace)); - - return; - } - - $this->recoveringBlockedLoop = true; - $this->parkedCoroutineId = Coroutine::id(); - - // PHP cannot dispatch another signal callback while this one is parked. - // The kernel's default action still terminates a second stall or blocked cleanup. - pcntl_signal(SIGALRM, SIG_DFL); - pcntl_alarm($grace); - - try { - if (Coroutine::id() > 0) { - Coroutine::yield(); - } - } finally { - // Never return to the interrupted job if it is resumed or canceled. - $this->terminateProcess(static::$timedOutExitCode ?? static::EXIT_ERROR); - } - } - /** * Scan the running jobs and terminate the timeout jobs. */ @@ -738,7 +615,7 @@ protected function terminateTimeoutJobs(WorkerOptions $options): void } if ($job['expires_at'] !== null && $job['expires_at'] <= $currentTime) { - $this->timeoutJobIds[$jobId] = $job['expires_at']; + $this->timeoutJobIds[$jobId] = true; if (! static::$killOnTimeout) { $this->interruptTimeoutJob($jobId, $job); @@ -746,27 +623,16 @@ protected function terminateTimeoutJobs(WorkerOptions $options): void continue; } - $job['parked'] = $job['coroutine_id'] === $this->parkedCoroutineId; $expiredJobs[$jobId] = $job; } } - // A parked attempt cannot resume. Handle it before spending its kernel - // deadline waiting for other attempts to unwind. - foreach ($expiredJobs as $jobId => $job) { - if ($job['parked']) { - $this->notifyTimeoutJob($job['job']); - $this->handleTimeoutJob($job['job'], $options, $job['processing_marker']); - unset($expiredJobs[$jobId]); - } - } - $coroutineIds = []; foreach ($expiredJobs as $jobId => $job) { $this->interruptTimeoutJob($jobId, $job); - if ($job['coroutine_id'] !== $this->parkedCoroutineId && Coroutine::exists($job['coroutine_id'])) { + if (Coroutine::exists($job['coroutine_id'])) { $coroutineIds[] = $job['coroutine_id']; } } @@ -801,7 +667,6 @@ protected function interruptTimeoutJob(string $jobId, array $job): void $notification?->done(); if (isset($this->runningJobs[$jobId]) - && $job['coroutine_id'] !== $this->parkedCoroutineId && Coroutine::exists($job['coroutine_id'])) { // @TODO: Pass TimeoutExceededException as the cancellation reason if Swoole adds cancellation reasons. Coroutine::cancelById($job['coroutine_id'], throwException: true); @@ -1453,10 +1318,6 @@ protected function registerCoroutineJob(JobContract $job, WorkerOptions $options : null, ]; - if ($this->runningJobs[$jobId]['expires_at'] !== null) { - $this->armTimeoutAlarm($this->runningJobs[$jobId]['expires_at'] + $this->timeoutGracePeriod($options)); - } - return $jobId; } @@ -1775,29 +1636,17 @@ protected function getTimestampOfLastQueueRestart(): ?int } /** - * Enable async signals for the process. + * Listen for worker control signals through the coroutine runtime. */ protected function listenForSignals(string $connectionName, string $queue, WorkerOptions $options): void { - // queue:work owns PCNTL signals in its console process. A Swoole server process - // must use SignalManager instead; registering both would create competing consumers. - pcntl_async_signals(true); - - foreach ([SIGQUIT, SIGTERM, SIGINT] as $signal) { - pcntl_signal($signal, fn (int $signal) => $this->handleInterruptionSignal( - $signal, - $connectionName, - $queue, - $options - )); - } - - pcntl_signal(SIGUSR2, fn () => $this->handlePauseSignal($connectionName, $queue, $options)); - pcntl_signal(SIGCONT, fn () => $this->handleResumeSignal($connectionName, $queue, $options)); - - if (! pcntl_sigprocmask(SIG_UNBLOCK, self::HANDLED_SIGNALS)) { - throw new RuntimeException('Unable to unblock queue worker signals.'); - } + Container::getInstance()->make(SignalRegistry::class)->register($this, self::HANDLED_SIGNALS, function (int $signal) use ($connectionName, $queue, $options): void { + match ($signal) { + SIGUSR2 => $this->handlePauseSignal($connectionName, $queue, $options), + SIGCONT => $this->handleResumeSignal($connectionName, $queue, $options), + default => $this->handleInterruptionSignal($signal, $connectionName, $queue, $options), + }; + }); } /** @@ -1997,6 +1846,10 @@ protected function terminateProcess(int $status): never { posix_kill(getmypid(), SIGKILL); + // A container's PID 1 ignores its own SIGKILL. Replace the process to exit + // without running application preload or resuming any job coroutines. + pcntl_exec(PHP_BINARY, ['-n', '-r', "exit({$status});"]); + exit($status); } diff --git a/tests/Queue/Fixtures/timeout-worker.php b/tests/Queue/Fixtures/timeout-worker.php index a985ce7250..2d8524e481 100644 --- a/tests/Queue/Fixtures/timeout-worker.php +++ b/tests/Queue/Fixtures/timeout-worker.php @@ -2,28 +2,22 @@ declare(strict_types=1); -use Hypervel\Bus\Dispatcher as BusDispatcher; use Hypervel\Container\Container; use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Events\Dispatcher as DispatcherContract; use Hypervel\Contracts\Queue\Factory; -use Hypervel\Contracts\Queue\Interruptible; use Hypervel\Contracts\Queue\Job; -use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Database\Capsule\Manager; use Hypervel\Events\Dispatcher; -use Hypervel\Queue\CallQueuedHandler; use Hypervel\Queue\DatabaseQueue; use Hypervel\Queue\Events\JobFailed; use Hypervel\Queue\Events\JobTimedOut; use Hypervel\Queue\Events\WorkerStopping; use Hypervel\Queue\Failed\DatabaseUuidFailedJobProvider; -use Hypervel\Queue\InteractsWithQueue; use Hypervel\Queue\Worker; use Hypervel\Queue\WorkerOptions; use JMac\Testing\Double; use Swoole\Coroutine; -use Swoole\Coroutine\Channel; use Swoole\Runtime; require dirname(__DIR__, 3) . '/vendor/autoload.php'; @@ -34,7 +28,7 @@ class TimeoutWorkerJob { /** - * Block the loop on the first attempt and complete a subsequent delivery. + * Time out the first attempt and complete a subsequent delivery. */ public function fire(Job $job, array $data): void { @@ -84,11 +78,7 @@ public function fire(Job $job, array $data): void return; } - if (in_array($data['mode'], ['yielding', 'blocked-cleanup'], true)) { - Coroutine::sleep(30); - } else { - while (true); - } + Coroutine::sleep(30); } /** @@ -102,40 +92,12 @@ public function failed(array $data, Throwable $exception, string $uuid, Job $job } } -class LateParkTimeoutWorkerJob implements Interruptible, ShouldQueue -{ - use InteractsWithQueue; - - protected ?Channel $gate = null; - - /** - * Block the loop only after the monitor has declared the timeout. - */ - public function handle(): void - { - echo 'attempt:', $this->job->attempts(), "\n"; - $this->gate = new Channel(1); - $this->gate->pop(30); - - while (true); - } - - /** - * Resume the attempt while its timeout notification is still on the stack. - */ - public function interrupted(int $signal): void - { - $this->gate->push(true); - } -} - Runtime::enableCoroutine(SWOOLE_HOOK_ALL); Coroutine\run(static function () use ($argv): void { [$script, $databasePath, $mode] = $argv; $container = new Container; Container::setInstance($container); - $container->instance(CallQueuedHandler::class, new CallQueuedHandler(new BusDispatcher($container), $container)); $database = new Manager($container); $database->addConnection(['driver' => 'sqlite', 'database' => $databasePath]); $connection = $database->getConnection(); @@ -155,12 +117,8 @@ public function interrupted(int $signal): void $failures->log($event->connectionName, $event->job->getQueue(), $event->job->getRawBody(), $event->exception); echo "failure-recorded\n"; }); - $events->listen(JobTimedOut::class, static function () use ($mode): void { + $events->listen(JobTimedOut::class, static function (): void { echo "timed-out\n"; - - if (in_array($mode, ['reblock', 'blocked-cleanup'], true)) { - while (true); - } }); $events->listen(WorkerStopping::class, static function (): void { echo "stopping\n"; @@ -174,10 +132,8 @@ public function interrupted(int $signal): void if ($mode !== 'finish') { $queue->pushRaw(json_encode([ 'uuid' => 'timeout-worker-job', - 'job' => $mode === 'late-park' ? CallQueuedHandler::class . '@call' : TimeoutWorkerJob::class . '@fire', - 'data' => $mode === 'late-park' - ? ['commandName' => LateParkTimeoutWorkerJob::class, 'command' => serialize(new LateParkTimeoutWorkerJob)] - : ['mode' => $mode], + 'job' => TimeoutWorkerJob::class . '@fire', + 'data' => ['mode' => $mode], 'maxTries' => 3, 'timeout' => 1, 'failOnTimeout' => $mode !== 'retry', diff --git a/tests/Queue/WorkerTimeoutTest.php b/tests/Queue/WorkerTimeoutTest.php index 54665e29d9..d1fe488bee 100644 --- a/tests/Queue/WorkerTimeoutTest.php +++ b/tests/Queue/WorkerTimeoutTest.php @@ -60,13 +60,12 @@ public function testTimeoutRunsFailureHandlingBeforeTerminating(string $mode, st } /** - * Cover blocked PHP and slow failure cleanup with a healthy event loop. + * Cover yielding jobs and their failure cleanup. */ public static function timeoutModes(): array { return [ - 'CPU-bound job' => ['fail', ''], - 'yielding failure cleanup outlives the alarm grace' => ['yielding', ''], + 'slow failure cleanup' => ['yielding', ''], 'manually suspended job' => ['suspended', ''], 'job cleanup finishes before failure handling' => ['unwind', "unwind-start\nunwind-finished\n"], ]; @@ -92,24 +91,12 @@ public function testTimedOutJobCanBeRetriedAfterItsReservationExpires(): void $this->assertSame(0, (int) $database->query('SELECT COUNT(*) FROM jobs')->fetchColumn()); } - #[TestWith(['reblock'])] - #[TestWith(['blocked-cleanup'])] - public function testKernelAlarmTerminatesRecoveryThatBlocksAgain(string $mode): void + public function testUnfinishedAttemptIsLeftReservedInsteadOfFailedConcurrently(): void { - $process = $this->runWorker($mode); - - $this->assertSame(SIGALRM, $process->getTermSignal()); - $this->assertSame("attempt:1\nfailed-start\nfailed-finished\nfailure-recorded\ntimed-out\n", $process->getOutput()); - } - - #[TestWith(['unwind-stall', "unwind-start\n"])] - #[TestWith(['late-park', ''])] - public function testUnfinishedAttemptIsLeftReservedInsteadOfFailedConcurrently(string $mode, string $cleanupOutput): void - { - $process = $this->runWorker($mode); + $process = $this->runWorker('unwind-stall'); $this->assertSame(SIGKILL, $process->getTermSignal()); - $this->assertSame("attempt:1\n" . $cleanupOutput . "timed-out\nstopping\nkill-callback\n", $process->getOutput()); + $this->assertSame("attempt:1\nunwind-start\ntimed-out\nstopping\nkill-callback\n", $process->getOutput()); $database = new PDO('sqlite:' . $this->directory . '/queue.sqlite'); $this->assertSame(0, (int) $database->query('SELECT COUNT(*) FROM failed_jobs')->fetchColumn()); $jobs = $database->query('SELECT attempts, reserved_at FROM jobs')->fetchAll(PDO::FETCH_ASSOC); From e3575f15fcb50f0fd0a44e27a2eed2f1cddcb812 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:02:25 +0000 Subject: [PATCH 02/11] Serialize Horizon shutdown on the supervisor monitor loop Use coroutine signal handlers for supervisors and command traps for foreground Horizon processes. Queue an interrupt for the master to handle on its monitor loop so it cannot republish its Redis record during shutdown. Remove the child startup masks that Swoole blocks. Keep child replacement under supervisor control and cover an interrupt that arrives while a supervisor still needs time to stop. --- src/horizon/src/Console/HorizonCommand.php | 7 +- .../src/Console/HorizonRestartStrategy.php | 11 -- src/horizon/src/Console/ListenCommand.php | 1 + src/horizon/src/ListensForSignals.php | 37 ++-- src/horizon/src/MasterSupervisor.php | 29 +++- src/horizon/src/Supervisor.php | 21 ++- src/horizon/src/SupervisorProcess.php | 10 -- src/horizon/src/WorkerProcess.php | 38 +---- .../Horizon/Feature/HorizonCommandTest.php | 24 +++ .../Horizon/Feature/WorkerProcessTest.php | 158 ------------------ 10 files changed, 78 insertions(+), 258 deletions(-) diff --git a/src/horizon/src/Console/HorizonCommand.php b/src/horizon/src/Console/HorizonCommand.php index da318f6ebf..204083926d 100644 --- a/src/horizon/src/Console/HorizonCommand.php +++ b/src/horizon/src/Console/HorizonCommand.php @@ -44,14 +44,13 @@ public function handle(MasterSupervisorRepository $masters): int $this->components->info('Horizon started successfully.'); - pcntl_async_signals(true); - - pcntl_signal(SIGINT, function () use ($master) { + $this->trap(SIGINT, function () use ($master) { $this->output->writeln(''); $this->components->info('Shutting down.'); - $master->terminate(); + // The trap runs in another coroutine. Let the monitor loop shut down so it cannot recreate the master record. + $master->requestTermination(); }); return $master->monitor(); diff --git a/src/horizon/src/Console/HorizonRestartStrategy.php b/src/horizon/src/Console/HorizonRestartStrategy.php index e400347209..10a04ae568 100644 --- a/src/horizon/src/Console/HorizonRestartStrategy.php +++ b/src/horizon/src/Console/HorizonRestartStrategy.php @@ -23,17 +23,6 @@ public function __construct( protected OutputInterface $output, protected ?string $environment = null, ) { - pcntl_async_signals(true); - - pcntl_signal(SIGINT, function () { - $this->stop(); - exit(0); - }); - - pcntl_signal(SIGTERM, function () { - $this->stop(); - exit(0); - }); } /** diff --git a/src/horizon/src/Console/ListenCommand.php b/src/horizon/src/Console/ListenCommand.php index 37ac3ed9ba..5f41435648 100644 --- a/src/horizon/src/Console/ListenCommand.php +++ b/src/horizon/src/Console/ListenCommand.php @@ -59,6 +59,7 @@ public function handle(): int ]); $watcher = new Watcher($driver, $this->output, $strategy); + $this->trap([SIGINT, SIGTERM, SIGQUIT], fn () => $driver->stop()); $watcher->run(); return self::SUCCESS; diff --git a/src/horizon/src/ListensForSignals.php b/src/horizon/src/ListensForSignals.php index e975665b41..dd8c5fa765 100644 --- a/src/horizon/src/ListensForSignals.php +++ b/src/horizon/src/ListensForSignals.php @@ -4,7 +4,7 @@ namespace Hypervel\Horizon; -use RuntimeException; +use Hypervel\Coroutine\SignalRegistry; trait ListensForSignals { @@ -25,27 +25,24 @@ trait ListensForSignals */ protected function listenForSignals(): void { - pcntl_async_signals(true); - - pcntl_signal(SIGTERM, function () { - $this->pendingSignals['terminate'] = 'terminate'; - }); - - pcntl_signal(SIGUSR1, function () { - $this->pendingSignals['restart'] = 'restart'; - }); - - pcntl_signal(SIGUSR2, function () { - $this->pendingSignals['pause'] = 'pause'; - }); - - pcntl_signal(SIGCONT, function () { - $this->pendingSignals['continue'] = 'continue'; + app(SignalRegistry::class)->register($this, self::HANDLED_SIGNALS, function (int $signal): void { + $action = [ + SIGTERM => 'terminate', + SIGUSR1 => 'restart', + SIGUSR2 => 'pause', + SIGCONT => 'continue', + ][$signal]; + + $this->pendingSignals[$action] = $action; }); + } - if (! pcntl_sigprocmask(SIG_UNBLOCK, self::HANDLED_SIGNALS)) { - throw new RuntimeException('Unable to unblock Horizon process signals.'); - } + /** + * Release this process's signal handlers when monitoring ends. + */ + protected function stopListeningForSignals(): void + { + app(SignalRegistry::class)->unregister($this); } /** diff --git a/src/horizon/src/MasterSupervisor.php b/src/horizon/src/MasterSupervisor.php index 35214f5a10..4bde0912b4 100644 --- a/src/horizon/src/MasterSupervisor.php +++ b/src/horizon/src/MasterSupervisor.php @@ -143,6 +143,14 @@ public function continue(): void $this->supervisors->each->continue(); } + /** + * Schedule termination on the monitor loop. + */ + public function requestTermination(): void + { + $this->pendingSignals['terminate'] = 'terminate'; + } + /** * Terminate this master supervisor and all of its supervisors. */ @@ -197,19 +205,22 @@ public function monitor(): int { $this->ensureNoOtherMasterSupervisors(); - $this->listenForSignals(); + try { + $this->listenForSignals(); + $this->persist(); - $this->persist(); + while (true) { + // @phpstan-ignore hypervel.rawSleep (the monitor loop polls its processes in real time) + sleep(1); - while (true) { - // @phpstan-ignore hypervel.rawSleep (the monitor loop polls its processes in real time) - sleep(1); + $this->loop(); - $this->loop(); - - if ($this->exitStatus !== null) { - return $this->exitStatus; + if ($this->exitStatus !== null) { + return $this->exitStatus; + } } + } finally { + $this->stopListeningForSignals(); } } diff --git a/src/horizon/src/Supervisor.php b/src/horizon/src/Supervisor.php index 9d1aa30695..ca2ad3dedb 100644 --- a/src/horizon/src/Supervisor.php +++ b/src/horizon/src/Supervisor.php @@ -215,19 +215,22 @@ public function monitor(): int { $this->ensureNoDuplicateSupervisors(); - $this->listenForSignals(); - - $this->persist(); + try { + $this->listenForSignals(); + $this->persist(); - while (true) { - // @phpstan-ignore hypervel.rawSleep (the monitor loop polls its processes in real time) - sleep(1); + while (true) { + // @phpstan-ignore hypervel.rawSleep (the monitor loop polls its processes in real time) + sleep(1); - $this->loop(); + $this->loop(); - if ($this->exitStatus !== null) { - return $this->exitStatus; + if ($this->exitStatus !== null) { + return $this->exitStatus; + } } + } finally { + $this->stopListeningForSignals(); } } diff --git a/src/horizon/src/SupervisorProcess.php b/src/horizon/src/SupervisorProcess.php index b99bdeb200..e2d1dbbf6a 100644 --- a/src/horizon/src/SupervisorProcess.php +++ b/src/horizon/src/SupervisorProcess.php @@ -14,16 +14,6 @@ class SupervisorProcess extends WorkerProcess { - /** - * Signals handled by a supervisor after its application boots. - */ - protected const array STARTUP_SIGNALS = [ - SIGTERM, - SIGUSR1, - SIGUSR2, - SIGCONT, - ]; - /** * The name of the supervisor. */ diff --git a/src/horizon/src/WorkerProcess.php b/src/horizon/src/WorkerProcess.php index 556f065f23..783f86bb65 100644 --- a/src/horizon/src/WorkerProcess.php +++ b/src/horizon/src/WorkerProcess.php @@ -9,27 +9,14 @@ use Hypervel\Horizon\Events\UnableToLaunchProcess; use Hypervel\Horizon\Events\WorkerProcessRestarting; use Hypervel\Support\CarbonImmutable; -use RuntimeException; use Symfony\Component\Process\Exception\ExceptionInterface; use Symfony\Component\Process\Process; -use Throwable; /** * @mixin Process */ class WorkerProcess { - /** - * Signals handled by a queue worker after its application boots. - */ - protected const array STARTUP_SIGNALS = [ - SIGQUIT, - SIGTERM, - SIGINT, - SIGUSR2, - SIGCONT, - ]; - /** * The output handler callback. */ @@ -61,30 +48,7 @@ public function start(Closure $callback): static $this->cooldown(); - $previousMask = []; - - // Symfony's setIgnoredSignals() also suppresses Process::signal() on - // SIGCHLD builds. Horizon must still send these control signals, so - // only the fork-inherited process mask is changed here. - if (! pcntl_sigprocmask(SIG_BLOCK, static::STARTUP_SIGNALS, $previousMask)) { - throw new RuntimeException('Unable to block Horizon child startup signals.'); - } - - $exception = null; - - try { - $this->process->start($callback); - } catch (Throwable $throwable) { - $exception = $throwable; - } - - if (! pcntl_sigprocmask(SIG_SETMASK, $previousMask)) { - $exception ??= new RuntimeException('Unable to restore the Horizon parent signal mask.'); - } - - if ($exception !== null) { - throw $exception; - } + $this->process->start($callback); return $this; } diff --git a/tests/Integration/Horizon/Feature/HorizonCommandTest.php b/tests/Integration/Horizon/Feature/HorizonCommandTest.php index 33972bb539..f0ad9ee853 100644 --- a/tests/Integration/Horizon/Feature/HorizonCommandTest.php +++ b/tests/Integration/Horizon/Feature/HorizonCommandTest.php @@ -6,7 +6,11 @@ use Hypervel\Coroutine\Coroutine; use Hypervel\Horizon\Contracts\MasterSupervisorRepository; +use Hypervel\Horizon\Events\MasterSupervisorLooped; use Hypervel\Horizon\MasterSupervisor; +use Hypervel\Horizon\Supervisor; +use Hypervel\Support\Facades\Event; +use Hypervel\Tests\Integration\Horizon\Feature\Fixtures\EternalSupervisor; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; @@ -22,6 +26,26 @@ public function testAlreadyRunningMasterIsASuccessfulNoOp(): void ->assertExitCode(0); } + #[RunInSeparateProcess] + public function testInterruptForgetsTheMasterWhileWaitingForItsSupervisorToStop(): void + { + $supervisor = new EternalSupervisor; + $supervisor->options->timeout = 2; + (new Supervisor($supervisor->options))->persist(); + + Event::listen(MasterSupervisorLooped::class, static function (MasterSupervisorLooped $event) use ($supervisor): void { + if ($event->master->supervisors->isEmpty()) { + $event->master->supervisors->push($supervisor); + posix_kill(getmypid(), SIGINT); + } + }); + + $this->artisan('horizon', ['--environment' => 'empty'])->assertExitCode(0); + + $this->assertTrue($supervisor->killed); + $this->assertNull(app(MasterSupervisorRepository::class)->find(MasterSupervisor::name())); + } + #[DataProvider('environmentProvider')] #[RunInSeparateProcess] public function testCommandUsesTheSelectedEnvironment( diff --git a/tests/Integration/Horizon/Feature/WorkerProcessTest.php b/tests/Integration/Horizon/Feature/WorkerProcessTest.php index d4c0ef1bb0..bbe72e363e 100644 --- a/tests/Integration/Horizon/Feature/WorkerProcessTest.php +++ b/tests/Integration/Horizon/Feature/WorkerProcessTest.php @@ -4,24 +4,16 @@ namespace Hypervel\Tests\Integration\Horizon\Feature; -use Closure; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Horizon\Events\UnableToLaunchProcess; use Hypervel\Horizon\Events\WorkerProcessRestarting; -use Hypervel\Horizon\MasterSupervisor; -use Hypervel\Horizon\Supervisor; -use Hypervel\Horizon\SupervisorProcess; use Hypervel\Horizon\WorkerProcess; -use Hypervel\Queue\Worker as QueueWorker; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Integration\Horizon\IntegrationTestCase; use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; -use JMac\Testing\Matching\Argument; -use ReflectionClass; use ReflectionMethod; -use RuntimeException; use Symfony\Component\Process\Process; class WorkerProcessTest extends IntegrationTestCase @@ -54,100 +46,6 @@ public function testWorkerProcessSkipsOptionalEventsWhenTheyHaveNoListeners(): v (new ReflectionMethod(WorkerProcess::class, 'cooldown'))->invoke($failedWorker); } - public function testControlSignalSentDuringBootstrapIsDeliveredAfterHandlerInstallation(): void - { - $script = <<<'PHP' - pcntl_async_signals(true); - usleep(200_000); - $received = false; - pcntl_signal(SIGUSR2, static function () use (&$received): void { - $received = true; - }); - pcntl_sigprocmask(SIG_UNBLOCK, [SIGUSR2]); - $deadline = microtime(true) + 1.0; - while (! $received && microtime(true) < $deadline) { - usleep(1_000); - } - fwrite(STDOUT, $received ? 'received' : 'missing'); - PHP; - $output = ''; - $process = new WorkerProcess(new Process([PHP_BINARY, '-r', $script])); - - try { - $process->start(static function (string $type, string $buffer) use (&$output): void { - $output .= $buffer; - }); - - $process->pause(); - $exitCode = $process->wait(); - - $this->assertSame(0, $exitCode); - $this->assertSame('received', $output); - } finally { - $process->kill(); - } - } - - public function testStartRestoresTheParentSignalMaskAfterSuccess(): void - { - $before = $this->signalMask(); - $during = []; - $process = Double::for(Process::class)->strict(); - $process->allows('stop')->with(0.0); - $process->expects('start')->with(Argument::type(Closure::class))->resolves( - static function () use (&$during): void { - $during = self::signalMaskStatically(); - }, - ); - - (new WorkerProcess($process))->start(static function (): void { - }); - - $expectedDuring = array_values(array_unique([ - ...$before, - ...$this->queueWorkerSignals(), - ])); - sort($expectedDuring); - - $this->assertSame($expectedDuring, $during); - $this->assertSame($before, $this->signalMask()); - } - - public function testStartRestoresTheParentSignalMaskWhenStartThrows(): void - { - $before = $this->signalMask(); - $failure = new RuntimeException('start failed'); - $process = Double::for(Process::class)->strict(); - $process->allows('stop')->with(0.0); - $process->expects('start')->throws($failure); - - try { - (new WorkerProcess($process))->start(static function (): void { - }); - $this->fail('Expected process startup to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($failure, $exception); - } - - $this->assertSame($before, $this->signalMask()); - } - - public function testParentBlockSetsMatchTheChildHandlerSets(): void - { - $this->assertSame( - $this->constant(QueueWorker::class, 'HANDLED_SIGNALS'), - $this->constant(WorkerProcess::class, 'STARTUP_SIGNALS'), - ); - $this->assertSame( - $this->constant(Supervisor::class, 'HANDLED_SIGNALS'), - $this->constant(SupervisorProcess::class, 'STARTUP_SIGNALS'), - ); - $this->assertSame( - $this->constant(Supervisor::class, 'HANDLED_SIGNALS'), - $this->constant(MasterSupervisor::class, 'HANDLED_SIGNALS'), - ); - } - public function testKillStopsARunningProcessImmediately(): void { $timeouts = []; @@ -257,60 +155,4 @@ protected function waitForProcessToExit(Process $process): void $this->assertNotNull($process->getExitCode()); }); } - - /** - * Read the current process signal mask in stable numeric order. - * - * @return list - */ - private function signalMask(): array - { - return self::signalMaskStatically(); - } - - /** - * @return list - */ - private static function signalMaskStatically(): array - { - $mask = []; - - if (! pcntl_sigprocmask(SIG_BLOCK, [SIGUSR1], $mask)) { - throw new RuntimeException('Unable to read the process signal mask.'); - } - - if (! pcntl_sigprocmask(SIG_SETMASK, $mask)) { - throw new RuntimeException('Unable to restore the process signal mask.'); - } - - sort($mask); - - return $mask; - } - - /** - * @return list - */ - private function queueWorkerSignals(): array - { - $signals = $this->constant(QueueWorker::class, 'HANDLED_SIGNALS'); - sort($signals); - - return $signals; - } - - /** - * Read a protected signal-set constant. - * - * @param class-string $class - * @return list - */ - private function constant(string $class, string $name): array - { - $value = (new ReflectionClass($class))->getConstant($name); - - $this->assertIsArray($value); - - return $value; - } } From 0093d1c66408c6e4ad6e7e62acd6fc7cb0d4b307 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:02:25 +0000 Subject: [PATCH 03/11] Install PHPUnit deadline handlers outside the coroutine runtime Wrap the coroutine run with the native alarm handler so PHPUnit can interrupt CPU-bound tests. Preserve the cooperative deadline for suspended tests and avoid delivering a second timeout while cleanup is in progress. Move native signal setup for the affected Prompts tests outside the runtime while exercising their coroutine behavior. Declare the PCNTL dependency in the packages that use it. --- src/foundation/composer.json | 1 + .../Testing/Concerns/RunTestsInCoroutine.php | 57 +++++--- src/testbench/composer.json | 1 + tests/Prompts/ProgressSignalTest.php | 128 ++++++++++++++++++ tests/Prompts/ProgressTest.php | 127 ----------------- tests/Prompts/SpinnerNonCoroutineTest.php | 20 +++ tests/Prompts/SpinnerTest.php | 17 --- tests/Prompts/TaskProcessTest.php | 41 ++++++ tests/Prompts/TaskTest.php | 38 ------ .../Fixtures/TimeLimitAlarmFixture.php | 51 +++---- 10 files changed, 248 insertions(+), 233 deletions(-) diff --git a/src/foundation/composer.json b/src/foundation/composer.json index f895668710..6500eee403 100644 --- a/src/foundation/composer.json +++ b/src/foundation/composer.json @@ -25,6 +25,7 @@ "require": { "php": "^8.4", "ext-filter": "*", + "ext-pcntl": "*", "ext-posix": "*", "composer-runtime-api": "^2.2", "brick/math": "^1.0", diff --git a/src/foundation/src/Testing/Concerns/RunTestsInCoroutine.php b/src/foundation/src/Testing/Concerns/RunTestsInCoroutine.php index ee2fb2110e..fd985894e3 100644 --- a/src/foundation/src/Testing/Concerns/RunTestsInCoroutine.php +++ b/src/foundation/src/Testing/Concerns/RunTestsInCoroutine.php @@ -4,6 +4,7 @@ namespace Hypervel\Foundation\Testing\Concerns; +use Closure; use Hypervel\Context\CoroutineContext; use Hypervel\Coordinator\Constants; use Hypervel\Coordinator\CoordinatorManager; @@ -69,11 +70,13 @@ protected function invokeTestMethod(string $methodName, array $testArguments): m } }; - run(function () use (&$testResult, &$exception, &$timeoutException, &$rootCompleted, $capture, $methodName, $testArguments): void { + $this->runWithTestTimeLimit($timeoutException, function (?float $deadline) use (&$testResult, &$exception, &$timeoutException, &$rootCompleted, $capture, $methodName, $testArguments): void { $shouldBootFramework = false; try { - $this->enforceCoroutineTestTimeLimit($timeoutException, $rootCompleted); + if ($deadline !== null) { + $this->enforceCoroutineTestTimeLimit($deadline, $timeoutException, $rootCompleted); + } $this->clearNonCoroutineTransactionContext(); if ($this->copyNonCoroutineContext) { @@ -127,24 +130,50 @@ protected function invokeTestMethod(string $methodName, array $testArguments): m } /** - * Enforce PHPUnit's deadline while the test or its children are suspended. + * Run the test while preserving PHPUnit's native deadline for non-yielding code. + * + * @param Closure(?float): void $test */ - protected function enforceCoroutineTestTimeLimit(?TimeoutException &$timeoutException, bool &$rootCompleted): void + private function runWithTestTimeLimit(?TimeoutException &$timeoutException, Closure $test): void { - if (! function_exists('pcntl_alarm')) { + $handler = pcntl_signal_get_handler(SIGALRM); + $remaining = is_callable($handler) ? pcntl_alarm(0) : 0; + if ($remaining === 0) { + run(static fn () => $test(null)); return; } - // Keep the native alarm armed so non-yielding tests are still interrupted. - $remaining = pcntl_alarm(0); - pcntl_alarm($remaining); + $deadline = hrtime(true) / 1e9 + $remaining; + // Swoole owns signal registration while the runtime is active. A late native + // alarm must not interrupt cleanup after the coroutine watchdog has fired. + pcntl_signal(SIGALRM, static function (int $signal, ?array $info) use ($handler, &$timeoutException): void { + if ($timeoutException === null) { + // @phpstan-ignore arguments.count (PCNTL passes the signal number and siginfo to the installed handler) + $handler($signal, $info); + } + }); - if ($remaining === 0) { - return; + try { + pcntl_alarm($remaining); + run(static fn () => $test($deadline)); + } finally { + try { + if ($timeoutException !== null) { + pcntl_alarm(0); + pcntl_signal_dispatch(); + } + } finally { + pcntl_signal(SIGALRM, $handler); + } } + } + /** + * Enforce PHPUnit's deadline while the test or its children are suspended. + */ + protected function enforceCoroutineTestTimeLimit(float $deadline, ?TimeoutException &$timeoutException, bool &$rootCompleted): void + { $root = Coroutine::getCid(); - $deadline = hrtime(true) / 1e9 + $remaining; // Buffer the exit signal so cleanup cannot block after the deadline has expired. $completed = new Channel(1); // Register first so the signal follows all other root cleanup defers. @@ -184,11 +213,7 @@ protected function enforceCoroutineTestTimeLimit(?TimeoutException &$timeoutExce } } - // Cancel the native alarm while protected so it cannot fire during cleanup. - pcntl_alarm(0); - pcntl_signal_dispatch(); - - throw new TimeoutException('The coroutine test exceeded its time limit.'); + throw $timeoutException = new TimeoutException('The coroutine test exceeded its time limit.'); } catch (TimeoutException $exception) { $timeoutException = $exception; diff --git a/src/testbench/composer.json b/src/testbench/composer.json index 46ab522d50..7b03d44dea 100644 --- a/src/testbench/composer.json +++ b/src/testbench/composer.json @@ -26,6 +26,7 @@ "php": "^8.4", "composer/semver": "^3.5.1", "composer-runtime-api": "^2.2", + "ext-pcntl": "*", "ext-posix": "*", "mockery/mockery": "^1.6.15", "phpunit/phpunit": "~13.4.3", diff --git a/tests/Prompts/ProgressSignalTest.php b/tests/Prompts/ProgressSignalTest.php index 8725003eee..3a7b5b8c9b 100644 --- a/tests/Prompts/ProgressSignalTest.php +++ b/tests/Prompts/ProgressSignalTest.php @@ -11,8 +11,11 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; +use WeakReference; use function Hypervel\Coroutine\run; @@ -39,6 +42,131 @@ protected function tearDown(): void parent::tearDown(); } + #[RunInSeparateProcess] + public function testRestoresExactSignalHandlerAndAsyncMode(): void + { + Prompt::fake(); + + foreach ([SIG_IGN, static function (): void { + }] as $index => $handler) { + $async = $index === 1; + pcntl_signal(SIGINT, $handler); + pcntl_async_signals($async); + + $progress = new Progress('Working', 1); + $progress->start(); + $progress->finish(); + + $this->assertSame($handler, pcntl_signal_get_handler(SIGINT)); + $this->assertSame($async, pcntl_async_signals()); + } + } + + #[RunInSeparateProcess] + public function testRepeatedStartRestoresTheApplicationSignalState(): void + { + Prompt::fake(); + $previousHandler = static function (): void { + }; + pcntl_signal(SIGINT, $previousHandler); + pcntl_async_signals(false); + + $progress = new Progress('Working', 1); + $progress->start(); + $progress->start(); + $progress->finish(); + + $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); + $this->assertFalse(pcntl_async_signals()); + } + + #[RunInSeparateProcess] + #[TestWith([false])] + #[TestWith([true])] + public function testStartFailureRestoresExactSignalAndTerminalState(bool $canceled): void + { + Prompt::fake(); + $originalHandler = pcntl_signal_get_handler(SIGINT); + $originalAsync = pcntl_async_signals(); + $previousHandler = static function (): void { + }; + $failure = new RuntimeException('unable to render progress'); + $expected = $failure; + if ($canceled) { + $expected = new CanceledException; + Prompt::terminal()->shouldReceive('restoreTty')->once()->andThrow($expected); + } + $output = new class($failure) extends BufferedConsoleOutput { + /** @var list */ + public array $directWrites = []; + + public function __construct(private RuntimeException $failure) + { + parent::__construct(decorated: true); + } + + public function writeDirectly(string $message): void + { + $this->directWrites[] = $message; + } + + protected function doWrite(string $message, bool $newline): void + { + throw $this->failure; + } + }; + + pcntl_signal(SIGINT, $previousHandler); + pcntl_async_signals(false); + Prompt::setOutput($output); + + try { + $progress = new Progress('Working', 1); + + try { + $progress->start(); + + $this->fail('Expected the initial progress render to fail.'); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($expected, $exception); + } + + $this->assertSame(["\e[?25l", "\e[?25h"], $output->directWrites); + $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); + $this->assertFalse(pcntl_async_signals()); + $this->assertFalse( + (new ReflectionProperty(Prompt::class, 'cursorHidden'))->getValue(), + ); + } finally { + pcntl_signal(SIGINT, $originalHandler); + pcntl_async_signals($originalAsync); + } + } + + #[RunInSeparateProcess] + public function testAbandonedManualProgressRestoresSignalAndTerminalState(): void + { + Prompt::fake(); + $previousHandler = static function (): void { + }; + pcntl_signal(SIGINT, $previousHandler); + pcntl_async_signals(false); + + $progress = new Progress('Working', 1); + $reference = WeakReference::create($progress); + $progress->start(); + + unset($progress); + gc_collect_cycles(); + + $this->assertNull($reference->get()); + $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); + $this->assertFalse(pcntl_async_signals()); + $this->assertFalse( + (new ReflectionProperty(Prompt::class, 'cursorHidden'))->getValue(), + ); + } + #[RunInSeparateProcess] public function testSigintSettlesAndExitsWhenCancellationRenderingFails(): void { diff --git a/tests/Prompts/ProgressTest.php b/tests/Prompts/ProgressTest.php index 848370bf12..63987f824d 100644 --- a/tests/Prompts/ProgressTest.php +++ b/tests/Prompts/ProgressTest.php @@ -12,12 +12,10 @@ use Hypervel\Tests\TestCase; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; use RuntimeException; use Swoole\Coroutine\CanceledException; -use WeakReference; use function Hypervel\Prompts\progress; @@ -161,131 +159,6 @@ public function testProgressCanBeReusedWithoutStaleOperationState(): void $this->assertSame('submit', $progress->state); } - #[RunInSeparateProcess] - public function testRestoresExactSignalHandlerAndAsyncMode(): void - { - Prompt::fake(); - - foreach ([SIG_IGN, static function (): void { - }] as $index => $handler) { - $async = $index === 1; - pcntl_signal(SIGINT, $handler); - pcntl_async_signals($async); - - $progress = new Progress('Working', 1); - $progress->start(); - $progress->finish(); - - $this->assertSame($handler, pcntl_signal_get_handler(SIGINT)); - $this->assertSame($async, pcntl_async_signals()); - } - } - - #[RunInSeparateProcess] - public function testRepeatedStartRestoresTheApplicationSignalState(): void - { - Prompt::fake(); - $previousHandler = static function (): void { - }; - pcntl_signal(SIGINT, $previousHandler); - pcntl_async_signals(false); - - $progress = new Progress('Working', 1); - $progress->start(); - $progress->start(); - $progress->finish(); - - $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); - $this->assertFalse(pcntl_async_signals()); - } - - #[RunInSeparateProcess] - #[TestWith([false])] - #[TestWith([true])] - public function testStartFailureRestoresExactSignalAndTerminalState(bool $canceled): void - { - Prompt::fake(); - $originalHandler = pcntl_signal_get_handler(SIGINT); - $originalAsync = pcntl_async_signals(); - $previousHandler = static function (): void { - }; - $failure = new RuntimeException('unable to render progress'); - $expected = $failure; - if ($canceled) { - $expected = new CanceledException; - Prompt::terminal()->shouldReceive('restoreTty')->once()->andThrow($expected); - } - $output = new class($failure) extends BufferedConsoleOutput { - /** @var list */ - public array $directWrites = []; - - public function __construct(private RuntimeException $failure) - { - parent::__construct(decorated: true); - } - - public function writeDirectly(string $message): void - { - $this->directWrites[] = $message; - } - - protected function doWrite(string $message, bool $newline): void - { - throw $this->failure; - } - }; - - pcntl_signal(SIGINT, $previousHandler); - pcntl_async_signals(false); - Prompt::setOutput($output); - - try { - $progress = new Progress('Working', 1); - - try { - $progress->start(); - - $this->fail('Expected the initial progress render to fail.'); - } catch (CanceledException|RuntimeException $exception) { - $this->assertSame($expected, $exception); - } - - $this->assertSame(["\e[?25l", "\e[?25h"], $output->directWrites); - $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); - $this->assertFalse(pcntl_async_signals()); - $this->assertFalse( - (new ReflectionProperty(Prompt::class, 'cursorHidden'))->getValue(), - ); - } finally { - pcntl_signal(SIGINT, $originalHandler); - pcntl_async_signals($originalAsync); - } - } - - #[RunInSeparateProcess] - public function testAbandonedManualProgressRestoresSignalAndTerminalState(): void - { - Prompt::fake(); - $previousHandler = static function (): void { - }; - pcntl_signal(SIGINT, $previousHandler); - pcntl_async_signals(false); - - $progress = new Progress('Working', 1); - $reference = WeakReference::create($progress); - $progress->start(); - - unset($progress); - gc_collect_cycles(); - - $this->assertNull($reference->get()); - $this->assertSame($previousHandler, pcntl_signal_get_handler(SIGINT)); - $this->assertFalse(pcntl_async_signals()); - $this->assertFalse( - (new ReflectionProperty(Prompt::class, 'cursorHidden'))->getValue(), - ); - } - public function testCallbackFailureRendersOneUndecoratedErrorFrameAndSettles(): void { Prompt::fake(); diff --git a/tests/Prompts/SpinnerNonCoroutineTest.php b/tests/Prompts/SpinnerNonCoroutineTest.php index 7617195f9d..02094112cb 100644 --- a/tests/Prompts/SpinnerNonCoroutineTest.php +++ b/tests/Prompts/SpinnerNonCoroutineTest.php @@ -11,6 +11,9 @@ use ReflectionProperty; use RuntimeException; +use function Hypervel\Coroutine\run; +use function Hypervel\Prompts\spin; + class SpinnerNonCoroutineTest extends TestCase { protected bool $runTestsInCoroutine = false; @@ -28,6 +31,23 @@ public function testSpinnerRendersStaticallyOutsideACoroutine(): void Prompt::assertOutputContains('Running...'); } + public function testCoroutineSpinnerPreservesThePreviousSignalHandler(): void + { + Prompt::fake(); + + $originalSignalHandler = pcntl_signal_get_handler(SIGINT); + $signalHandler = fn (): null => null; + pcntl_signal(SIGINT, $signalHandler); + + try { + run(static fn () => spin(fn (): string => 'done', 'Running...')); + + $this->assertSame($signalHandler, pcntl_signal_get_handler(SIGINT)); + } finally { + pcntl_signal(SIGINT, $originalSignalHandler); + } + } + public function testEraseFailureStillRestoresTerminalState(): void { Prompt::fake(); diff --git a/tests/Prompts/SpinnerTest.php b/tests/Prompts/SpinnerTest.php index 3fe08cbf5c..0c2361388f 100644 --- a/tests/Prompts/SpinnerTest.php +++ b/tests/Prompts/SpinnerTest.php @@ -82,23 +82,6 @@ public function testAnimatesWhenOutputIsADecoratedTerminal(): void $this->assertFalse($spinner->static); } - public function testRestoresThePreviousSignalHandler(): void - { - Prompt::fake(); - - $originalSignalHandler = pcntl_signal_get_handler(SIGINT); - $signalHandler = fn (): null => null; - pcntl_signal(SIGINT, $signalHandler); - - try { - spin(fn (): string => 'done', 'Running...'); - - $this->assertSame($signalHandler, pcntl_signal_get_handler(SIGINT)); - } finally { - pcntl_signal(SIGINT, $originalSignalHandler); - } - } - #[TestWith([false])] #[TestWith([true])] public function testCallbackFailureRemainsPrimaryUnlessTerminalRestorationIsCanceled(bool $canceled): void diff --git a/tests/Prompts/TaskProcessTest.php b/tests/Prompts/TaskProcessTest.php index 16b4e7e8dd..98146f6598 100644 --- a/tests/Prompts/TaskProcessTest.php +++ b/tests/Prompts/TaskProcessTest.php @@ -14,6 +14,9 @@ use ReflectionProperty; use RuntimeException; +use function Hypervel\Coroutine\run; +use function Hypervel\Prompts\task; + class TaskProcessTest extends TestCase { protected bool $runTestsInCoroutine = false; @@ -36,6 +39,44 @@ protected function setUp(): void Prompt::theme('task-process-test'); } + public function testProcessSettlementPrintsCompletionLineOnlyAfterSuccess(): void + { + Prompt::fake(); + $originalAsync = pcntl_async_signals(); + $originalHandler = pcntl_signal_get_handler(SIGINT); + + try { + (new Task(label: 'Failed Task', keepSummary: true))->applyMessage('reset', "\x00"); + (new Task(label: 'Succeeded Task', keepSummary: true))->applyMessage('reset', "\x01"); + } finally { + pcntl_async_signals($originalAsync); + pcntl_signal(SIGINT, $originalHandler); + } + + Prompt::assertStrippedOutputDoesntContain('✔ Failed Task'); + Prompt::assertStrippedOutputContains('✔ Succeeded Task'); + } + + public function testCoroutineTaskPreservesThePreviousSignalHandler(): void + { + Prompt::fake(); + + $originalSignalHandler = pcntl_signal_get_handler(SIGINT); + $signalHandler = fn (): null => null; + pcntl_signal(SIGINT, $signalHandler); + + try { + run(static fn () => task( + label: 'Running...', + callback: fn (Logger $logger): null => null, + )); + + $this->assertSame($signalHandler, pcntl_signal_get_handler(SIGINT)); + } finally { + pcntl_signal(SIGINT, $originalSignalHandler); + } + } + #[RunInSeparateProcess] public function testSuccessfulRendererRestoresSignalAndTerminalStateAndReapsChild(): void { diff --git a/tests/Prompts/TaskTest.php b/tests/Prompts/TaskTest.php index 3b0800151d..cb5ffd0c51 100644 --- a/tests/Prompts/TaskTest.php +++ b/tests/Prompts/TaskTest.php @@ -119,24 +119,6 @@ public function testPrintsCompletionLineAfterSuccessfulCoroutineTaskWithSummary( Prompt::assertStrippedOutputContains('✔ My Task'); } - public function testProcessSettlementPrintsCompletionLineOnlyAfterSuccess(): void - { - Prompt::fake(); - $originalAsync = pcntl_async_signals(); - $originalHandler = pcntl_signal_get_handler(SIGINT); - - try { - (new Task(label: 'Failed Task', keepSummary: true))->applyMessage('reset', "\x00"); - (new Task(label: 'Succeeded Task', keepSummary: true))->applyMessage('reset', "\x01"); - } finally { - pcntl_async_signals($originalAsync); - pcntl_signal(SIGINT, $originalHandler); - } - - Prompt::assertStrippedOutputDoesntContain('✔ Failed Task'); - Prompt::assertStrippedOutputContains('✔ Succeeded Task'); - } - public function testUndecoratedTaskWritesPlainStartAndCompletionLines(): void { Prompt::fake(); @@ -308,26 +290,6 @@ public function testReturnsNullWhenCallbackDoesNotReturnValue(): void $this->assertNull($result); } - public function testRestoresThePreviousSignalHandler(): void - { - Prompt::fake(); - - $originalSignalHandler = pcntl_signal_get_handler(SIGINT); - $signalHandler = fn (): null => null; - pcntl_signal(SIGINT, $signalHandler); - - try { - task( - label: 'Running...', - callback: fn (Logger $logger): null => null, - ); - - $this->assertSame($signalHandler, pcntl_signal_get_handler(SIGINT)); - } finally { - pcntl_signal(SIGINT, $originalSignalHandler); - } - } - public function testCoroutinePathRendersLoggerOutput(): void { Prompt::fake(); diff --git a/tests/Testing/PHPUnit/Fixtures/TimeLimitAlarmFixture.php b/tests/Testing/PHPUnit/Fixtures/TimeLimitAlarmFixture.php index 7522bab5d5..a8ac8940ee 100644 --- a/tests/Testing/PHPUnit/Fixtures/TimeLimitAlarmFixture.php +++ b/tests/Testing/PHPUnit/Fixtures/TimeLimitAlarmFixture.php @@ -2,43 +2,24 @@ declare(strict_types=1); -namespace Hypervel\Foundation\Testing\Concerns { - use Hypervel\Tests\Testing\PHPUnit\Fixtures\TimeLimitAlarmFixture; +namespace Hypervel\Tests\Testing\PHPUnit\Fixtures; - /** - * Deliver a pending native alarm when the watchdog cancels it. - */ - function pcntl_alarm(int $seconds): int - { - if ($seconds === 0 && TimeLimitAlarmFixture::$deliverAlarm) { - TimeLimitAlarmFixture::$deliverAlarm = false; - file_put_contents((string) getenv('TIME_LIMIT_FIXTURE_LOG'), 'alarm delivered' . PHP_EOL, FILE_APPEND); - posix_kill(getmypid(), SIGALRM); - pcntl_signal_dispatch(); - } - - return \pcntl_alarm($seconds); - } -} +use Hypervel\Coroutine\Coroutine; +use Hypervel\Tests\TestCase; +use Swoole\Coroutine\Channel; -namespace Hypervel\Tests\Testing\PHPUnit\Fixtures { - use Hypervel\Tests\TestCase; - use Swoole\Coroutine; - - class TimeLimitAlarmFixture extends TestCase +class TimeLimitAlarmFixture extends TestCase +{ + public function testAlarmAtCancellationIsReportedAsTimeout(): void { - public static bool $deliverAlarm = false; - - public function testAlarmAtCancellationIsReportedAsTimeout(): void - { - // Keep the watchdog's deadline, but deliver the only SIGALRM at cancellation - // so the regression cannot depend on which real timer fires first. - \pcntl_alarm(0); - self::$deliverAlarm = true; - - Coroutine::sleep(30); - - $this->fail('The sleeping test was not interrupted.'); - } + Coroutine::create(static function (): void { + try { + (new Channel(1))->pop(30); + } finally { + posix_kill(getmypid(), SIGALRM); + pcntl_signal_dispatch(); + file_put_contents((string) getenv('TIME_LIMIT_FIXTURE_LOG'), 'alarm delivered' . PHP_EOL, FILE_APPEND); + } + }); } } From c62de2587bc8222f807a0535a4cdc4cfcb343efd Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:10:03 +0000 Subject: [PATCH 04/11] Install the Tinker test interrupt handler before starting the coroutine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep the caller’s native SIGINT setup and restoration outside the Swoole runtime. Execute the real Tinker command inside the coroutine and check both the exit status and the original handler afterwards for successful and failed evaluations. Isolate these two cases so all other Tinker tests keep their normal coroutine setup. This exposes dependency failures as command failures instead of failing during signal setup. --- tests/Tinker/TinkerCommandSignalTest.php | 53 ++++++++++++++++++++++++ tests/Tinker/TinkerCommandTest.php | 27 ------------ 2 files changed, 53 insertions(+), 27 deletions(-) create mode 100644 tests/Tinker/TinkerCommandSignalTest.php diff --git a/tests/Tinker/TinkerCommandSignalTest.php b/tests/Tinker/TinkerCommandSignalTest.php new file mode 100644 index 0000000000..d1e98503f8 --- /dev/null +++ b/tests/Tinker/TinkerCommandSignalTest.php @@ -0,0 +1,53 @@ +realArtisan('tinker', ['--execute' => $code]); + }); + + $this->assertSame($exitCode, $actualExitCode); + + $this->assertSame($sentinelHandler, pcntl_signal_get_handler(SIGINT)); + } finally { + pcntl_signal(SIGINT, $originalHandler); + } + } + + public static function directExecutionOutcomeProvider(): array + { + return [ + ['echo "hello";', 0], + ['throw new \Exception("fail");', 1], + ]; + } +} diff --git a/tests/Tinker/TinkerCommandTest.php b/tests/Tinker/TinkerCommandTest.php index a3aef02971..e8d57eecd1 100644 --- a/tests/Tinker/TinkerCommandTest.php +++ b/tests/Tinker/TinkerCommandTest.php @@ -245,33 +245,6 @@ public static function falseyExecuteCodeProvider(): array ]; } - #[DataProvider('directExecutionOutcomeProvider')] - public function testDirectExecutionPreservesTheSigintHandler(string $code, int $exitCode): void - { - $originalHandler = pcntl_signal_get_handler(SIGINT); - $sentinelHandler = static function (): void { - }; - - pcntl_signal(SIGINT, $sentinelHandler); - - try { - $this->artisan('tinker', ['--execute' => $code]) - ->assertExitCode($exitCode); - - $this->assertSame($sentinelHandler, pcntl_signal_get_handler(SIGINT)); - } finally { - pcntl_signal(SIGINT, $originalHandler); - } - } - - public static function directExecutionOutcomeProvider(): array - { - return [ - ['echo "hello";', 0], - ['throw new \Exception("fail");', 1], - ]; - } - public function testExecuteDoesNotChangeTheConsoleExceptionPolicy(): void { $application = $this->app->make(KernelContract::class)->getArtisan(); From 34c3614be01a320f48bb534bd92719cf1831e500 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:00 +0000 Subject: [PATCH 05/11] Disable Symfony signal events when creating the Artisan application MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A dispatcher attached after construction inherited Symfony’s default signal events. Running a command then installed native PCNTL handlers inside the coroutine. Set the default at construction so both early and late dispatchers use the same behavior. --- src/console/src/Application.php | 8 +++----- src/foundation/src/Console/Kernel.php | 1 - 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/console/src/Application.php b/src/console/src/Application.php index d054e416e4..9fcc767698 100644 --- a/src/console/src/Application.php +++ b/src/console/src/Application.php @@ -35,7 +35,6 @@ use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Process\PhpExecutableFinder; use Throwable; @@ -80,10 +79,9 @@ public function __construct( ) { parent::__construct('Hypervel Framework', $version); - if ($dispatcher instanceof EventDispatcher) { - $this->setDispatcher($dispatcher); - $this->setSignalsToDispatchEvent(); - } + // Commands trap signals through Swoole. Symfony's default signal events would install + // PCNTL handlers on every run, which Swoole rejects inside coroutines. + $this->setSignalsToDispatchEvent(); $this->setAutoExit(false); $this->setCatchExceptions(false); diff --git a/src/foundation/src/Console/Kernel.php b/src/foundation/src/Console/Kernel.php index fb2c124fb0..4aff0e5834 100644 --- a/src/foundation/src/Console/Kernel.php +++ b/src/foundation/src/Console/Kernel.php @@ -567,7 +567,6 @@ public function getArtisan(): ApplicationContract if ($this->symfonyDispatcher instanceof EventDispatcher) { $artisan->setDispatcher($this->symfonyDispatcher); - $artisan->setSignalsToDispatchEvent(); } $this->setArtisan($artisan); From 8286f44402964b170a02bc5a2e9646431789a22d Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:00 +0000 Subject: [PATCH 06/11] Stop the Horizon child when the file watcher is interrupted Stop the child as soon as a stop signal arrives, even while the file driver is waiting on a slow scan. Prevent a pending or interrupted restart from launching a new child during shutdown. Release the process reference before waiting so concurrent stops cannot both wait on the same process. Propagate coroutine cancellation out of both supervisor loops so monitoring unwinds and releases its signal handlers. Continue reporting ordinary exceptions as before. --- .../src/Console/HorizonRestartStrategy.php | 56 ++++++++++++++++--- src/horizon/src/Console/ListenCommand.php | 8 ++- src/horizon/src/MasterSupervisor.php | 6 ++ src/horizon/src/Supervisor.php | 6 ++ .../Console/HorizonRestartStrategyTest.php | 39 +++++++++++++ .../Horizon/Feature/MasterSupervisorTest.php | 13 +++++ .../Horizon/Feature/SupervisorTest.php | 13 +++++ 7 files changed, 131 insertions(+), 10 deletions(-) diff --git a/src/horizon/src/Console/HorizonRestartStrategy.php b/src/horizon/src/Console/HorizonRestartStrategy.php index 10a04ae568..1b5c74a2cf 100644 --- a/src/horizon/src/Console/HorizonRestartStrategy.php +++ b/src/horizon/src/Console/HorizonRestartStrategy.php @@ -18,6 +18,8 @@ class HorizonRestartStrategy implements RestartStrategy { protected ?Process $horizonProcess = null; + protected bool $stopping = false; + public function __construct( protected ApplicationContract $application, protected OutputInterface $output, @@ -30,23 +32,28 @@ public function __construct( */ public function start(): void { + $this->stopping = false; $environmentFile = $this->application->environmentFilePath(); DotenvManager::reload([dirname($environmentFile)], basename($environmentFile)); - $this->horizonProcess = $this->createProcess(); - $this->horizonProcess->start(function (string $type, string $line) { + if ($this->isStopping()) { + return; + } + + $process = $this->horizonProcess = $this->createProcess(); + $process->start(function (string $type, string $line) { $this->output->write($line); }); // @phpstan-ignore hypervel.rawSleep (gives the started Horizon process real time to fail) usleep(100_000); - if ($this->horizonProcess->isTerminated()) { + if (! $this->isStopping() && $process->isTerminated()) { $message = sprintf( 'Horizon failed to start with exit code [%s].', - $this->horizonProcess->getExitCode() ?? 'unknown', + $process->getExitCode() ?? 'unknown', ); - $errorOutput = trim($this->horizonProcess->getErrorOutput()); + $errorOutput = trim($process->getErrorOutput()); if ($errorOutput !== '') { $message .= ' ' . $errorOutput; @@ -61,10 +68,17 @@ public function start(): void */ public function restart(): void { + if ($this->isStopping()) { + return; + } + $this->output->writeln('File changed. Restarting Horizon...'); - $this->stop(); - $this->start(); + $this->stopProcess(); + + if (! $this->isStopping()) { + $this->start(); + } } /** @@ -72,8 +86,32 @@ public function restart(): void */ public function stop(): void { - if ($this->horizonProcess?->isRunning()) { - $this->horizonProcess->stop(); + $this->stopping = true; + $this->stopProcess(); + } + + /** + * Determine whether the strategy has been stopped. + * + * A signal can stop the strategy while a process operation yields. + * + * @phpstan-impure + */ + protected function isStopping(): bool + { + return $this->stopping; + } + + /** + * Stop the child without allowing two coroutines to wait on the same process. + */ + protected function stopProcess(): void + { + $process = $this->horizonProcess; + $this->horizonProcess = null; + + if ($process?->isRunning()) { + $process->stop(); } } diff --git a/src/horizon/src/Console/ListenCommand.php b/src/horizon/src/Console/ListenCommand.php index 5f41435648..734c1bb04f 100644 --- a/src/horizon/src/Console/ListenCommand.php +++ b/src/horizon/src/Console/ListenCommand.php @@ -59,7 +59,13 @@ public function handle(): int ]); $watcher = new Watcher($driver, $this->output, $strategy); - $this->trap([SIGINT, SIGTERM, SIGQUIT], fn () => $driver->stop()); + $this->trap([SIGINT, SIGTERM, SIGQUIT], function () use ($driver, $strategy): void { + try { + $driver->stop(); + } finally { + $strategy->stop(); + } + }); $watcher->run(); return self::SUCCESS; diff --git a/src/horizon/src/MasterSupervisor.php b/src/horizon/src/MasterSupervisor.php index 4bde0912b4..3e4c1a2e60 100644 --- a/src/horizon/src/MasterSupervisor.php +++ b/src/horizon/src/MasterSupervisor.php @@ -8,6 +8,7 @@ use Exception; use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Debug\ExceptionHandler; +use Hypervel\Coroutine\Coroutine; use Hypervel\Horizon\Contracts\HorizonCommandQueue; use Hypervel\Horizon\Contracts\MasterSupervisorRepository; use Hypervel\Horizon\Contracts\Pausable; @@ -258,6 +259,11 @@ public function loop(): void event(new MasterSupervisorLooped($this)); } catch (Throwable $e) { + // Let cancellation unwind the monitor and release its signal handlers. + if (Coroutine::causedByCancellation($e)) { + throw $e; + } + app(ExceptionHandler::class)->report($e); } } diff --git a/src/horizon/src/Supervisor.php b/src/horizon/src/Supervisor.php index ca2ad3dedb..01b9971f49 100644 --- a/src/horizon/src/Supervisor.php +++ b/src/horizon/src/Supervisor.php @@ -8,6 +8,7 @@ use Exception; use Hypervel\Contracts\Cache\Factory as CacheFactory; use Hypervel\Contracts\Debug\ExceptionHandler; +use Hypervel\Coroutine\Coroutine; use Hypervel\Horizon\Contracts\HorizonCommandQueue; use Hypervel\Horizon\Contracts\Pausable; use Hypervel\Horizon\Contracts\Restartable; @@ -276,6 +277,11 @@ public function loop(): void event(new SupervisorLooped($this)); } catch (Throwable $e) { + // Let cancellation unwind the monitor and release its signal handlers. + if (Coroutine::causedByCancellation($e)) { + throw $e; + } + app(ExceptionHandler::class)->report($e); } } diff --git a/tests/Horizon/Console/HorizonRestartStrategyTest.php b/tests/Horizon/Console/HorizonRestartStrategyTest.php index b54c2159b8..ff545f1155 100644 --- a/tests/Horizon/Console/HorizonRestartStrategyTest.php +++ b/tests/Horizon/Console/HorizonRestartStrategyTest.php @@ -15,6 +15,7 @@ use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; +use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Process\Process; @@ -116,6 +117,44 @@ public static function startupFailures(): array ]; } + #[TestWith([true], 'stop during startup')] + #[TestWith([false], 'stop during restart')] + public function testShutdownPreventsAnotherChildFromStarting(bool $duringStartup): void + { + $process = Double::for(Process::class)->strict(); + $process->allows('stop')->with(0.0); + $strategy = new class($this->app, new NullOutput, process: $process) extends HorizonRestartStrategy { + public function __construct(ApplicationContract $app, NullOutput $output, private Process $process) + { + parent::__construct($app, $output); + } + + protected function createProcess(): Process + { + return $this->process; + } + }; + $process->expects('start')->resolves(static function () use ($strategy, $duringStartup): void { + if ($duringStartup) { + $strategy->stop(); + } + }); + $process->expects('isRunning')->returns(true); + $process->expects('stop')->with()->resolves(static function () use ($strategy): int { + $strategy->stop(); + + return 0; + }); + + if (! $duringStartup) { + $process->expects('isTerminated')->returns(false); + } + + $strategy->start(); + $strategy->restart(); + $strategy->restart(); + } + #[RunInSeparateProcess] public function testStartAndRestartReloadTheConfiguredEnvironmentBeforeCreatingTheProcess(): void { diff --git a/tests/Integration/Horizon/Feature/MasterSupervisorTest.php b/tests/Integration/Horizon/Feature/MasterSupervisorTest.php index 33366ae6f2..37b2db7d56 100644 --- a/tests/Integration/Horizon/Feature/MasterSupervisorTest.php +++ b/tests/Integration/Horizon/Feature/MasterSupervisorTest.php @@ -23,6 +23,7 @@ use JMac\Testing\Double; use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; +use Swoole\Coroutine\CanceledException; use Symfony\Component\Process\Process; class MasterSupervisorTest extends IntegrationTestCase @@ -204,6 +205,18 @@ public function testMasterProcessInformationIsPersisted(): void $this->assertSame('paused', $masterRecord->status); } + public function testLoopPropagatesCancellation(): void + { + $master = new MasterSupervisor; + $master->working = false; + $cancellation = new CanceledException; + Event::listen(MasterSupervisorLooped::class, static fn () => throw $cancellation); + + $this->expectExceptionObject($cancellation); + + $master->loop(); + } + public function testMasterStateIsPersistedBeforeLoopedEvent(): void { $master = new MasterSupervisor; diff --git a/tests/Integration/Horizon/Feature/SupervisorTest.php b/tests/Integration/Horizon/Feature/SupervisorTest.php index e6d28d0dcb..e63f59cff0 100644 --- a/tests/Integration/Horizon/Feature/SupervisorTest.php +++ b/tests/Integration/Horizon/Feature/SupervisorTest.php @@ -32,6 +32,7 @@ use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\RequiresPhpExtension; +use Swoole\Coroutine\CanceledException; use Throwable; class SupervisorTest extends IntegrationTestCase @@ -217,6 +218,18 @@ public function testExceptionsAreCaughtAndHandledDuringLoop(): void $supervisor->loop(); } + public function testLoopPropagatesCancellation(): void + { + $supervisor = new Supervisor($this->supervisorOptions()); + $supervisor->working = false; + $cancellation = new CanceledException; + Event::listen(SupervisorLooped::class, static fn () => throw $cancellation); + + $this->expectExceptionObject($cancellation); + + $supervisor->loop(); + } + public function testSupervisorInformationIsPersisted(): void { $this->supervisor = $supervisor = new Supervisor($options = $this->supervisorOptions()); From 1bcff43d5a3c7b80bc2dcb7d2c0a98359d5d677d Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:01 +0000 Subject: [PATCH 07/11] Exit the container worker even when process replacement fails MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failed exec in the timeout monitor could leave PID 1 alive indefinitely because exit inside a coroutine throws. Stop the event loop when exec fails and apply the worker status during PHP shutdown. Successful exec still bypasses the old process’s shutdown handlers. Exercise both paths in a subprocess with a real timed-out job. Confirm the exit code, the reserved attempt, and that unfinished cleanup never resumes. --- src/queue/src/Worker.php | 9 ++++++- tests/Queue/Fixtures/container-worker.php | 30 +++++++++++++++++++++++ tests/Queue/WorkerTimeoutTest.php | 24 ++++++++++++++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/Queue/Fixtures/container-worker.php diff --git a/src/queue/src/Worker.php b/src/queue/src/Worker.php index 6cfd0ae956..e4eae14daa 100644 --- a/src/queue/src/Worker.php +++ b/src/queue/src/Worker.php @@ -54,6 +54,7 @@ use LogicException; use PDOException; use Swoole\Coroutine\CanceledException; +use Swoole\Event; use Throwable; class Worker @@ -1848,7 +1849,13 @@ protected function terminateProcess(int $status): never // A container's PID 1 ignores its own SIGKILL. Replace the process to exit // without running application preload or resuming any job coroutines. - pcntl_exec(PHP_BINARY, ['-n', '-r', "exit({$status});"]); + try { + pcntl_exec(PHP_BINARY, ['-n', '-r', "exit({$status});"]); + } finally { + // If exec fails, stop the event loop and apply the exit status outside the coroutine. + register_shutdown_function(static fn () => exit($status)); + Event::exit(); + } exit($status); } diff --git a/tests/Queue/Fixtures/container-worker.php b/tests/Queue/Fixtures/container-worker.php new file mode 100644 index 0000000000..0b6fb88b75 --- /dev/null +++ b/tests/Queue/Fixtures/container-worker.php @@ -0,0 +1,30 @@ +assertSame(0, (int) $database->query('SELECT COUNT(*) FROM jobs')->fetchColumn()); } + #[TestWith(['allow-exec'])] + #[TestWith(['deny-exec'])] + public function testContainerWorkerExitsWithItsTimeoutStatus(string $mode): void + { + $process = new Process([ + PHP_BINARY, + __DIR__ . '/Fixtures/container-worker.php', + $this->directory . '/queue.sqlite', + 'unwind-stall', + $mode, + ], timeout: 20); + $process->run(); + + $this->assertSame(17, $process->getExitCode(), $process->getErrorOutput()); + $this->assertStringContainsString('unwind-start', $process->getOutput()); + $this->assertStringNotContainsString('unwind-finished', $process->getOutput()); + if ($mode === 'allow-exec') { + $this->assertStringNotContainsString('shutdown callback', $process->getOutput()); + } + + $database = new PDO('sqlite:' . $this->directory . '/queue.sqlite'); + $this->assertSame(1, (int) $database->query('SELECT COUNT(*) FROM jobs WHERE reserved_at IS NOT NULL AND attempts = 1')->fetchColumn()); + } + public function testUnfinishedAttemptIsLeftReservedInsteadOfFailedConcurrently(): void { $process = $this->runWorker('unwind-stall'); From a9d7f55060fa976546f564b1f7d80b44b5f56715 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:01 +0000 Subject: [PATCH 08/11] Preserve HTTP/2 stream reset codes in gRPC responses Carry the peer reset code through the engine response and map it before decoding a gRPC message or interpreting HTTP status. A canceled stream whose local deadline has elapsed now reports DEADLINE_EXCEEDED instead of treating the native reset marker as an HTTP status. Retain earlier metadata, discard any incomplete frame and let other streams continue on the connection. Remove the obsolete platform limitation. --- .../src/Engine/Http/V2/ResponseInterface.php | 5 ++++ src/docs/grpc.md | 1 - src/engine/src/Http/V2/Client.php | 1 + src/engine/src/Http/V2/Response.php | 9 +++++++ src/grpc/src/Client/StreamState.php | 13 ++++++++++ src/grpc/src/Protocol/StatusCodec.php | 16 +++++++++++++ tests/Grpc/StreamStateTest.php | 24 +++++++++++++++++++ 7 files changed, 68 insertions(+), 1 deletion(-) diff --git a/src/contracts/src/Engine/Http/V2/ResponseInterface.php b/src/contracts/src/Engine/Http/V2/ResponseInterface.php index 85ed6840c0..9561ef3d1b 100644 --- a/src/contracts/src/Engine/Http/V2/ResponseInterface.php +++ b/src/contracts/src/Engine/Http/V2/ResponseInterface.php @@ -16,6 +16,11 @@ public function getStreamId(): int; */ public function getStatusCode(): int; + /** + * Get the HTTP/2 error code when the peer resets the stream. + */ + public function getResetCode(): ?int; + /** * Get the response headers. */ diff --git a/src/docs/grpc.md b/src/docs/grpc.md index 9c59254645..7bc06dc397 100644 --- a/src/docs/grpc.md +++ b/src/docs/grpc.md @@ -947,6 +947,5 @@ Hypervel's gRPC client and server are tested against an independent grpc-go impl - Hypervel servers support unary and server-streaming methods. Server-side client streaming and bidirectional streaming are not available because Swoole gives the request handler the complete body instead of exposing each incoming HTTP/2 data frame. Hypervel clients may use all four call types against compatible servers. - Swoole cannot reset an individual client stream. Calling `cancel` abandons the stream locally, reports `CANCELLED`, and retires the connection instead of sending `RST_STREAM`. Deadlines are still enforced. - Swoole may reduce independently repeated metadata fields to one value and does not expose the inbound `:scheme` pseudo-header. Hypervel preserves repeated values whenever the transport exposes them, but inbound duplicate-field and metadata-size validation can only cover the values Swoole provides. -- When a server resets a stream, only the affected client call fails. Swoole's HTTP/2 client does not expose the reset error code. - Swoole merges initial response metadata immediately followed by final metadata without a response message into one uncommitted response. Since this cannot be distinguished from a Trailers-Only response, an explicitly retry-enabled call may retry it. - The built-in health service returns `Unimplemented` from `Watch` because it does not publish health changes across workers. diff --git a/src/engine/src/Http/V2/Client.php b/src/engine/src/Http/V2/Client.php index c1937ddef1..6297486950 100644 --- a/src/engine/src/Http/V2/Client.php +++ b/src/engine/src/Http/V2/Client.php @@ -155,6 +155,7 @@ private function transformResponse(SwResponse $response): ResponseInterface $response->headers ?? [], $response->data, $response->pipeline, + $response->statusCode === SWOOLE_HTTP_CLIENT_ESTATUS_SERVER_RESET ? $response->errCode : null, ); } diff --git a/src/engine/src/Http/V2/Response.php b/src/engine/src/Http/V2/Response.php index 0b48ea6a54..90cd50e7b7 100644 --- a/src/engine/src/Http/V2/Response.php +++ b/src/engine/src/Http/V2/Response.php @@ -17,6 +17,7 @@ public function __construct( protected array $headers, protected ?string $body, protected bool $pipeline, + protected ?int $resetCode = null, ) { } @@ -36,6 +37,14 @@ public function getStatusCode(): int return $this->statusCode; } + /** + * Get the HTTP/2 error code when the peer resets the stream. + */ + public function getResetCode(): ?int + { + return $this->resetCode; + } + /** * Get the response headers. */ diff --git a/src/grpc/src/Client/StreamState.php b/src/grpc/src/Client/StreamState.php index a4c6d8a76b..4f891dafcf 100644 --- a/src/grpc/src/Client/StreamState.php +++ b/src/grpc/src/Client/StreamState.php @@ -121,6 +121,19 @@ public function handle(ResponseInterface $response): void throw new LogicException('The completed gRPC stream cannot accept another response event.'); } + if (($resetCode = $response->getResetCode()) !== null) { + $this->decoder = null; + $this->metadata ??= Metadata::make(); + $this->trailers = Metadata::make(); + $this->status = $resetCode === SWOOLE_HTTP2_ERROR_CANCEL && $this->deadline->expired() + ? new Status(StatusCode::DeadlineExceeded, 'The gRPC deadline was exceeded.') + : StatusCodec::fromResetCode($resetCode); + $this->onAbandon = null; + $this->signalWaiters(); + + return; + } + $headers = $response->getHeaders(); $endStream = $response->isEndStream(); $initialEvent = $this->initialEvent; diff --git a/src/grpc/src/Protocol/StatusCodec.php b/src/grpc/src/Protocol/StatusCodec.php index b990daaa70..3f357598ca 100644 --- a/src/grpc/src/Protocol/StatusCodec.php +++ b/src/grpc/src/Protocol/StatusCodec.php @@ -100,6 +100,22 @@ public static function parse(array $headers, int $httpStatus, bool $endStream): return new Status($code, $details->getMessage(), $details); } + /** + * Map an HTTP/2 stream reset to a gRPC status. + */ + public static function fromResetCode(int $resetCode): Status + { + $code = match ($resetCode) { + SWOOLE_HTTP2_ERROR_REFUSED_STREAM => StatusCode::Unavailable, + SWOOLE_HTTP2_ERROR_CANCEL => StatusCode::Cancelled, + SWOOLE_HTTP2_ERROR_ENHANCE_YOUR_CALM => StatusCode::ResourceExhausted, + SWOOLE_HTTP2_ERROR_INADEQUATE_SECURITY => StatusCode::PermissionDenied, + default => StatusCode::Internal, + }; + + return new Status($code, "The peer reset the HTTP/2 stream with error code {$resetCode}."); + } + /** * Map an HTTP response without grpc-status to a gRPC status. */ diff --git a/tests/Grpc/StreamStateTest.php b/tests/Grpc/StreamStateTest.php index 3a25397fb6..f87dda68ce 100644 --- a/tests/Grpc/StreamStateTest.php +++ b/tests/Grpc/StreamStateTest.php @@ -16,6 +16,7 @@ use Hypervel\Grpc\StatusCode; use Hypervel\Tests\TestCase; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; use Swoole\Coroutine\CanceledException; @@ -62,6 +63,29 @@ public function testProcessesInitialMetadataFramesAndFinalTrailersAcrossEvents() $this->assertFalse($state->trailersOnly()); } + #[TestWith([SWOOLE_HTTP2_ERROR_REFUSED_STREAM, false, StatusCode::Unavailable])] + #[TestWith([SWOOLE_HTTP2_ERROR_CANCEL, false, StatusCode::Cancelled])] + #[TestWith([SWOOLE_HTTP2_ERROR_CANCEL, true, StatusCode::DeadlineExceeded])] + public function testRemoteResetEndsTheStream(int $resetCode, bool $expired, StatusCode $status): void + { + $state = $this->state($expired ? Deadline::fromPeerTimeout(0) : null); + + $state->handle(new Response(1, -3, [], null, false, $resetCode)); + + $this->assertSame($status, $state->status()->code()); + $this->assertSame([], $state->metadata()->all()); + } + + public function testResetDiscardsAnIncompleteFrame(): void + { + $state = $this->state(); + $state->handle(new Response(1, 200, ['content-type' => 'application/grpc'], "\x00", true)); + $state->handle(new Response(1, -3, [], null, false, SWOOLE_HTTP2_ERROR_INTERNAL_ERROR)); + + $this->assertSame(StatusCode::Internal, $state->status()->code()); + $this->assertNull($state->nextMessage()); + } + public function testClassifiesFinalFirstEventAsTrailersOnly(): void { $state = $this->state(); From 5b37ee083ff2ed445cd3c72db777a25fc022e6ac Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:01 +0000 Subject: [PATCH 09/11] Clarify Redis cancellation behavior when the socket error is lost A native Redis read can close its stream before raising an exception, clearing the socket error on newer Swoole versions. Preserve the existing classification and describe which exception reaches the caller and failure listeners. Cover throwing and non-throwing cancellation with a partial bulk reply that retains the socket error. Keep the transaction and discard checks for cancellations that carry a cause. --- src/docs/redis.md | 2 ++ src/redis/src/RedisCancellation.php | 3 ++- tests/Redis/RedisCancellationLifecycleTest.php | 18 +++++++----------- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/docs/redis.md b/src/docs/redis.md index b1d9cc6854..5fe6511278 100644 --- a/src/docs/redis.md +++ b/src/docs/redis.md @@ -440,6 +440,8 @@ Redis::listenForFailures(function (CommandFailed $event): void { Listening for a failure does not suppress the command's exception. You may also use `Redis::listen` to register a callback that receives a `Hypervel\Redis\Events\CommandExecuted` event after each successful command. +If you cancel a coroutine without asking Swoole to throw an exception, a Redis command waiting for a reply may throw its original `RedisException`. In that case, failure listeners receive the exception as well. + #### Holding a Pooled Connection diff --git a/src/redis/src/RedisCancellation.php b/src/redis/src/RedisCancellation.php index fe3ebab8b2..46c1b0fd50 100644 --- a/src/redis/src/RedisCancellation.php +++ b/src/redis/src/RedisCancellation.php @@ -31,7 +31,8 @@ public static function cancellationFrom(Throwable $exception, string $message): return $exception; } - // phpredis keeps a thrown cancellation as the cause; a non-throwing one leaves only the socket error. + // phpredis may close the failed stream before throwing, clearing the socket error. + // Without a cancellation cause or that error, preserve the original Redis exception. if (($exception instanceof RedisException || $exception instanceof RedisClusterException) && (Coroutine::causedByCancellation($exception) || (EngineCoroutine::isCanceled() && swoole_last_error() === SOCKET_ECANCELED)) diff --git a/tests/Redis/RedisCancellationLifecycleTest.php b/tests/Redis/RedisCancellationLifecycleTest.php index 7fad0cd409..e8d45b2167 100644 --- a/tests/Redis/RedisCancellationLifecycleTest.php +++ b/tests/Redis/RedisCancellationLifecycleTest.php @@ -33,10 +33,12 @@ public function testBlockedCommandCancellationInvalidatesAndReturnsTheLeaseWitho $commandReceived = new Channel(1); $releaseServer = new Channel(1); $server->start(function ($client) use ($commandReceived, $releaseServer): void { + // Queue a partial reply so cancellation interrupts the bulk read, where phpredis preserves the socket error. + fwrite($client, '$4' . "\r\nab"); $command = fread($client, 4096); $this->assertIsString($command); - $this->assertStringContainsString('BLPOP', $command); + $this->assertStringContainsString('GET', $command); $commandReceived->push(true); $releaseServer->pop(2.0); }); @@ -67,13 +69,13 @@ public function testBlockedCommandCancellationInvalidatesAndReturnsTheLeaseWitho try { $exception = $this->cancelAfter( - static fn () => $connection->blpop('blocked', 0), + static fn () => $connection->get('blocked'), $commandReceived, $throwException, ); $this->assertInstanceOf(CanceledException::class, $exception); - $this->assertSame('Executing Redis command [blpop] was canceled.', $exception->getMessage()); + $this->assertSame('Executing Redis command [get] was canceled.', $exception->getMessage()); $this->assertInstanceOf(RedisException::class, $exception->getPrevious()); $this->assertSame(0, $executed); $this->assertSame(0, $failed); @@ -164,7 +166,6 @@ public function testNativeClientCancellationIsClassifiedAtItsBoundary( string $stallOn, Closure $operation, string $message, - bool $throwException, ): void { $server = new RespServer; $entered = new Channel(1); @@ -188,7 +189,7 @@ public function testNativeClientCancellationIsClassifiedAtItsBoundary( $redis = RedisFacade::connection($connectionName); try { - $exception = $this->cancelAfter(static fn () => $operation($redis), $entered, $throwException); + $exception = $this->cancelAfter(static fn () => $operation($redis), $entered); $this->assertInstanceOf(CanceledException::class, $exception); $this->assertSame($message, $exception->getMessage()); @@ -209,7 +210,7 @@ public function testNativeClientCancellationIsClassifiedAtItsBoundary( */ public static function nativeClientOperations(): iterable { - $operations = [ + return [ 'transaction exec' => [ 'EXEC', static fn (RedisProxy $redis) => $redis->transaction(static fn (Redis $client) => $client->set('key', 'value')), @@ -231,11 +232,6 @@ public static function nativeClientOperations(): iterable 'Discarding the Redis transaction was canceled.', ], ]; - - foreach ($operations as $name => $operation) { - yield "{$name}, throwing" => [...$operation, true]; - yield "{$name}, non-throwing" => [...$operation, false]; - } } public function testFailureAfterAHandledCancellationKeepsItsRedisException(): void From 7d57bf09a920c305f3eb6c2ddb33f4e6f9a70b79 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:01 +0000 Subject: [PATCH 10/11] Reuse the immutable JWE builder without resetting it Build each Mercure message from the pristine cached builder. The supported versions clone on mutation and web-token 4.3 deprecates the redundant reset. Verify that one encrypter round-trips consecutive messages on different channels. --- src/broadcasting/src/Mercure/ChannelEncrypter.php | 2 +- .../Broadcasting/MercureChannelEncrypterTest.php | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/broadcasting/src/Mercure/ChannelEncrypter.php b/src/broadcasting/src/Mercure/ChannelEncrypter.php index 1d848c9445..875d5a70e2 100644 --- a/src/broadcasting/src/Mercure/ChannelEncrypter.php +++ b/src/broadcasting/src/Mercure/ChannelEncrypter.php @@ -53,7 +53,7 @@ public function encrypt(string $plaintext, string $channel): string $this->serializer ??= new CompactSerializer; - $jwe = $this->jweBuilder->create() + $jwe = $this->jweBuilder ->withPayload($plaintext) ->withSharedProtectedHeader(['alg' => 'dir', 'enc' => 'A256GCM']) ->addRecipient(new JWK(['kty' => 'oct', 'k' => Base64UrlSafe::encodeUnpadded($this->channelKey($channel))])) diff --git a/tests/Broadcasting/MercureChannelEncrypterTest.php b/tests/Broadcasting/MercureChannelEncrypterTest.php index 2c874b8f96..13fafedb08 100644 --- a/tests/Broadcasting/MercureChannelEncrypterTest.php +++ b/tests/Broadcasting/MercureChannelEncrypterTest.php @@ -65,14 +65,15 @@ public function testEncryptRoundTripsThroughAStandardJweDecrypter(): void { $encrypter = new ChannelEncrypter($this->key()); - $jwe = (new CompactSerializer)->unserialize( - $encrypter->encrypt('{"event":"Tick"}', 'private-encrypted-a') - ); - + $serializer = new CompactSerializer; $decrypter = new JWEDecrypter(new AlgorithmManager([new Dir, new A256GCM])); - $this->assertTrue($decrypter->decryptUsingKey($jwe, new JWK($encrypter->channelJwk('private-encrypted-a')), 0)); - $this->assertSame('{"event":"Tick"}', $jwe->getPayload()); - $this->assertSame(['alg' => 'dir', 'enc' => 'A256GCM'], $jwe->getSharedProtectedHeader()); + foreach (['private-encrypted-a', 'private-encrypted-b'] as $channel) { + $jwe = $serializer->unserialize($encrypter->encrypt('{"event":"Tick"}', $channel)); + + $this->assertTrue($decrypter->decryptUsingKey($jwe, new JWK($encrypter->channelJwk($channel)), 0)); + $this->assertSame('{"event":"Tick"}', $jwe->getPayload()); + $this->assertSame(['alg' => 'dir', 'enc' => 'A256GCM'], $jwe->getSharedProtectedHeader()); + } } } From 081586b15f34adcba2e946569997edf32227c8ba Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:35:01 +0000 Subject: [PATCH 11/11] Track the coroutine signal fix in the PsySH release prerequisite Wait for the optional signal-handler fix as well as the earlier shell lifecycle changes before switching Tinker back to a stable dependency. --- docs/todo.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/todo.md b/docs/todo.md index 3f9948a137..fc980e97f4 100644 --- a/docs/todo.md +++ b/docs/todo.md @@ -2,7 +2,7 @@ ## Release preparation -- Replace `psy/psysh` `dev-main` in the root and `src/tinker` manifests with the first stable release containing PsySH #951–#954. The latest stable release, v0.12.24, predates those changes. +- Replace `psy/psysh` `dev-main` in the root and `src/tinker` manifests with the first stable release containing PsySH #951–#954 and #972. The latest stable release, v0.12.24, predates those changes. ## Authentication