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
50 changes: 50 additions & 0 deletions docs/plans/2026-11-25-coroutine-channel-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Coroutine channel inspection

Give callers a small, working inspection API on `Hypervel\Contracts\Engine\ChannelInterface`. Hypervel owns this contract. Its implementation wraps Swoole in `Hypervel\Engine\Channel`. The same class remains the place to compare future Hyperf improvements.

## Public contract

| Call | Meaning and implementation |
| --- | --- |
| `push($data, $timeout)`, `pop($timeout)`, `close()` | Keep signatures, return values, timeout units, channel element types and suspension behavior. Closing prevents further pushes and wakes waiters. Buffered values can still be popped. |
| `length()`, `capacity()` | Return the current buffered count and the maximum, respectively. Declare native `length(): int` on the interface. Return the existing Swoole capacity property from `capacity(): int`. Remove the two `get*` names. |
| `isEmpty()`, `isFull()`, `isClosed()` | Use the inherited occupancy methods. Rename `isClosing()` to `isClosed()` and read the wrapper’s closed flag. Set it before native close resumes waiting coroutines. A later close returns false. |
| `hasWaitingProducers()`, `hasWaitingConsumers()` | Report whether a coroutine is blocked pushing or popping. Inspect the corresponding native queue on demand, including while close is waking other waiters. |
| `timedOut()`, `wasCanceled()` | Inspect the native error immediately after a failed push or pop, before yielding. A successful call can leave an earlier error in place. |

The native waiter counts are exposed by Swoole’s `ext-src/swoole_channel_coro.cc`. Its `src/coroutine/channel.cc` removes each waiter before resuming it. While one resumed consumer is running, another can still be waiting on the same closed channel. The implementation is one native stats read per explicit query:

```php
public function hasWaitingProducers(): bool
{
return $this->stats()['producer_num'] > 0;
}

public function hasWaitingConsumers(): bool
{
return $this->stats()['consumer_num'] > 0;
}
```

Remove the four throwing stubs and their exception import. Drop `isAvailable()`, which was simply the inverse of closed. Occupancy, closure and waiting answer different questions. All three are snapshots. Push and pop stay free of stats reads, added counters and error resets. Retain the pool’s own waiter count for its release path.

## Consumer migration

- Trace receivers before renaming calls, overrides and test-double expectations throughout components, including its package source, tests, fixtures, skeletons and guides. The coordinator’s shutdown state, a keepalive connection’s timeout, coroutine cancellation and unrelated streams or queues have their own APIs.
- Use `length()` for counts and `isEmpty()` for occupancy. Drop a guard around a repeated close when the return value is ignored and the receiver is the engine channel. Retain predicates that control other work. Preserve existing cancellation, retry, timeout and cleanup responsibilities at each call site.
- Cover engine sockets, coroutine primitives, AI streams, gRPC, Redis subscribers, connection pools, the watcher and server-process tests. Check the analyzer and its fixtures for method-name strings. Its suspension rules key on push, pop and close.
- Update the Channels section of the coroutine guide with the new names, buffered reads after closure, and immediate inspection after failure. Keep the guidance to wrap a false payload when the caller needs to distinguish it from a failed pop.

## Cancellation in framework consumers

- Redis subscriber command acknowledgements and PONGs share reusable reply channels. Once a command has been sent, abandoning its wait leaves a reply for the next command. Several acknowledgements can also fill the buffer and block the receiver. Use a single private reply helper for both command paths. On a failed pop, preserve the receiver's terminal failure, recognize native cancellation or timeout, and otherwise report closure. On any exception from the wait, interrupt the invoker and rethrow the original exception even if cleanup fails. Both thrown and non-throwing coroutine cancellation must close the transport before another send.
- A canceled enqueue on a full SafeSocket send channel throws `CanceledException` in either socket error mode. The background sender retains its socket and queued writes.
- On native socket reads, `SOCKET_ECANCELED` plus the current coroutine's cancellation flag identifies owner cancellation, even when `recvAll()` has received part of the requested bytes. A different coroutine can interrupt the socket without canceling the reader. Return partial data on ordinary timeouts. Classify a timeout only for native false: a subsequent empty EOF can retain the previous timeout code. An empty `recvAll()` means EOF; an empty framed `recvPacket()` can also carry a current protocol error. Keep both receive methods' normal data and error-mode semantics.
- Exercise both Redis cancellation modes and both reply entry points with the existing controlled connection. Verify the owner sees cancellation and subsequent sends are rejected. Use local socket pairs for canceled enqueues and reads, foreign interruption, and a timeout followed by EOF. Reuse the existing close and timeout tests.

