Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
49 changes: 48 additions & 1 deletion src/coroutine/src/Coroutine.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,57 @@ private static function runChild(callable $callable, array $context): void
* that the timeout elapsed. It is not a general failure signal.
*
* @param list<int> $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);

// 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.');
}

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<int> $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(...));
}

/**
Expand Down
6 changes: 1 addition & 5 deletions src/coroutine/src/Parallel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
34 changes: 7 additions & 27 deletions src/coroutine/src/Waiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -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();

Expand Down Expand Up @@ -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;
}
}
14 changes: 2 additions & 12 deletions src/docs/coroutines.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand Down
6 changes: 1 addition & 5 deletions src/grpc/src/Client/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]],
];
Expand Down
2 changes: 1 addition & 1 deletion src/phpstan/src/Rules/Coroutine/CoroutineRuleHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
];

Expand Down
14 changes: 6 additions & 8 deletions src/prompts/src/Progress.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -159,9 +157,7 @@ public function start(): void

$this->state = 'active';
} catch (Throwable $exception) {
$this->settleOperation($exception);

throw $exception;
throw $this->settleOperation($exception);
}
}

Expand Down Expand Up @@ -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
{
Expand Down
4 changes: 1 addition & 3 deletions src/prompts/src/Prompt.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,7 @@ public function prompt(): mixed
try {
$this->restoreTerminalState();
} catch (Throwable $exception) {
if ($operationFailure === null) {
throw $exception;
}
throw Coroutine::preferCancellation($operationFailure, $exception);
}
}
}
Expand Down
20 changes: 10 additions & 10 deletions src/prompts/src/Spinner.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
}
Expand Down Expand Up @@ -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);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/prompts/src/Support/PromptAnimation.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public function stop(): ?Throwable
$this->coroutineId = null;

$this->stop->push(true);
Coroutine::join([$coroutineId]);
Coroutine::joinUninterruptibly([$coroutineId]);
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

return $this->renderFailure;
}
Expand Down
27 changes: 12 additions & 15 deletions src/prompts/src/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -750,7 +750,7 @@ protected function renderInCoroutine(Closure $callback): mixed
{
$animation = null;
$result = null;
$operationFailure = null;
$failure = null;
$success = false;

try {
Expand All @@ -771,29 +771,26 @@ protected function renderInCoroutine(Closure $callback): mixed
$result = $callback($logger);
$success = true;
} catch (Throwable $exception) {
$operationFailure = $exception;
$failure = $exception;
}

$animationFailure = null;

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;
Expand Down
Loading
Loading