Skip to content

Commit 90302f9

Browse files
committed
Add the benchmarks suite; restore() cancels the scoped context
CI failed: testo.php declares a Benchmarks suite and the empty directory is not tracked by git. The new benchmark showed a leak: every scope derives withCancel() from the parent and restore() left it attached, so a scope per job under a long-lived parent accumulated children. restore() now cancels the scoped context like Go's NotifyContext stop, after applying a pending signal so its cause is kept.
1 parent dd71221 commit 90302f9

7 files changed

Lines changed: 92 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111
`signal()`, `restore()`) cancels a `rasuvaeff/context` context on
1212
SIGTERM/SIGINT through `requestCancel()`; a second signal restores and
1313
hands itself to the previous disposition. `SignalReceived` is the reason.
14+
`restore()` cancels the scoped context (like Go's `NotifyContext` stop), so
15+
a scope per job never stays attached to a long-lived parent.

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ $scope->signal(); // the first signal received, or null
9696
|---|---|
9797
| First signal of the set | `requestCancel(new SignalReceived($signal))`. Nothing else runs in the handler; the next check terminates the context, runs its `onTerminate()` listeners and throws `ContextCancelledException` with the `SignalReceived` as `previous` |
9898
| Second signal of the set | The scope restores the previous handlers and hands this signal to them: a PHP handler is called, the default disposition terminates the process (Ctrl+C twice stops a stuck worker), an ignored signal stays ignored |
99-
| `restore()` | Previous handlers and the previous `pcntl_async_signals()` mode come back; idempotent; the context keeps its state |
99+
| `restore()` | Previous handlers and the previous `pcntl_async_signals()` mode come back, then the scoped context is cancelled (like Go's `NotifyContext` stop) so it never stays attached to a long-lived parent; a signal cause already received is kept; idempotent |
100100
| Parent cancelled/expired | The scoped context terminates with it (it is `$parent->withCancel()`) |
101101
| `SIGKILL`, `SIGSTOP`, duplicates, empty set | `InvalidArgumentException` before anything is installed |
102102
| A signal already owned by another active scope | `LogicException` |

‎README.ru.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ $scope->signal(); // первый полученный сигнал или nul
9898
|---|---|
9999
| Первый сигнал из набора | `requestCancel(new SignalReceived($signal))`. Больше в обработчике ничего не исполняется; следующая проверка завершает контекст, вызывает его `onTerminate()`-слушателей и бросает `ContextCancelledException` с `SignalReceived` в `previous` |
100100
| Второй сигнал из набора | Scope восстанавливает прежние обработчики и передаёт им этот сигнал: PHP-обработчик вызывается, поведение по умолчанию завершает процесс (двойной Ctrl+C останавливает зависший воркер), игнорируемый сигнал остаётся игнорируемым |
101-
| `restore()` | Возвращаются прежние обработчики и прежний режим `pcntl_async_signals()`; идемпотентен; состояние контекста не меняется |
101+
| `restore()` | Возвращаются прежние обработчики и прежний режим `pcntl_async_signals()`, затем контекст scope отменяется (как `stop()` у `NotifyContext` в Go), чтобы он не остался навсегда привязан к долгоживущему родителю; уже полученная причина-сигнал сохраняется; идемпотентен |
102102
| Родитель отменён/истёк | Контекст scope завершается вместе с ним (это `$parent->withCancel()`) |
103103
| `SIGKILL`, `SIGSTOP`, дубликаты, пустой набор | `InvalidArgumentException` до установки чего-либо |
104104
| Сигнал уже занят другим активным scope | `LogicException` |

‎benchmarks/SignalScopeBench.php‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rasuvaeff\Context\Cli\Benchmarks;
6+
7+
use Rasuvaeff\Context\Cli\SignalScope;
8+
use Rasuvaeff\Context\Context;
9+
use Testo\Bench;
10+
11+
/**
12+
* Cost of a scope per job: install and restore the handlers of two signals,
13+
* against the bare withCancel() every scope performs.
14+
*/
15+
final class SignalScopeBench
16+
{
17+
private static ?Context $parent = null;
18+
19+
#[Bench(
20+
callables: [
21+
'withCancel() only' => [self::class, 'deriveOnly'],
22+
],
23+
calls: 10_000,
24+
iterations: 10,
25+
)]
26+
public static function listenAndRestore(): ?int
27+
{
28+
$scope = SignalScope::listen(self::$parent ??= Context::background(), [\SIGUSR1, \SIGUSR2]);
29+
$scope->restore();
30+
31+
return $scope->signal();
32+
}
33+
34+
public static function deriveOnly(): bool
35+
{
36+
[$context] = (self::$parent ??= Context::background())->withCancel();
37+
38+
return $context->isTerminated();
39+
}
40+
}