## Verification and delivery

1. Exercise both sides of a real capacity-one channel. Fill it, block a producer, pop and observe the producer queue clear. Block a consumer on an empty channel, wake it and observe the consumer queue clear. Include the closed-channel wakeup case, checking the state from the resumed coroutine while another waiter is still queued. Use bounded waits and close in cleanup.
2. Adapt existing tests for counts, close/drain, repeat close, failed pushes, timeouts and cancellation. Check the failure reason immediately after the failed operation. Exercise the callers’ existing tests for cancellation, shutdown, queue occupancy and Redis response handling.
3. Run touched test files as they change. At the verification checkpoint run components’ CS Fixer, PHPStan and targeted tests in order. Review the full diff and search for stale names, including method names passed as strings.
4. Obtain review across the contract, implementation and framework consumers. After signoff remove the completed channel item from `docs/todo.md` and commit on the framework branch.
17 changes: 0 additions & 17 deletions docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@

- Create hypervel/react-starter-kit. Include the standard skeleton pieces that currently only exist as follow-ups: a `composer dev` script for running the Hypervel development server and frontend asset watcher together, plus explicit Hypervel Vite refresh paths instead of the Laravel plugin's `refresh: true` shortcut.

## Artisan

- Track the Swoole fix for signal behavior after a coroutine signal wait ends. In Swoole 6.2.2, the generic signal backend used by default on macOS keeps intercepting a signal after `Coroutine\System::waitSignal()` returns and drops later deliveries, so `schedule:run`'s second termination signal releases running tasks' overlap mutexes but no longer stops the process. Linux's default signalfd backend is unaffected. Once a fixed release is available, raise the `ext-swoole` constraint and verify scheduler force-stop and Testbench signal cleanup on macOS.

## Wayfinder

- Fix `@laravel/vite-plugin-wayfinder` generation scheduling upstream. Each plugin instance should capture its own hook context, normalize Windows path separators, parse a documented multiword command into an argument vector without shell expansion, serialize its own runs, collapse a burst into one follow-up run, recover after failure, and remain isolated from other plugin instances. Components should not carry a scheduler or shell workaround for plugin-owned behavior.
Expand Down Expand Up @@ -104,21 +100,8 @@ Remove older ways of doing things once a modern equivalent fully replaces them,
## HTTP Client

- Run a broader Guzzle performance study using the ownership and Sentry benchmark harnesses: SDK workloads, multiple concurrency levels, sustained traffic, cold/cached startup, execution outside coroutines, individual promise operations, and pending-work memory. Compare independent checkouts with matched dependencies and record CPU, latency, connection reuse and resource cleanup. Profile measured bottlenecks and optimize only where the improvement justifies the complexity.
- Recheck streaming performance once a build containing the Swoole native `curl_multi_select()` fix is available. The affected hook can consume ready response data internally and then wait for another event or its timeout before returning. Hypervel therefore sometimes delays an SSE event or completion by up to one second, even though the data has arrived. This requires no Hypervel workaround.
- Run `Hypervel\Tests\Http\Client\CurlStreamingHandlerTest::testNativeWaitReportsDataArrivingBetweenPerformAndSelect` against the patched extension with its temporary version-gate skip removed locally. Verify both mid-stream readiness and completion, plus the existing quiet-provider timeout/cancellation and cleanup tests. Update the committed version gate only after identifying the actual fixed release; the current gate does not establish that a later release is fixed.
- In an idle window, use `tests/Benchmarks/HttpTransport` and its README to repeat alternating paired measurements before/after high-water buffering on the same patched runtime. Keep dependencies, TLS verification, idle-retention bound, PHP/OPcache/JIT/GC settings and request concurrency identical. Cover paced events, unpaced bulk responses and slow consumers, then repeat sustained concurrent traffic. Check first-event and completion latency (including outliers), throughput, client CPU, memory, connection reuse and descriptor cleanup. Confirm the one-second stalls disappear without changing Hypervel's select interval or buffering strategy.
- Record the native PR/build, settings and raw reports before publishing buffering performance claims. If a verified problem remains, investigate its owning layer rather than adding polling, shorter waits or a producer coroutine to hide it.
- Once the HTTP client can optionally use Swoole's coroutine HTTP client as its transport instead of curl, explore and benchmark that transport for Inertia SSR requests. Each SSR render posts the page JSON to a local SSR server through the `inertia-ssr` connection (`HttpGateway::CONNECTION`), which makes it a good candidate for the alternative transport. Compare the curl and Swoole transports on that connection against a local SSR server under concurrent load, measuring latency, throughput, client CPU, memory and connection reuse, and use the Swoole transport for the SSR connection if it is a clear improvement.

