From b1f6fa4899a37bd7fa7187ced2d7dbe7397a44af Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:34:10 +0000 Subject: [PATCH 01/12] Clarify when to add a Hypervel PHPStan rule Evaluate proposed checks against recurring mistakes and realistic correct usage, including patterns whose known instances have already been fixed. Prefer a simple framework fix when it prevents the mistake. Reject checks that flag correct code or rely on a growing list of exemptions. When an existing check misfires, correct the analyzer so callers can keep their working code. --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 19a4db2d7..196c70801 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -759,7 +759,7 @@ See the existing entries for database, Redis, Meilisearch, and Typesense as exam Components is analyzed with its own `hypervel/phpstan` extension. [Static Analysis](src/docs/static-analysis.md#fixing-and-ignoring-diagnostics) is the source of truth for each diagnostic's intended fix and legitimate exceptions; the rules below add Components-specific requirements. -**Keep `hypervel/phpstan` evolving** — Codify framework contracts and useful conventions to help agents avoid mistakes. When implementation or review reveals a pattern worth checking, verify realistic usage, reliable detection and proportionate complexity; reach peer consensus, then seek owner approval for the new rule. Investigate false positives on realistic code; fix analyzer defects rather than rewriting correct code to work around them. Keep inference limits explicit; do not add brittle machinery merely to handle unusual cases. +**Keep `hypervel/phpstan` evolving** — Codify framework contracts and useful conventions. Prefer a simple framework fix when it prevents the mistake. Add rules for mistakes likely to recur in packages or apps, even when existing cases are already fixed. Check each proposed rule against real mistakes and realistic correct usage. Reject rules that flag correct code or need a growing list of exceptions to avoid doing so. Keep inference limits explicit. Reach peer consensus, then seek owner approval for a new rule. If an existing rule flags correct code, fix the analyzer and leave the correct code alone. The `tests/` directory is excluded from phpstan. Do not run phpstan on tests. From b2573a84dfcd5f1f83bdc6fa26b084b4837330d8 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:13 +0000 Subject: [PATCH 02/12] Handle caller cancellation consistently when joining coroutines Translate an interrupted native join into CanceledException in both Swoole cancellation modes. Read the error from the join itself so that a canceled operation earlier in the same coroutine cannot turn a later join into a cancellation. Add joinUninterruptibly() for cleanup that must finish before cancellation propagates. Keep the first cancellation and spend only the time left on the original deadline. Reuse it for strict child teardown and remove duplicate cancellation checks from Waiter and Parallel. --- src/coroutine/src/Coroutine.php | 41 +++++++++++- src/coroutine/src/Parallel.php | 6 +- src/coroutine/src/Waiter.php | 34 ++-------- tests/Coroutine/CoroutineTest.php | 103 ++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 33 deletions(-) diff --git a/src/coroutine/src/Coroutine.php b/src/coroutine/src/Coroutine.php index d545d2eef..fe5e9e5ac 100644 --- a/src/coroutine/src/Coroutine.php +++ b/src/coroutine/src/Coroutine.php @@ -203,10 +203,49 @@ private static function runChild(callable $callable, array $context): void * that the timeout elapsed. It is not a general failure signal. * * @param list $coroutineIds + * @throws CanceledException if the caller is canceled during the wait */ public static function join(array $coroutineIds, float $timeout = -1): bool { - return Co::join($coroutineIds, $timeout); + $joined = Co::join($coroutineIds, $timeout); + + // A join with no live targets doesn't yield, so isCanceled() can still describe an earlier wait. + if (! $joined && swoole_last_error() === SWOOLE_ERROR_CO_CANCELED) { + throw new CanceledException('Waiting for child coroutines was canceled.'); + } + + return $joined; + } + + /** + * Wait for the given coroutines to finish before propagating caller cancellation. + * + * A timeout of zero or less waits without limit, like join(). + * + * @param list $coroutineIds + * @return bool whether none of the supplied coroutines remain active + * @throws CanceledException if the caller was canceled during the wait + */ + public static function joinUninterruptibly(array $coroutineIds, float $timeout = -1): bool + { + $deadline = $timeout > 0 ? hrtime(true) / 1e9 + $timeout : null; + $cancellation = null; + $joined = false; + + do { + try { + $joined = static::join($coroutineIds, $timeout); + break; + } catch (CanceledException $exception) { + $cancellation ??= $exception; + } + } while ($deadline === null || ($timeout = $deadline - hrtime(true) / 1e9) > 0); + + if ($cancellation !== null) { + throw $cancellation; + } + + return $joined || ! array_any($coroutineIds, Co::exists(...)); } /** diff --git a/src/coroutine/src/Parallel.php b/src/coroutine/src/Parallel.php index 12407d6de..b21840bab 100644 --- a/src/coroutine/src/Parallel.php +++ b/src/coroutine/src/Parallel.php @@ -169,11 +169,7 @@ public function wait(bool $throw = true): array // WaitGroup completion precedes the last child's physical teardown. if ($coroutineIds !== []) { - $joined = Coroutine::join($coroutineIds); - - if (! $joined && EngineCoroutine::isCanceled()) { - throw new CanceledException('Waiting for parallel child coroutines was canceled.'); - } + Coroutine::join($coroutineIds); } } catch (Throwable $throwable) { // Context copying can wrap the cancellation after earlier children started. diff --git a/src/coroutine/src/Waiter.php b/src/coroutine/src/Waiter.php index fcdc297c4..a2e5031fd 100644 --- a/src/coroutine/src/Waiter.php +++ b/src/coroutine/src/Waiter.php @@ -109,18 +109,12 @@ public function wait( // Throw into the operation so an interrupted wait cannot be ignored accidentally, // then give the child a bounded interval to unwind and run deferred cleanup. $this->cancelChild($childCoroutineId, $childCancellationRequested); - $joined = Coroutine::join([$childCoroutineId], $this->pushTimeout); + Coroutine::join([$childCoroutineId], $this->pushTimeout); } catch (CanceledException $exception) { $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); throw $exception; } - if (! $joined && EngineCoroutine::isCanceled()) { - $exception = new CanceledException('Waiting for a child coroutine was canceled.'); - $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); - throw $exception; - } - // A false join may mean either timeout or a missing coroutine, so only // existence proves that the child survived the cleanup allowance. if ($waitForChildTermination && Coroutine::exists($childCoroutineId)) { @@ -142,18 +136,12 @@ public function wait( } try { - $joined = Coroutine::join([$childCoroutineId]); + Coroutine::join([$childCoroutineId]); } catch (CanceledException $exception) { $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); throw $exception; } - if (! $joined && EngineCoroutine::isCanceled()) { - $exception = new CanceledException('Waiting for a child coroutine was canceled.'); - $this->cancelChild($childCoroutineId, $childCancellationRequested, $waitForChildTermination); - throw $exception; - } - if ($result instanceof ExceptionThrower) { $exception = $result->getThrowable(); @@ -196,20 +184,12 @@ protected function cancelChild(?int $childCoroutineId, bool &$cancellationReques */ protected function awaitChildTermination(int $childCoroutineId): ?CanceledException { - $cancellation = null; - - // Each cancellation interrupts the join, so join again until the child is gone. - while (Coroutine::exists($childCoroutineId)) { - try { - if (! Coroutine::join([$childCoroutineId]) && EngineCoroutine::isCanceled()) { - $cancellation ??= new CanceledException('Waiting for a child coroutine was canceled.'); - } - } catch (CanceledException $exception) { - // @phpstan-ignore hypervel.cancellation.precedence (both values are this coroutine's direct cancellation) - $cancellation ??= $exception; - } + try { + Coroutine::joinUninterruptibly([$childCoroutineId]); + } catch (CanceledException $exception) { + return $exception; } - return $cancellation; + return null; } } diff --git a/tests/Coroutine/CoroutineTest.php b/tests/Coroutine/CoroutineTest.php index d9768c7a9..824e17e02 100644 --- a/tests/Coroutine/CoroutineTest.php +++ b/tests/Coroutine/CoroutineTest.php @@ -27,9 +27,12 @@ use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; +use Swoole\Event; use Throwable; use function Hypervel\Coroutine\go; +use function Hypervel\Coroutine\parallel; +use function Hypervel\Coroutine\wait; class CoroutineTest extends TestCase { @@ -129,6 +132,106 @@ public function testJoinWaitsForCreatedCoroutines(): void $this->assertFalse(Coroutine::exists($coroutineId)); } + #[TestWith([false])] + #[TestWith([true])] + public function testJoinThrowsWhenTheWaitIsCanceled(bool $throw): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $parent = Coroutine::id(); + Event::defer(static fn () => EngineCoroutine::cancelById($parent, $throw)); + + $this->expectException(CanceledException::class); + try { + Coroutine::join([$child], 1); + } finally { + $release->close(); + } + } + + public function testUninterruptibleJoinReportsWhetherAnyChildRemainsActive(): void + { + $finished = Coroutine::create(static fn () => null); + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + + try { + $this->assertFalse(Coroutine::joinUninterruptibly([$finished, $child], 0.001)); + } finally { + $release->close(); + } + + $this->assertTrue(Coroutine::joinUninterruptibly([$finished, $child])); + } + + #[TestWith([false])] + #[TestWith([true])] + public function testUninterruptibleJoinPropagatesCancellationAfterChildExit(bool $throw): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $failure = null; + $waiter = Coroutine::create(static function () use ($child, &$failure): void { + try { + Coroutine::joinUninterruptibly([$child], 0); + } catch (CanceledException $exception) { + $failure = $exception; + } + }); + + try { + EngineCoroutine::cancelById($waiter, $throw); + $this->assertTrue(Coroutine::exists($waiter)); + } finally { + $release->close(); + Coroutine::join([$waiter]); + } + + $this->assertInstanceOf(CanceledException::class, $failure); + } + + public function testRepeatedInterruptionsDoNotRestartTheJoinTimeout(): void + { + $release = new Channel(1); + $child = Coroutine::create(static fn () => $release->pop()); + $failure = null; + $waiter = Coroutine::create(static function () use ($child, &$failure): void { + try { + Coroutine::joinUninterruptibly([$child], 0.03); + } catch (CanceledException $exception) { + $failure = $exception; + } + }); + + try { + $limit = hrtime(true) + 500_000_000; + while (Coroutine::exists($waiter) && hrtime(true) < $limit) { + EngineCoroutine::cancelById($waiter); + Coroutine::sleep(0.002); + } + + $this->assertInstanceOf(CanceledException::class, $failure); + $this->assertTrue(Coroutine::exists($child)); + } finally { + $release->close(); + Coroutine::join([$waiter]); + } + } + + public function testJoiningFinishedChildrenAfterAnEarlierWaitWasCanceled(): void + { + $parent = Coroutine::id(); + Event::defer(static fn () => EngineCoroutine::cancelById($parent)); + $channel = new Channel(1); + $channel->pop(1); + $this->assertTrue($channel->isCanceled()); + + $finished = Coroutine::create(static fn () => null); + $this->assertTrue(Coroutine::joinUninterruptibly([$finished])); + $this->assertSame('done', wait(static fn () => 'done')); + $this->assertSame(['done'], parallel([static fn () => 'done'])); + } + public function testCoroutineParentId(): void { $pid = Coroutine::id(); From 330c99b7d7d0a2664e5f8801e9c926208a826bb8 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:14 +0000 Subject: [PATCH 03/12] Finish gRPC receiver cleanup before closing the client An interrupted close could reach the native transport while the receiver was still unwinding. Wait for the receiver to exit before releasing the transport, then propagate the cancellation to the caller. Exercise interruption in the existing connection close test. --- src/grpc/src/Client/Connection.php | 6 +----- tests/Grpc/ConnectionTest.php | 20 ++++++++++++++++++-- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/grpc/src/Client/Connection.php b/src/grpc/src/Client/Connection.php index 57c67d2e2..4a054b507 100644 --- a/src/grpc/src/Client/Connection.php +++ b/src/grpc/src/Client/Connection.php @@ -764,11 +764,7 @@ private function terminateWhileLocked(ConnectionException $failure): ConnectionE // Native close must wait for physical receiver and engine-client cleanup. // A bounded join could still leave the socket owned when its timeout elapsed. - if (! Coroutine::join([$receiverCoroutineId]) && Coroutine::isCanceled()) { - $cancellation = new CanceledException( - 'Waiting for the gRPC response receiver to stop was canceled.', - ); - } + FrameworkCoroutine::joinUninterruptibly([$receiverCoroutineId]); } catch (CanceledException $exception) { $cancellation = $exception; } diff --git a/tests/Grpc/ConnectionTest.php b/tests/Grpc/ConnectionTest.php index 4261a25bc..9653ad8d9 100644 --- a/tests/Grpc/ConnectionTest.php +++ b/tests/Grpc/ConnectionTest.php @@ -877,7 +877,9 @@ static function () use (&$now): int { $this->assertSame(1, $retired); } - public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(bool $interrupt): void { $client = new ConnectionCloseWaitTestClient; $connection = $this->connection(new ConnectionTestClientFactory($client)); @@ -889,7 +891,21 @@ public function testCloseJoinsTheReceiverBeforeClosingItsNativeClient(): void $this->assertIsInt($receiverCoroutineId); $this->assertTrue($client->waiting); - $connection->close(); + if ($interrupt) { + $cancellation = null; + $closer = Coroutine::create(static function () use ($connection, &$cancellation): void { + try { + $connection->close(); + } catch (CanceledException $exception) { + $cancellation = $exception; + } + })->getId(); + Coroutine::cancelById($closer, throwException: true); + Coroutine::join([$closer]); + $this->assertInstanceOf(CanceledException::class, $cancellation); + } else { + $connection->close(); + } $this->assertFalse($client->waiting); $this->assertTrue($client->receiverCleanupCompleted); From f89013eea5a14116744657fcec73e366ec678f84 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:14 +0000 Subject: [PATCH 04/12] Wait for the last prompt animation frame during cancellation The renderer can still own terminal output when the spinner callback finishes. Join the renderer through cancellation so prompt teardown cannot race an in-flight frame. Cover cancellation while that frame is waiting to finish. --- src/prompts/src/Support/PromptAnimation.php | 2 +- tests/Prompts/SpinnerTest.php | 34 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/prompts/src/Support/PromptAnimation.php b/src/prompts/src/Support/PromptAnimation.php index b441bb90e..6424ad112 100644 --- a/src/prompts/src/Support/PromptAnimation.php +++ b/src/prompts/src/Support/PromptAnimation.php @@ -69,7 +69,7 @@ public function stop(): ?Throwable $this->coroutineId = null; $this->stop->push(true); - Coroutine::join([$coroutineId]); + Coroutine::joinUninterruptibly([$coroutineId]); return $this->renderFailure; } diff --git a/tests/Prompts/SpinnerTest.php b/tests/Prompts/SpinnerTest.php index 5e1e79f0c..d4deb7f1f 100644 --- a/tests/Prompts/SpinnerTest.php +++ b/tests/Prompts/SpinnerTest.php @@ -6,11 +6,14 @@ use Hypervel\Coroutine\Coroutine; use Hypervel\Engine\Channel; +use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Prompts\Output\BufferedConsoleOutput; use Hypervel\Prompts\Prompt; use Hypervel\Prompts\Spinner; use Hypervel\Tests\TestCase; use RuntimeException; +use Swoole\Coroutine\CanceledException; +use Swoole\Event; use function Hypervel\Prompts\spin; @@ -146,6 +149,37 @@ public function testWaitsForAnInFlightAnimationBeforeSettling(): void $this->assertSame($renderCalls, $spinner->renderCalls); } + public function testCancellationDuringStopWaitsForTheLastFrame(): void + { + Prompt::fake(); + $spinner = new SpinnerAnimationFixture('Running'); + $spinner->interval = 1; + $cancellation = null; + $callbackFinished = new Channel(1); + $owner = Coroutine::fork(static function () use ($spinner, $callbackFinished, &$cancellation): void { + try { + $spinner->spin(static function () use ($spinner, $callbackFinished): void { + $spinner->renderStarted->pop(1); + Event::defer(static fn () => $callbackFinished->push(true)); + }); + } catch (CanceledException $exception) { + $cancellation = $exception; + } + }); + + try { + $this->assertTrue($callbackFinished->pop(1)); + EngineCoroutine::cancelById($owner); + $this->assertTrue(Coroutine::exists($owner)); + } finally { + $spinner->renderRelease->push(true); + Coroutine::join([$owner]); + } + + $this->assertInstanceOf(CanceledException::class, $cancellation); + $this->assertFalse($spinner->rendering); + } + public function testSurfacesAnimationRenderFailureAfterSuccessfulCallback(): void { Prompt::fake(); From ef88d1d43754ecb039a0607739da19e335fd6838 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:14 +0000 Subject: [PATCH 05/12] Recognize uninterruptible joins in cancellation analysis Register the cleanup join with both existing wait checks. An exact cancellation catch is valid around this operation, and swallowing cancellation in a queue job must still produce a diagnostic. Exercise both cases in the existing rule fixtures. --- .../Collectors/SwallowedCancellationCollector.php | 2 +- .../src/Rules/Coroutine/CoroutineRuleHelper.php | 2 +- .../Coroutine/ExactCancellationCatchRuleTest.php | 12 ++++++------ .../Coroutine/SwallowedCancellationRuleTest.php | 11 ++++++----- .../Coroutine/data/exact-cancellation-catches.php | 1 + .../Coroutine/data/swallowed-cancellation-waits.php | 9 ++++++++- 6 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php index 0abce8a57..3185b6048 100644 --- a/src/phpstan/src/Collectors/SwallowedCancellationCollector.php +++ b/src/phpstan/src/Collectors/SwallowedCancellationCollector.php @@ -352,7 +352,7 @@ class SwallowedCancellationCollector implements Collector WaitConcurrent::class => [self::WAIT, ['create' => true, 'fork' => true, 'wait' => true]], Concurrency::class => [self::WAIT, ['run' => true]], SwooleCoroutine::class => [self::WAIT, ['join' => true, 'sleep' => true]], - Coroutine::class => [self::WAIT, ['join' => true, 'sleep' => true]], + Coroutine::class => [self::WAIT, ['join' => true, 'joinuninterruptibly' => true, 'sleep' => true]], EngineCoroutine::class => [self::WAIT, ['join' => true]], Sleep::class => [self::WAIT, ['then' => true]], ]; diff --git a/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php b/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php index b8b9b57e3..29b32dc55 100644 --- a/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php +++ b/src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php @@ -77,7 +77,7 @@ class CoroutineRuleHelper 'Hypervel\Coroutine\WaitGroup' => ['add', 'done', 'wait'], 'Hypervel\Coroutine\Waiter' => ['wait'], 'Swoole\Coroutine' => ['join'], - 'Hypervel\Coroutine\Coroutine' => ['join'], + 'Hypervel\Coroutine\Coroutine' => ['join', 'joinuninterruptibly'], 'Hypervel\Engine\Coroutine' => ['join'], ]; diff --git a/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php b/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php index 3b1ed1cbf..c95982b6c 100644 --- a/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php +++ b/tests/PHPStan/Rules/Coroutine/ExactCancellationCatchRuleTest.php @@ -29,12 +29,12 @@ public function testRule(): void [sprintf(self::MESSAGE, 74), 72], [sprintf(self::MESSAGE, 85), 83], [sprintf(self::MESSAGE, 169), 167], - [sprintf(self::MESSAGE, 220), 218], - [sprintf(self::MESSAGE, 235), 233], - [sprintf(self::MESSAGE, 248), 246], - [sprintf(self::MESSAGE, 339), 337], - [sprintf(self::MESSAGE, 352), 350], - [sprintf(self::MESSAGE, 377), 375], + [sprintf(self::MESSAGE, 221), 219], + [sprintf(self::MESSAGE, 236), 234], + [sprintf(self::MESSAGE, 249), 247], + [sprintf(self::MESSAGE, 340), 338], + [sprintf(self::MESSAGE, 353), 351], + [sprintf(self::MESSAGE, 378), 376], ]); } diff --git a/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php b/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php index a083088bd..2f83b36bf 100644 --- a/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php +++ b/tests/PHPStan/Rules/Coroutine/SwallowedCancellationRuleTest.php @@ -104,11 +104,12 @@ public function testRule(): void public function testConcurrencyWaitsAndPropertyReceivers(): void { $this->analyse([__DIR__ . '/data/swallowed-cancellation-waits.php'], [ - self::swallowed('a wait', 23), - self::swallowed('a wait', 30), - self::swallowed('a wait', 36), - self::swallowed('a database query', 44), - self::swallowed('a database query', 51), + self::swallowed('a wait', 24), + self::swallowed('a wait', 31), + self::swallowed('a wait', 37), + self::swallowed('a database query', 45), + self::swallowed('a database query', 52), + self::swallowed('a wait', 58), ]); } diff --git a/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php b/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php index 60995b7bf..aec7a8597 100644 --- a/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php +++ b/tests/PHPStan/Rules/Coroutine/data/exact-cancellation-catches.php @@ -185,6 +185,7 @@ public function waitsNatively(Channel $channel, WaitGroup $waitGroup, array $cor try { $waitGroup->wait(1.0); Coroutine::join($coroutineIds, 1.0); + Coroutine::joinUninterruptibly($coroutineIds); $results = new Channel(1); $later = $this->work(...); diff --git a/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php b/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php index 5e8dedcdd..0490cbc20 100644 --- a/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php +++ b/tests/PHPStan/Rules/Coroutine/data/swallowed-cancellation-waits.php @@ -7,6 +7,7 @@ use Hypervel\Contracts\Engine\ChannelInterface; use Hypervel\Contracts\Queue\ShouldQueue; use Hypervel\Coroutine\Concurrent; +use Hypervel\Coroutine\Coroutine; use Hypervel\Coroutine\WaitConcurrent; use Hypervel\Database\Connection; use Hypervel\Support\Facades\DB; @@ -16,7 +17,7 @@ class WaitingImportJob implements ShouldQueue { private ?Connection $connection = null; - public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInterface $results, ?Connection $connection): void + public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInterface $results, ?Connection $connection, int $childId): void { try { $imports->wait(1.0); @@ -51,5 +52,11 @@ public function handle(WaitConcurrent $imports, Concurrent $limiter, ChannelInte } catch (Throwable) { return; } + + try { + Coroutine::joinUninterruptibly([$childId]); + } catch (Throwable) { + return; + } } } From 8ac53dfcbb90683ed39250b638b70ca657101285 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:59:14 +0000 Subject: [PATCH 06/12] Document cancellation and deadlines for coroutine joins Describe when an ordinary join returns false and when it throws. Show when resource cleanup should use the new wait and explain how a timeout limits retries. Remove the obsolete recommendation to inspect coroutine-wide cancellation state after a failed join. --- src/docs/coroutines.md | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/docs/coroutines.md b/src/docs/coroutines.md index cc2ebea49..637aab6ce 100644 --- a/src/docs/coroutines.md +++ b/src/docs/coroutines.md @@ -974,19 +974,9 @@ $coroutineIds = Coroutine::list(); The `join` method waits for the supplied child coroutine IDs to finish. You may include IDs for coroutines that have already finished. -A `false` result may mean that none of the supplied coroutines remained active or that the timeout elapsed. It does not always indicate a failure. +A `false` result may mean that all supplied coroutines had already finished or that the timeout elapsed. If the caller is canceled during the wait, `join` throws a `CanceledException`. -Low-level infrastructure that must distinguish a canceled native wait from its other `false` outcomes may inspect the engine cancellation state immediately: - -```php -use Hypervel\Engine\Coroutine as EngineCoroutine; - -if (! Coroutine::join($coroutineIds) && EngineCoroutine::isCanceled()) { - // The join was canceled... -} -``` - -This state is not durable. Read it only at the failed native operation boundary. +Use `joinUninterruptibly` when cleanup must wait for children to exit even if the caller is canceled. It waits until the children exit or the original timeout expires, then throws the caller's first cancellation. Without cancellation, it returns `true` if none of the supplied coroutines are still running. As with `join`, a timeout of zero or less waits without a deadline. The `afterCreated` method registers a callback that runs during child startup for `Coroutine::create`, `fork`, `createOwned`, and `forkOwned`, as well as helpers such as `go` and `co`: From ddae743fc5ac31a341d61e53dda041022d7699e7 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:17 +0000 Subject: [PATCH 07/12] Wait for repeated coroutine IDs without changing ordinary joins Swoole rejects a repeated live ID before it starts waiting. Retry that failure once with distinct IDs. Successful multi-child joins keep their existing path and a second owner still cannot join a child that already has a waiter. Exercise duplicate IDs in the existing completion and interrupted-cleanup tests. --- src/coroutine/src/Coroutine.php | 8 ++++++++ tests/Coroutine/CoroutineTest.php | 4 ++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/coroutine/src/Coroutine.php b/src/coroutine/src/Coroutine.php index fe5e9e5ac..936eb5637 100644 --- a/src/coroutine/src/Coroutine.php +++ b/src/coroutine/src/Coroutine.php @@ -209,6 +209,14 @@ public static function join(array $coroutineIds, float $timeout = -1): bool { $joined = Co::join($coroutineIds, $timeout); + // Swoole rejects repeated live IDs before waiting. Retry only that case to avoid copying normal lists. + if (! $joined && swoole_last_error() === SWOOLE_ERROR_WRONG_OPERATION && count($coroutineIds) > 1) { + $distinctIds = array_keys(array_flip($coroutineIds)); + if (count($distinctIds) < count($coroutineIds)) { + $joined = Co::join($distinctIds, $timeout); + } + } + // A join with no live targets doesn't yield, so isCanceled() can still describe an earlier wait. if (! $joined && swoole_last_error() === SWOOLE_ERROR_CO_CANCELED) { throw new CanceledException('Waiting for child coroutines was canceled.'); diff --git a/tests/Coroutine/CoroutineTest.php b/tests/Coroutine/CoroutineTest.php index 824e17e02..4e38f2762 100644 --- a/tests/Coroutine/CoroutineTest.php +++ b/tests/Coroutine/CoroutineTest.php @@ -127,7 +127,7 @@ public function testJoinWaitsForCreatedCoroutines(): void $completed = true; }); - $this->assertTrue(Coroutine::join([$coroutineId], 1)); + $this->assertTrue(Coroutine::join([$coroutineId, $coroutineId], 1)); $this->assertTrue($completed); $this->assertFalse(Coroutine::exists($coroutineId)); } @@ -173,7 +173,7 @@ public function testUninterruptibleJoinPropagatesCancellationAfterChildExit(bool $failure = null; $waiter = Coroutine::create(static function () use ($child, &$failure): void { try { - Coroutine::joinUninterruptibly([$child], 0); + Coroutine::joinUninterruptibly([$child, $child], 0); } catch (CanceledException $exception) { $failure = $exception; } From cfc7a5a2a1ef67f2b74b9c64650078bbad2e21cf Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:17 +0000 Subject: [PATCH 08/12] Propagate terminal cleanup cancellation from interactive prompts If submitting a prompt fails, terminal restoration still runs. Preserve the submission error for ordinary cleanup failures and propagate an interruption of the caller during restoration. Cover the ordering through TextPrompt submission. --- src/prompts/src/Prompt.php | 4 +--- tests/Prompts/PromptLifecycleTest.php | 10 ++++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/prompts/src/Prompt.php b/src/prompts/src/Prompt.php index 0c1c0387c..0d2467762 100644 --- a/src/prompts/src/Prompt.php +++ b/src/prompts/src/Prompt.php @@ -226,9 +226,7 @@ public function prompt(): mixed try { $this->restoreTerminalState(); } catch (Throwable $exception) { - if ($operationFailure === null) { - throw $exception; - } + throw Coroutine::preferCancellation($operationFailure, $exception); } } } diff --git a/tests/Prompts/PromptLifecycleTest.php b/tests/Prompts/PromptLifecycleTest.php index c09dbc42f..166df74c5 100644 --- a/tests/Prompts/PromptLifecycleTest.php +++ b/tests/Prompts/PromptLifecycleTest.php @@ -16,6 +16,7 @@ use ReflectionMethod; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; use function Hypervel\Prompts\text; @@ -203,6 +204,15 @@ protected function doWrite(string $message, bool $newline): void $this->assertFalse(TextPrompt::shouldFallback()); } + public function testTerminalCleanupCancellationPropagatesAfterSubmissionFails(): void + { + Prompt::fake([Key::ENTER]); + Prompt::terminal()->shouldReceive('restoreTty')->once()->andThrow(new CanceledException); + $this->expectException(CanceledException::class); + + (new TextPrompt('Name', transform: static fn () => throw new RuntimeException('Submission failed.')))->prompt(); + } + public function testCursorOwnershipIsReleasedWhenOperationCleanupCannotRestoreIt(): void { Prompt::fake(); From 5d49585ec1c4892a157084145aa773447404b52e Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:18 +0000 Subject: [PATCH 09/12] Preserve caller cancellation while settling a spinner Keep a callback error ahead of ordinary render or terminal errors, while allowing cancellation during the final join or terminal restoration to reach the caller. Keep a render failure returned by the child separate from cancellation thrown in its owner. Exercise both ordinary and interrupted restoration, including a callback that fails before the final frame finishes. --- src/prompts/src/Spinner.php | 20 ++++++++++---------- tests/Prompts/SpinnerTest.php | 16 +++++++++++----- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/prompts/src/Spinner.php b/src/prompts/src/Spinner.php index d5505f242..a19413aed 100644 --- a/src/prompts/src/Spinner.php +++ b/src/prompts/src/Spinner.php @@ -77,24 +77,24 @@ public function spin(Closure $callback): mixed throw $exception; } finally { + $failure = $operationFailure; $animationFailure = null; try { $animationFailure = $animation?->stop(); } catch (Throwable $exception) { - $animationFailure = $exception; + $failure = Coroutine::preferCancellation($failure, $exception); } $cleanupFailure = $this->settleOperation(); - if ($operationFailure === null) { - if ($animationFailure !== null) { - throw $animationFailure; - } + if ($cleanupFailure !== null && Coroutine::causedByCancellation($cleanupFailure)) { + $failure = Coroutine::preferCancellation($failure, $cleanupFailure); + } - if ($cleanupFailure !== null) { - throw $cleanupFailure; - } + $failure ??= $animationFailure ?? $cleanupFailure; + if ($failure !== null && $failure !== $operationFailure) { + throw $failure; } } } @@ -124,8 +124,8 @@ protected function renderStatically(Closure $callback): mixed } finally { $cleanupFailure = $this->settleOperation(); - if ($operationFailure === null && $cleanupFailure !== null) { - throw $cleanupFailure; + if ($cleanupFailure !== null) { + throw Coroutine::preferCancellation($operationFailure, $cleanupFailure); } } } diff --git a/tests/Prompts/SpinnerTest.php b/tests/Prompts/SpinnerTest.php index d4deb7f1f..6e3548f09 100644 --- a/tests/Prompts/SpinnerTest.php +++ b/tests/Prompts/SpinnerTest.php @@ -11,9 +11,11 @@ use Hypervel\Prompts\Prompt; use Hypervel\Prompts\Spinner; use Hypervel\Tests\TestCase; +use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; use Swoole\Event; +use Throwable; use function Hypervel\Prompts\spin; @@ -64,15 +66,18 @@ public function testRestoresThePreviousSignalHandler(): void } } - public function testCallbackFailureRemainsPrimaryWhenTerminalRestorationFails(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCallbackFailureRemainsPrimaryUnlessTerminalRestorationIsCanceled(bool $canceled): void { Prompt::fake(); $callbackFailure = new RuntimeException('callback failed'); + $cleanupFailure = $canceled ? new CanceledException : new RuntimeException('terminal restoration failed'); Prompt::terminal() ->shouldReceive('restoreTty') // @phpstan-ignore-line ->once() - ->andThrow(new RuntimeException('terminal restoration failed')); + ->andThrow($cleanupFailure); try { (new Spinner('Running...'))->spin(function () use ($callbackFailure): never { @@ -80,8 +85,8 @@ public function testCallbackFailureRemainsPrimaryWhenTerminalRestorationFails(): }); $this->fail('Expected the spinner callback to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($callbackFailure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($canceled ? $cleanupFailure : $callbackFailure, $exception); } } @@ -161,8 +166,9 @@ public function testCancellationDuringStopWaitsForTheLastFrame(): void $spinner->spin(static function () use ($spinner, $callbackFinished): void { $spinner->renderStarted->pop(1); Event::defer(static fn () => $callbackFinished->push(true)); + throw new RuntimeException('Callback failed before the spinner stopped.'); }); - } catch (CanceledException $exception) { + } catch (Throwable $exception) { $cancellation = $exception; } }); From f962b40b7fc2b714ebe9406b31ae72db2a807beb Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:18 +0000 Subject: [PATCH 10/12] Preserve cancellation while rendering the final task summary Select the caller failure after the animation and terminal have settled. Preserve the first ordinary error when rendering also fails and propagate an interruption of the caller during cleanup in both rendering modes. Exercise the public task runner with decorated and undecorated output when a kept summary encounters cancellation after the callback fails. --- src/prompts/src/Task.php | 27 ++++++++++++--------------- tests/Prompts/TaskTest.php | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/prompts/src/Task.php b/src/prompts/src/Task.php index e11e915f8..bd713cf86 100644 --- a/src/prompts/src/Task.php +++ b/src/prompts/src/Task.php @@ -725,12 +725,12 @@ protected function renderStatically(Closure $callback): mixed $cleanupFailure = $this->settleOperation(success: $success); - if ($operationFailure !== null) { - throw $operationFailure; + if ($cleanupFailure !== null) { + throw Coroutine::preferCancellation($operationFailure, $cleanupFailure); } - if ($cleanupFailure !== null) { - throw $cleanupFailure; + if ($operationFailure !== null) { + throw $operationFailure; } return $result; @@ -750,7 +750,7 @@ protected function renderInCoroutine(Closure $callback): mixed { $animation = null; $result = null; - $operationFailure = null; + $failure = null; $success = false; try { @@ -771,7 +771,7 @@ protected function renderInCoroutine(Closure $callback): mixed $result = $callback($logger); $success = true; } catch (Throwable $exception) { - $operationFailure = $exception; + $failure = $exception; } $animationFailure = null; @@ -779,21 +779,18 @@ protected function renderInCoroutine(Closure $callback): mixed try { $animationFailure = $animation?->stop(); } catch (Throwable $exception) { - $animationFailure = $exception; + $failure = Coroutine::preferCancellation($failure, $exception); } $cleanupFailure = $this->settleOperation(renderFinalFrame: true, success: $success); - if ($operationFailure !== null) { - throw $operationFailure; - } - - if ($animationFailure !== null) { - throw $animationFailure; + if ($cleanupFailure !== null && Coroutine::causedByCancellation($cleanupFailure)) { + $failure = Coroutine::preferCancellation($failure, $cleanupFailure); } - if ($cleanupFailure !== null) { - throw $cleanupFailure; + $failure ??= $animationFailure ?? $cleanupFailure; + if ($failure !== null) { + throw $failure; } return $result; diff --git a/tests/Prompts/TaskTest.php b/tests/Prompts/TaskTest.php index 79bdb5993..49e3f294f 100644 --- a/tests/Prompts/TaskTest.php +++ b/tests/Prompts/TaskTest.php @@ -16,9 +16,11 @@ use Hypervel\Prompts\Themes\Default\TaskRenderer; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use PHPUnit\Framework\Attributes\TestWith; use ReflectionMethod; use ReflectionProperty; use RuntimeException; +use Swoole\Coroutine\CanceledException; use function Hypervel\Prompts\task; @@ -91,6 +93,22 @@ public function testDoesNotPrintStaticCompletionLineAfterFailure(): void Prompt::assertStrippedOutputDoesntContain('✔ My Task'); } + #[TestWith([false])] + #[TestWith([true])] + public function testCancellationWhileRenderingTheFinalSummaryPropagatesAfterCallbackFailure(bool $decorated): void + { + Prompt::fake(); + Prompt::setOutput(new BufferedConsoleOutput(decorated: $decorated)); + $this->expectException(CanceledException::class); + + (new Task('Deploy', keepSummary: true))->run(static function (Logger $logger): never { + $logger->success('Uploaded'); + Prompt::terminal()->shouldReceive('cols')->once()->andThrow(new CanceledException); + + throw new RuntimeException('Deploy failed.'); + }); + } + public function testPrintsCompletionLineAfterSuccessfulCoroutineTaskWithSummary(): void { Prompt::fake(); From bf237350fb1c837c556dcf2dcf703d4d693b5838 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:18 +0000 Subject: [PATCH 11/12] Propagate the failure selected during progress bar cleanup Starting a progress bar and mapping its items both restored terminal state after an exception, then discarded the outcome. Use the selected exception so cancellation during the error frame or terminal restoration reaches the caller. Preserve the original error when cleanup fails normally. --- src/prompts/src/Progress.php | 14 ++++++-------- tests/Prompts/ProgressTest.php | 25 ++++++++++++++++++------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/prompts/src/Progress.php b/src/prompts/src/Progress.php index 2a2bb9541..f3d0bc363 100644 --- a/src/prompts/src/Progress.php +++ b/src/prompts/src/Progress.php @@ -98,13 +98,11 @@ public function map(Closure $callback): array try { $this->renderTerminalFrame(); - } catch (Throwable) { - // The callback failure remains primary while settlement continues. + } catch (Throwable $renderFailure) { + $e = Coroutine::preferCancellation($e, $renderFailure); } - $this->settleOperation($e); - - throw $e; + throw $this->settleOperation($e); } $this->finish(); @@ -159,9 +157,7 @@ public function start(): void $this->state = 'active'; } catch (Throwable $exception) { - $this->settleOperation($exception); - - throw $exception; + throw $this->settleOperation($exception); } } @@ -204,6 +200,8 @@ public function finish(): void /** * Restore signal and terminal state for one progress operation. + * + * @return ($failure is Throwable ? Throwable : null|Throwable) */ private function settleOperation(?Throwable $failure = null): ?Throwable { diff --git a/tests/Prompts/ProgressTest.php b/tests/Prompts/ProgressTest.php index e98fc4f2c..50a8c93c7 100644 --- a/tests/Prompts/ProgressTest.php +++ b/tests/Prompts/ProgressTest.php @@ -12,8 +12,10 @@ 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; @@ -158,7 +160,9 @@ public function testRepeatedStartRestoresTheApplicationSignalState(): void } #[RunInSeparateProcess] - public function testStartFailureRestoresExactSignalAndTerminalState(): void + #[TestWith([false])] + #[TestWith([true])] + public function testStartFailureRestoresExactSignalAndTerminalState(bool $canceled): void { Prompt::fake(); $originalHandler = pcntl_signal_get_handler(SIGINT); @@ -166,6 +170,11 @@ public function testStartFailureRestoresExactSignalAndTerminalState(): void $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 = []; @@ -197,8 +206,8 @@ protected function doWrite(string $message, bool $newline): void $progress->start(); $this->fail('Expected the initial progress render to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($failure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($expected, $exception); } $this->assertSame(["\e[?25l", "\e[?25h"], $output->directWrites); @@ -260,12 +269,14 @@ public function testCallbackFailureRendersOneUndecoratedErrorFrameAndSettles(): ); } - public function testCallbackFailureRemainsPrimaryWhenRenderingAndTerminalCleanupFail(): void + #[TestWith([false])] + #[TestWith([true])] + public function testCallbackFailureRemainsPrimaryUnlessCleanupIsCanceled(bool $canceled): void { Prompt::fake(); $callbackFailure = new RuntimeException('progress callback failed'); $renderFailure = new RuntimeException('unable to render progress error'); - $cleanupFailure = new RuntimeException('unable to restore terminal'); + $cleanupFailure = $canceled ? new CanceledException : new RuntimeException('unable to restore terminal'); $output = new class($renderFailure) extends BufferedConsoleOutput { public bool $failFrames = false; @@ -306,8 +317,8 @@ protected function doWrite(string $message, bool $newline): void }); $this->fail('Expected the progress callback to fail.'); - } catch (RuntimeException $exception) { - $this->assertSame($callbackFailure, $exception); + } catch (CanceledException|RuntimeException $exception) { + $this->assertSame($canceled ? $cleanupFailure : $callbackFailure, $exception); } $this->assertSame("\e[?25l", $output->directWrites[0]); From e7b56aed809306fa306ee0a5d9bf7df7f8d654b3 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:49:18 +0000 Subject: [PATCH 12/12] Allow for elapsed time in the Passport device code expiry test The OAuth server reads the clock once to issue a device code and again to report the time remaining. Crossing a second boundary gives a valid lifetime of 599 seconds. Use the same tolerance as the other grant tests while keeping the expected ten-minute lifetime. --- tests/Passport/Feature/DeviceAuthorizationGrantTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Passport/Feature/DeviceAuthorizationGrantTest.php b/tests/Passport/Feature/DeviceAuthorizationGrantTest.php index 9dc1be9d6..3f40e8dc8 100644 --- a/tests/Passport/Feature/DeviceAuthorizationGrantTest.php +++ b/tests/Passport/Feature/DeviceAuthorizationGrantTest.php @@ -54,7 +54,7 @@ public function testIssueDeviceCode(): void $this->assertArrayHasKey('device_code', $json); $this->assertArrayHasKey('user_code', $json); $this->assertSame(5, $json['interval']); - $this->assertSame(600, $json['expires_in']); + $this->assertEqualsWithDelta(600, $json['expires_in'], 2); $this->assertSame('http://localhost/oauth/device', $json['verification_uri']); $this->assertSame('http://localhost/oauth/device?user_code=' . $json['user_code'], $json['verification_uri_complete']); }