‎llms.txt‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ Requires `ext-pcntl`, `ext-posix` (no Windows) and `rasuvaeff/context` ^0.3.
2121
- One process, one handler table: two active scopes on one signal →
2222
`LogicException`. `SIGKILL`/`SIGSTOP`/duplicates/empty → `InvalidArgumentException`.
2323
- Always restore: use `run()` or `restore()` in `finally`. The scope enables
24-
`pcntl_async_signals(true)` and restores the previous mode.
24+
`pcntl_async_signals(true)` and restores the previous mode. `restore()` also
25+
cancels the scoped context (like Go's NotifyContext stop); a signal cause
26+
already received is kept. Use the context only inside the scope.
2527

2628
## API
2729

‎src/SignalScope.php‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,11 @@ public function signal(): ?int
120120
}
121121

122122
/**
123-
* Puts back the previous handlers and the previous async-signals mode.
124-
* Idempotent. The context stays as it is: a cancelled one stays
125-
* cancelled, an active one stays active.
123+
* Puts back the previous handlers and the previous async-signals mode,
124+
* then cancels the scoped context (like Go's `NotifyContext` stop): the
125+
* context belongs to the scope, and an uncancelled child would stay
126+
* attached to a long-lived parent forever. A context already cancelled
127+
* by a signal keeps that cause. Idempotent.
126128
*/
127129
public function restore(): void
128130
{
@@ -136,6 +138,8 @@ public function restore(): void
136138
unset(self::$owned[$signal]);
137139
}
138140
pcntl_async_signals($this->previousAsync);
141+
$this->context->isTerminated();
142+
$this->controller->cancel();
139143
}
140144

141145
private function handle(int $signal): void

‎tests/SignalScopeTest.php‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,29 @@ public function restoringPutsBackHandlersAndTheAsyncMode(): void
115115
Assert::false(pcntl_async_signals());
116116
$this->send(\SIGUSR1);
117117
Assert::same($this->previous, [\SIGUSR1]);
118-
Assert::false($scope->context()->isTerminated());
119118
Assert::null($scope->signal());
120119
}
121120

121+
public function restoringCancelsTheScopedContextAndReleasesTheParent(): void
122+
{
123+
[$parent] = Context::background()->withCancel();
124+
$scope = SignalScope::listen($parent, self::SIGNALS);
125+
126+
$scope->restore();
127+
128+
try {
129+
$scope->context()->assertActive();
130+
} catch (ContextCancelledException $exception) {
131+
Assert::null($exception->getPrevious());
132+
Assert::false($parent->isTerminated());
133+
Assert::same($this->childCount($parent), 0);
134+
135+
return;
136+
}
137+
138+
throw new \LogicException('the scoped context was expected to be cancelled');
139+
}
140+
122141
public function aLateRestoreDoesNotStealTheSignalFromTheNextScope(): void
123142
{
124143
$first = SignalScope::listen(Context::background(), self::SIGNALS);
@@ -157,14 +176,22 @@ public function sighupCanBeHandled(): void
157176
Assert::same(pcntl_signal_get_handler(\SIGHUP), \SIG_DFL);
158177
}
159178

160-
public function restoringKeepsACancelledContextCancelled(): void
179+
public function restoringKeepsTheSignalAsTheCause(): void
161180
{
162181
$scope = SignalScope::listen(Context::background(), self::SIGNALS);
163182
$this->send(\SIGUSR2);
164183

165184
$scope->restore();
166185

167-
Assert::true($scope->context()->isCancelled());
186+
try {
187+
$scope->context()->assertActive();
188+
} catch (ContextCancelledException $exception) {
189+
Assert::same($exception->getPrevious()?->getMessage(), 'Received SIGUSR2');
190+
191+
return;
192+
}
193+
194+
throw new \LogicException('a cancellation was expected');
168195
}
169196

170197
public function aSignalOutsideTheSetIsNotHandled(): void
@@ -350,6 +377,14 @@ public function anInvalidSetLeavesNothingInstalled(): void
350377
}
351378
}
352379

380+
private function childCount(Context $context): int
381+
{
382+
$state = (new \ReflectionProperty(Context::class, 'state'))->getValue($context);
383+
$children = \is_object($state) ? (new \ReflectionProperty($state, 'children'))->getValue($state) : [];
384+
385+
return \is_array($children) ? \count($children) : -1;
386+
}
387+
353388
/** Sends the signal to this process and dispatches it before returning. */
354389
private function send(int $signal): void
355390
{

0 commit comments

Comments
 (0)