## HTTP Server

- Once a Swoole release ships `http2_cancel_on_stream_reset` ([swoole-src#6436](https://github.com/swoole/swoole-src/pull/6436), which replaced our stream-reset event in [swoole-src#6379](https://github.com/swoole/swoole-src/pull/6379)), raise the `ext-swoole` constraint and add it to the global `settings` in `config/server.php` (components and the `hypervel/hypervel` skeleton) as `env('SERVER_HTTP2_CANCEL_ON_STREAM_RESET', false)`. With it on, a client's HTTP/2 stream reset throws `CanceledException` into that request's coroutine, which Hypervel already handles as a quiet cancellation, so AI streams and gRPC calls stop when their client cancels. Document the setting and env var in `src/docs/deployment.md`, including when to use it: turn it on for gRPC services and other apps reached over HTTP/2 directly or through proxies that share backend connections (Envoy, service meshes); leave it off for ordinary apps, because it interrupts every in-flight HTTP/2 request at its next wait, not just streams, so multi-step work can stop halfway. It has no effect behind nginx, which talks HTTP/1.1 to Swoole. It only works in the global settings; a listener's own `settings`, including the gRPC listener's, ignore it. Update the HTTP/2 reset notes in `src/docs/responses.md`, `src/docs/ai-sdk.md` and `src/docs/grpc.md`.
- Remove trailer-stream one-chunk lookahead once the minimum supported Swoole release includes [swoole-src#6124](https://github.com/swoole/swoole-src/pull/6124). Current releases send an empty `END_STREAM` DATA frame before trailer HEADERS when `end()` receives no body after `write()`, so `ResponseBridge` retains the final chunk for `end($chunk)` and delays delivery by one chunk. Once fixed, raise the `ext-swoole` constraint, write every chunk immediately, emit trailers, call bare `end()`, invert the deterministic bridge ordering tests, and add real gRPC incremental-delivery coverage.

## Engine

- `Hypervel\Engine\Channel::hasProducers()`, `hasConsumers()`, `isReadable()` and `isWritable()` are inherited Hyperf stubs that always throw. Implement them with Swoole's `Channel::stats()` (`producer_num`, `consumer_num`, `queue_num`), or remove them from `ChannelInterface`, after checking their close, read and write semantics.

## Documentation

- Publish reproducible Hypervel 0.4 benchmarks on a dedicated documentation page before linking them from the introduction. Record the framework, PHP, Swoole, and dependency versions; use the same hardware and load-generation conditions for every runtime; publish the benchmark applications and configuration; and include the raw results, collection date, and limitations. Do not reuse the Hypervel 0.3 results as current data. Once the page is published, add it to `src/docs/documentation.md` and link to it from the introduction.
Expand Down
1 change: 1 addition & 0 deletions skeletons/hypervel/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ APP_MAINTENANCE_DRIVER=file

# SERVER_STATIC_FILE_HANDLER=true
# SERVER_MAX_REQUESTS=100000
# SERVER_HTTP2_CANCEL_ON_STREAM_RESET=false

BCRYPT_ROUNDS=12

Expand Down
2 changes: 2 additions & 0 deletions skeletons/hypervel/config/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
Constant::OPTION_OPEN_TCP_NODELAY => true,
Constant::OPTION_MAX_COROUTINE => 100000,
Constant::OPTION_OPEN_HTTP2_PROTOCOL => (bool) env('SERVER_HTTP2', true),
// Stock Swoole 6.3.0RC2 warns about this option even when it is false.
...((bool) env('SERVER_HTTP2_CANCEL_ON_STREAM_RESET', false) ? ['http2_cancel_on_stream_reset' => true] : []),
Constant::OPTION_MAX_REQUEST => (int) env('SERVER_MAX_REQUESTS', 100000),
Constant::OPTION_MAX_WAIT_TIME => (int) env('SERVER_MAX_WAIT_TIME', 3),
Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
Expand Down
2 changes: 2 additions & 0 deletions skeletons/react-starter-kit/config/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
Constant::OPTION_OPEN_TCP_NODELAY => true,
Constant::OPTION_MAX_COROUTINE => 100000,
Constant::OPTION_OPEN_HTTP2_PROTOCOL => (bool) env('SERVER_HTTP2', true),
// Stock Swoole 6.3.0RC2 warns about this option even when it is false.
...((bool) env('SERVER_HTTP2_CANCEL_ON_STREAM_RESET', false) ? ['http2_cancel_on_stream_reset' => true] : []),
Constant::OPTION_MAX_REQUEST => (int) env('SERVER_MAX_REQUESTS', 100000),
Constant::OPTION_MAX_WAIT_TIME => (int) env('SERVER_MAX_WAIT_TIME', 3),
Constant::OPTION_SOCKET_BUFFER_SIZE => 2 * 1024 * 1024,
Expand Down
6 changes: 3 additions & 3 deletions src/ai/src/Gateway/TextGenerationLoop.php
Original file line number Diff line number Diff line change
Expand Up @@ -958,15 +958,15 @@ private function concurrentToolResults(array $resolved, int $max, Closure $execu
for ($worker = 0; $worker < $max && $next < $count && $failure === null; ++$worker) {
$concurrent->fork(function () use ($resolved, $execute, $runner, $count, $events, &$next, &$completed, &$results, &$failure): void {
$work = function () use ($resolved, $execute, $count, $events, &$next, &$completed, &$results, &$failure): void {
while ($next < $count && $failure === null && ! $events->isClosing()) {
while ($next < $count && $failure === null && ! $events->isClosed()) {
// Reserve before invoking user code, which may suspend immediately.
$index = $next++;
$result = $execute(...$resolved[$index]);

if ($result instanceof Generator) {
foreach ($result as $event) {
if (! $events->push($event)) {
if ($events->isCanceled()) {
if ($events->wasCanceled()) {
throw new CanceledException('Forwarding tool output was canceled.');
}

Expand Down Expand Up @@ -1000,7 +1000,7 @@ private function concurrentToolResults(array $resolved, int $max, Closure $execu
$event = $events->pop();

if ($event === false) {
if ($events->isCanceled()) {
if ($events->wasCanceled()) {
throw new CanceledException('Waiting for tool output was canceled.');
}

Expand Down
6 changes: 3 additions & 3 deletions src/ai/src/Streaming/BroadcastBatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function push(StreamEvent $event): void
}

if (! $this->channel->push([$event, $arrived])) {
if ($this->channel->isCanceled()) {
if ($this->channel->wasCanceled()) {
throw new CanceledException('Waiting to broadcast an agent event was canceled.');
}

Expand Down Expand Up @@ -183,7 +183,7 @@ protected function read(?int $deadline = null): array|false
{
$timeout = -1.0;

if ($this->channel->isEmpty() && ! $this->channel->isClosing()) {
if ($this->channel->isEmpty() && ! $this->channel->isClosed()) {
if ($deadline !== null && $deadline <= hrtime(true)) {
return false;
}
Expand All @@ -203,7 +203,7 @@ protected function read(?int $deadline = null): array|false

$event = $this->channel->pop($timeout);

if ($event === false && $this->channel->isCanceled()) {
if ($event === false && $this->channel->wasCanceled()) {
throw new CanceledException('Waiting for an agent broadcast event was canceled.');
}

Expand Down
4 changes: 2 additions & 2 deletions src/connection-pool/src/KeepaliveConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public function call(Closure $closure, bool $refresh = true): mixed
$channel = $this->channel;
$connection = $channel->pop($this->pool->getOptions()->waitTimeout);
if ($connection === false) {
if ($channel->isCanceled()) {
if ($channel->wasCanceled()) {
throw new CanceledException('The keepalive connection wait was canceled.');
}

Expand Down Expand Up @@ -225,7 +225,7 @@ public function isTimeout(): bool

return $maxIdleTime !== null
&& $this->lastUseTime < hrtime(true) / 1e9 - $maxIdleTime
&& $this->channel->getLength() > 0;
&& ! $this->channel->isEmpty();
}

/**
Expand Down
Loading