• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dg / dresscode / 42041664657

30 Oct 2026 03:50PM UTC coverage: 97.067% (-0.7%) from 97.783%
42041664657

push

github

dg
cli: the hidden option --profile writes where the time of a run went, the workers included

`--profile <file>` writes as JSON where the time of a run went, in nanoseconds: the phases (the start of the process,
the start of the container of PHPStan or of a derived one and its scopes, the parse, the passes, the gaps, the print,
the cycle collection, the run as a whole), every rule by the time of its callbacks, how often they ran and how often
they changed the tree, every gap rule by the time of its claims, every file with its size, rounds and passes, and the
peak memory of every process. A worker measures its own files and hands that over with every result and the parent
adds it up, so the totals do not depend on the number of workers. A run with the option leaves the result cache out,
a file served from the cache having nothing to measure.

It says where the time of a run goes, not only how much of it: a comparison of two revisions then names the rule or
the claim that moved. Without the option the engine only asks whether there is a profiler, and wraps a claim in
a measurement only when there is one.

137 of 148 new or added lines in 14 files covered. (92.57%)

162 existing lines in 35 files now uncovered.

29456 of 30346 relevant lines covered (97.07%)

0.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.22
/src/Engine/WorkerPool.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the DressCode, a coding style and upgrade tool for PHP (https://dresscode.run)
5
 * Copyright (c) 2026 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace DressCode\Engine;
9

10
use DressCode\FileResult;
11
use function array_key_exists, count, dirname, function_exists, in_array, is_array, strlen;
12
use const PHP_OS_FAMILY, PHP_SAPI;
13

14

15
/**
16
 * Processes files in worker processes: a TCP server on the loopback hands the paths out one at a time,
17
 * a worker sends each result back as a line of JSON. The parent keeps the cache and the baseline, a worker
18
 * only processes and, when fixing, writes.
19
 * @internal
20
 */
21
final class WorkerPool
22
{
23
        /** microseconds the wait for the workers lasts at most while the progress is watched, so that a spinner turns */
24
        private const ProgressInterval = 100_000;
25

26
        /** seconds the end of a worker is waited for once its connection has closed */
27
        private const EndTimeout = 1;
28

29
        /**
30
         * The listening socket: from ext/sockets when available, because the stream layer on Windows waits 500 ms
31
         * for a socket to become writable before closing it, which a listening one never does.
32
         * @var \Socket|resource|null
33
         */
34
        private mixed $server = null;
35

36
        /** @var array<int, resource>  connected workers by socket id */
37
        private array $sockets = [];
38

39
        /** @var array<int, string>  what a worker sent after its last complete line, by socket id */
40
        private array $buffers = [];
41

42
        /** workers that have connected so far */
43
        private int $accepted = 0;
44

45
        /** workers started once the first has connected */
46
        private int $pending = 0;
47

48
        /** the address the workers connect to */
49
        private string $address = '';
50

51
        /** @var array<int, array{string, float, string}>  path in progress with the time it started and its content, by socket id */
52
        private array $inProgress = [];
53

54
        /** @var ?\Closure(string): string  path => content, read when the path is handed out */
55
        private ?\Closure $read = null;
56

57
        /** @var list<array{resource, string}>  process, file with its output */
58
        private array $workers = [];
59

60
        /** when the last worker was started */
61
        private float $spawnedAt = 0;
62

63
        /** @var list<string> */
64
        private array $queue = [];
65

66
        /** @var array<int, true>  workers asked for what they measured last, by socket id */
67
        private array $finishing = [];
68

69
        /** @var array<string, true>  the files the results depend on, as the workers sent them */
70
        private array $dependencies = [];
71

72
        /** @var array<string, true>  what the analyses of the workers tell the user about the run */
73
        private array $warnings = [];
74

75

76
        public function __construct(
77
                /** @var list<string> the worker command line; --worker with the address is appended */
78
                private readonly array $command,
1 ✔
79
                private readonly int $jobs,
1 ✔
80
                /** working directory of the workers */
81
                private readonly ?string $cwd = null,
1 ✔
82
                /** seconds a worker may spend on one file before the run fails, since a rule has most likely looped */
83
                private readonly int $taskTimeout = 300,
1 ✔
84
                /** seconds a worker may take to connect, the first one filling the cache the others share among them */
85
                private readonly int $connectTimeout = 300,
1 ✔
86
                /** with it, every worker hands over what it measured last once nothing is left, one that got no file among them */
87
                private readonly ?Profiler $profiler = null,
1 ✔
88
                /** the first worker fills a cache the others share before it connects, and they start after that */
89
                private readonly bool $warmFirst = false,
1 ✔
90
        ) {
91
        }
1 ✔
92

93

94
        /**
95
         * The workers a run of the files takes by default: a worker costs about the processing of a few files to start, so one
96
         * for every four files at most, and no more than the processors.
97
         */
98
        public static function countDefaultJobs(int $files): int
99
        {
100
                return max(1, min(self::detectCpuCount(), intdiv($files, 4)));
1 ✔
101
        }
102

103

104
        /** Processors the machine has, 1 when unknown. */
105
        public static function detectCpuCount(): int
106
        {
107
                $count = (int) getenv('NUMBER_OF_PROCESSORS');
1 ✔
108
                if ($count < 1 && is_readable('/proc/cpuinfo')) {
1 ✔
109
                        $count = preg_match_all('~^processor\s*:~m', (string) file_get_contents('/proc/cpuinfo'));
1 ✔
110
                }
111

112
                if ($count < 1 && in_array(PHP_OS_FAMILY, ['Darwin', 'BSD'], true) && function_exists('shell_exec')) {
1 ✔
UNCOV
113
                        $count = (int) @shell_exec('sysctl -n hw.ncpu 2>/dev/null'); // @ a failed command gives no count
×
114
                }
115

116
                return max(1, $count);
1 ✔
117
        }
118

119

120
        /**
121
         * The program of this very package, which a process of DressCode is started as: never the one the process itself was
122
         * started as, which for a test or an application embedding DressCode is another program.
123
         */
124
        public static function locateProgram(): string
125
        {
126
                return \Phar::running(returnPhar: false) ?: dirname(__DIR__, 2) . '/bin/dresscode';
1 ✔
127
        }
128

129

130
        /**
131
         * The PHP a process of DressCode is started with: the same binary with the same ini file, the binary alone loading the
132
         * default one, and the settings the process has beyond it; null where no CLI binary is found to start one.
133
         * @return ?list<string>
134
         */
135
        public static function buildPhpCommand(): ?array
136
        {
137
                $binary = self::findCliBinary();
1 ✔
138
                if ($binary === null) {
1 ✔
UNCOV
139
                        return null;
×
140
                }
141

142
                $ini = php_ini_loaded_file();
1 ✔
143
                $php = [$binary, ...($ini === false ? (php_ini_scanned_files() === false ? ['-n'] : []) : ['-c', $ini])];
1 ✔
144
                return [...$php, ...self::findIniOverrides($php)];
1 ✔
145
        }
146

147

148
        /**
149
         * The PHP a worker is started with, on Windows without OPcache: the workers share its memory there, and PHP with JIT
150
         * crashes once they fill it.
151
         * @return ?list<string>
152
         */
153
        public static function buildWorkerPhpCommand(): ?array
154
        {
155
                $php = self::buildPhpCommand();
1 ✔
156
                return $php === null || PHP_OS_FAMILY !== 'Windows' ? $php : [...$php, '-d', 'opcache.enable_cli=0'];
1 ✔
157
        }
158

159

160
        /** The binary of the process, or under another SAPI than CLI, such as CGI, the CLI binary beside it. */
161
        private static function findCliBinary(): ?string
162
        {
163
                if (PHP_SAPI === 'cli') {
1 ✔
164
                        return PHP_BINARY;
1 ✔
165
                }
166

UNCOV
167
                $path = dirname(PHP_BINARY) . '/php' . (PHP_OS_FAMILY === 'Windows' ? '.exe' : '');
×
UNCOV
168
                return is_file($path) ? $path : null;
×
169
        }
170

171

172
        /**
173
         * The settings the process has and the PHP of the command alone would not, those given by -d above all, as the
174
         * options -d that give them to a worker; PHP tells no process the options it started with, so the PHP of the
175
         * command is asked for its settings and they are compared.
176
         * @param  list<string>  $php
177
         * @return list<string>
178
         */
179
        private static function findIniOverrides(array $php): array
180
        {
181
                $null = PHP_OS_FAMILY === 'Windows' ? 'NUL' : '/dev/null';
1 ✔
182
                $process = @proc_open([...$php, '-r', 'echo serialize(ini_get_all(null, false));'], [1 => ['pipe', 'w'], 2 => ['file', $null, 'w']], $pipes); // @ no settings then
1 ✔
183
                if ($process === false) {
1 ✔
UNCOV
184
                        return [];
×
185
                }
186

187
                $base = @unserialize((string) stream_get_contents($pipes[1])); // @ a PHP that failed to start gives none
1 ✔
188
                fclose($pipes[1]);
1 ✔
189
                proc_close($process);
1 ✔
190
                $own = ini_get_all(details: false);
1 ✔
191
                if (!is_array($base) || $own === false) {
1 ✔
UNCOV
192
                        return [];
×
193
                }
194

195
                $options = [];
1 ✔
196
                foreach ($own as $name => $value) {
1 ✔
197
                        if (array_key_exists($name, $base) && $base[$name] !== $value) {
1 ✔
198
                                $options[] = '-d';
1 ✔
199
                                $options[] = "$name=$value";
1 ✔
200
                        }
201
                }
202

203
                return $options;
1 ✔
204
        }
205

206

207
        /**
208
         * The results by path, each as soon as it arrives; the content of a file is read when it is handed out, so that
209
         * only the files in progress are held.
210
         * @param  list<string>  $paths
211
         * @param  \Closure(string): string  $read  path => content
212
         * @param  ?\Closure(int, array<string, float>): void  $onProgress  files done and the paths in progress
213
         * @return \Generator<string, FileResult>
214
         * @throws \RuntimeException  when a worker fails
215
         */
216
        public function process(array $paths, \Closure $read, ?\Closure $onProgress = null): \Generator
1 ✔
217
        {
218
                $address = $this->listen();
1 ✔
219
                $this->queue = $paths;
1 ✔
220
                $this->read = $read;
1 ✔
221
                $done = 0;
1 ✔
222
                try {
223
                        $count = min($this->jobs, count($this->queue));
1 ✔
224
                        $this->address = $address;
1 ✔
225
                        $this->pending = $this->warmFirst ? $count - 1 : 0;
1 ✔
226
                        for ($i = $count - $this->pending; $i > 0; $i--) {
1 ✔
227
                                $this->workers[] = $this->spawn($address);
1 ✔
228
                        }
229

230
                        while ($done < count($paths) || $this->isFinishing()) {
1 ✔
231
                                foreach ($this->await(watched: $onProgress !== null) as $stream) {
1 ✔
232
                                        foreach ($this->receive((int) $stream) as $path => $result) {
1 ✔
233
                                                $done++;
1 ✔
234
                                                yield $path => $result;
1 ✔
235
                                        }
236
                                }
237

238
                                $this->checkWorkers($done < count($paths));
1 ✔
239
                                if ($onProgress !== null) {
1 ✔
UNCOV
240
                                        $onProgress($done, $this->getInProgress());
×
241
                                }
242
                        }
243

244
                } finally {
1 ✔
245
                        foreach ($this->sockets as $socket) {
1 ✔
246
                                fclose($socket);
1 ✔
247
                        }
248

249
                        $this->closeServer();
1 ✔
250
                        $this->stop();
1 ✔
251
                }
252
        }
1 ✔
253

254

255
        /**
256
         * The files the results of the workers depend on beyond the configuration, as they sent them.
257
         * @return list<string>
258
         */
259
        public function getDependencies(): array
260
        {
261
                return array_keys($this->dependencies);
1 ✔
262
        }
263

264

265
        /**
266
         * What the analyses of the workers tell the user about the run, each thing once.
267
         * @return list<string>
268
         */
269
        public function getWarnings(): array
270
        {
271
                return array_keys($this->warnings);
1 ✔
272
        }
273

274

275
        /** @return string  the address the workers connect to */
276
        private function listen(): string
277
        {
278
                if (function_exists('socket_create')) {
1 ✔
279
                        $server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
1 ✔
280
                        if (
281
                                $server === false
1 ✔
282
                                || !socket_bind($server, '127.0.0.1')
1 ✔
283
                                || !socket_listen($server, $this->jobs)
1 ✔
284
                                || !socket_getsockname($server, $ip, $port)
1 ✔
285
                        ) {
UNCOV
286
                                throw new \RuntimeException('Cannot start the worker server: ' . socket_strerror(socket_last_error()));
×
287
                        }
288

289
                        $this->server = $server;
1 ✔
290
                        return "$ip:$port";
1 ✔
291
                }
292

UNCOV
293
                $context = stream_context_create(['socket' => ['tcp_nodelay' => true]]); // Nagle would delay every small message by an ACK
×
UNCOV
294
                $server = @stream_socket_server('tcp://127.0.0.1:0', $errno, $error, context: $context); // @ is escalated to exception
×
UNCOV
295
                if ($server === false) {
×
UNCOV
296
                        throw new \RuntimeException("Cannot start the worker server: $error");
×
297
                }
298

UNCOV
299
                $this->server = $server;
×
UNCOV
300
                return (string) stream_socket_get_name($server, remote: false);
×
301
        }
302

303

304
        /**
305
         * Waits for messages from the workers, accepting the ones that connect meanwhile; the listening socket
306
         * from ext/sockets is closed as soon as the last worker is in.
307
         * @param  bool  $watched  the progress is drawn, so the wait is short
308
         * @return list<resource>  connections with a message waiting
309
         */
310
        private function await(bool $watched): array
311
        {
312
                $read = array_values($this->sockets);
1 ✔
313
                $write = $except = [];
1 ✔
314
                $seconds = $watched ? 0 : 1;
1 ✔
315
                $microseconds = $watched ? self::ProgressInterval : 0;
1 ✔
316
                $server = $this->server;
1 ✔
317
                if ($server instanceof \Socket) {
1 ✔
318
                        $this->acceptPending($server, blocking: $read === []);
1 ✔
319
                        if ($this->accepted === count($this->workers)) {
1 ✔
320
                                $this->closeServer();
1 ✔
321
                        } else { // short waits while workers may still be connecting
322
                                $seconds = 0;
1 ✔
323
                                $microseconds = 10_000;
1 ✔
324
                        }
325
                } elseif ($server !== null) {
1 ✔
UNCOV
326
                        $read[] = $server;
×
327
                }
328

329
                if ($read === []) { // nothing connected: the workers are still starting, or they are gone
1 ✔
330
                        return [];
1 ✔
331
                }
332

333
                if (@stream_select($read, $write, $except, $seconds, $microseconds) === false) { // @ is escalated to exception
1 ✔
UNCOV
334
                        throw new \RuntimeException('Waiting for the workers failed.');
×
335
                }
336

337
                $streams = [];
1 ✔
338
                foreach ($read as $stream) {
1 ✔
339
                        if ($stream === $server) {
1 ✔
UNCOV
340
                                $this->acceptStream($stream);
×
341
                        } else {
342
                                $streams[] = $stream;
1 ✔
343
                        }
344
                }
345

346
                return $streams;
1 ✔
347
        }
348

349

350
        /** Accepts every worker waiting to connect; with nothing to do otherwise, waits for the first one. */
351
        private function acceptPending(\Socket $server, bool $blocking): void
352
        {
353
                while (true) {
1 ✔
354
                        $read = [$server];
1 ✔
355
                        $write = $except = null;
1 ✔
356
                        if (socket_select($read, $write, $except, $blocking ? 1 : 0) !== 1) {
1 ✔
357
                                return;
1 ✔
358
                        }
359

360
                        $blocking = false;
1 ✔
361
                        $connection = socket_accept($server);
1 ✔
362
                        if ($connection === false) {
1 ✔
UNCOV
363
                                return;
×
364
                        }
365

366
                        socket_set_option($connection, SOL_TCP, TCP_NODELAY, 1); // Nagle would delay every small message by an ACK
1 ✔
367
                        $stream = socket_export_stream($connection);
1 ✔
368
                        if ($stream === false) {
1 ✔
UNCOV
369
                                throw new \RuntimeException('Cannot use the connection of a worker.');
×
370
                        }
371

372
                        $this->acceptConnection($stream);
1 ✔
373
                }
UNCOV
374
        }
×
375

376

377
        /** @param resource $server */
378
        private function acceptStream($server): void
379
        {
UNCOV
380
                $socket = @stream_socket_accept($server, 0); // @ a false alarm is harmless
×
UNCOV
381
                if ($socket !== false) {
×
UNCOV
382
                        $this->acceptConnection($socket);
×
383
                }
UNCOV
384
        }
×
385

386

387
        /**
388
         * Registers the connection, starts the workers that waited for it, and hands it a path. It is read without
389
         * blocking: a worker may have sent only a part of its line, and waiting for the rest would stop the parent from
390
         * hearing the others and from noticing a worker that is stuck.
391
         * @param resource $socket
392
         */
393
        private function acceptConnection($socket): void
394
        {
395
                stream_set_blocking($socket, enable: false);
1 ✔
396
                $this->accepted++;
1 ✔
397
                for (; $this->pending > 0; $this->pending--) {
1 ✔
398
                        $this->workers[] = $this->spawn($this->address);
1 ✔
399
                }
400

401
                $id = (int) $socket;
1 ✔
402
                $this->sockets[$id] = $socket;
1 ✔
403
                $this->assign($id);
1 ✔
404
        }
1 ✔
405

406

407
        private function closeServer(): void
408
        {
409
                if ($this->server instanceof \Socket) {
1 ✔
410
                        socket_close($this->server);
1 ✔
411
                } elseif ($this->server !== null) {
1 ✔
UNCOV
412
                        fclose($this->server);
×
413
                }
414

415
                $this->server = null;
1 ✔
416
        }
1 ✔
417

418

419
        /**
420
         * The results the worker has finished sending, by path: every line answers the path in progress, and a line
421
         * about any other one is a failure, as is an ended worker with a path in progress.
422
         * @return array<string, FileResult>
423
         */
424
        private function receive(int $id): array
425
        {
426
                $socket = $this->sockets[$id] ?? null;
1 ✔
427
                if ($socket === null) {
1 ✔
UNCOV
428
                        return [];
×
429
                }
430

431
                $chunk = fread($socket, 1 << 20);
1 ✔
432
                if ($chunk === false || ($chunk === '' && feof($socket))) {
1 ✔
433
                        if (isset($this->inProgress[$id])) {
1 ✔
434
                                $end = $this->findWorkerFailure();
1 ✔
435
                                throw new \RuntimeException('A worker ended ' . ($end === null ? '' : "$end ") . "while processing `{$this->inProgress[$id][0]}`." . $this->collectErrors());
1 ✔
436
                        }
437

UNCOV
438
                        $this->disconnect($id);
×
UNCOV
439
                        return [];
×
440
                }
441

442
                $buffer = ($this->buffers[$id] ?? '') . $chunk;
1 ✔
443
                $results = [];
1 ✔
444
                while (($end = strpos($buffer, "\n")) !== false) {
1 ✔
445
                        $data = json_decode(substr($buffer, 0, $end), associative: true);
1 ✔
446
                        $buffer = substr($buffer, $end + 1);
1 ✔
447
                        if (isset($this->finishing[$id]) && is_array($data['profile'] ?? null)) {
1 ✔
448
                                $this->profiler?->merge($data['profile']);
1 ✔
449
                                $this->disconnect($id);
1 ✔
450
                                break;
1 ✔
451
                        }
452

453
                        [$path, , $code] = $this->inProgress[$id] ?? [null, null, ''];
1 ✔
454
                        if (!is_array($data) || $path === null || ($data['path'] ?? null) !== base64_encode($path)) {
1 ✔
455
                                throw new \RuntimeException('A worker sent an unexpected message.' . $this->collectErrors());
1 ✔
456
                        }
457

458
                        unset($this->inProgress[$id]);
1 ✔
459
                        foreach (is_array($data['dependencies'] ?? null) ? $data['dependencies'] : [] as $file) {
1 ✔
460
                                $this->dependencies[(string) $file] = true;
1 ✔
461
                        }
462

463
                        foreach (is_array($data['runWarnings'] ?? null) ? $data['runWarnings'] : [] as $warning) {
1 ✔
464
                                $this->warnings[(string) $warning] = true;
1 ✔
465
                        }
466

467
                        [$results[$path], $profile] = WorkerCodec::decode($data, $code);
1 ✔
468
                        if ($profile !== null) {
1 ✔
469
                                $this->profiler?->merge($profile);
1 ✔
470
                        }
471

472
                        $this->assign($id);
1 ✔
473
                }
474

475
                if (isset($this->sockets[$id]) && strlen($buffer)) {
1 ✔
476
                        $this->buffers[$id] = $buffer;
1 ✔
477
                } else {
478
                        unset($this->buffers[$id]);
1 ✔
479
                }
480

481
                return $results;
1 ✔
482
        }
483

484

485
        /** Hands the next path to the worker; when there is none, asks it for what it measured last, or closes its connection. */
486
        private function assign(int $id): void
487
        {
488
                $path = array_shift($this->queue);
1 ✔
489
                if ($path === null && $this->profiler !== null) {
1 ✔
490
                        $this->finishing[$id] = true;
1 ✔
491
                        fwrite($this->sockets[$id], json_encode(['finish' => true], JSON_THROW_ON_ERROR) . "\n");
1 ✔
492
                        return;
1 ✔
493
                } elseif ($path === null) {
1 ✔
494
                        $this->disconnect($id);
1 ✔
495
                        return;
1 ✔
496
                }
497

498
                $read = $this->read ?? throw new \LogicException('No run is in progress.');
1 ✔
499
                $this->inProgress[$id] = [$path, microtime(as_float: true), $read($path)];
1 ✔
500
                fwrite($this->sockets[$id], json_encode(['path' => base64_encode($path)], JSON_THROW_ON_ERROR) . "\n"); // a path need not be UTF-8
1 ✔
501
        }
1 ✔
502

503

504
        /** @return array<string, float>  path in progress => the time it started */
505
        private function getInProgress(): array
506
        {
UNCOV
507
                $paths = [];
×
UNCOV
508
                foreach ($this->inProgress as [$path, $since]) {
×
UNCOV
509
                        $paths[$path] = $since;
×
510
                }
511

UNCOV
512
                return $paths;
×
513
        }
514

515

516
        private function disconnect(int $id): void
517
        {
518
                fclose($this->sockets[$id]);
1 ✔
519
                unset($this->sockets[$id], $this->inProgress[$id], $this->buffers[$id], $this->finishing[$id]);
1 ✔
520
        }
1 ✔
521

522

523
        /**
524
         * Whether the run still waits for what the workers measured last: from one asked for it, and from one still
525
         * starting, which gets nothing to process but has its peak memory.
526
         */
527
        private function isFinishing(): bool
528
        {
529
                if ($this->profiler === null) {
1 ✔
530
                        return false;
1 ✔
531
                } elseif ($this->finishing !== []) {
1 ✔
532
                        return true;
1 ✔
533
                }
534

535
                // which process a connection belongs to is unknown, so a worker done with its work is waited for too, until it exits
536
                return $this->accepted < count($this->workers)
1 ✔
537
                        && array_any($this->workers, fn(array $worker) => proc_get_status($worker[0])['running']);
1 ✔
538
        }
539

540

541
        /** @return array{resource, string}  process, file with its output */
542
        private function spawn(string $address): array
543
        {
544
                $output = (string) tempnam(sys_get_temp_dir(), 'dresscode-worker-');
1 ✔
545
                $process = @proc_open( // @ is escalated to exception
1 ✔
546
                        [...$this->command, '--worker', $address],
1 ✔
547
                        [0 => ['pipe', 'r'], 1 => ['file', $output, 'a'], 2 => ['file', $output, 'a']],
1 ✔
548
                        $pipes,
549
                        $this->cwd,
1 ✔
550
                );
551
                if ($process === false) {
1 ✔
UNCOV
552
                        throw new \RuntimeException('Cannot start a worker process: `' . implode(' ', $this->command) . '`');
×
553
                }
554

555
                fclose($pipes[0]);
1 ✔
556
                $this->spawnedAt = microtime(as_float: true);
1 ✔
557
                return [$process, $output];
1 ✔
558
        }
559

560

561
        /**
562
         * A worker that exited with an error, one that has spent longer than the timeout on a file, a worker the run waits
563
         * for that has not connected within its timeout, or every worker gone while results are missing fails the run.
564
         */
565
        private function checkWorkers(bool $resultsMissing): void
566
        {
567
                $running = false;
1 ✔
568
                foreach ($this->workers as [$process]) {
1 ✔
569
                        $status = proc_get_status($process);
1 ✔
570
                        if ($status['running']) {
1 ✔
571
                                $running = true;
1 ✔
572
                        } elseif ($status['exitcode'] !== 0) {
1 ✔
573
                                throw new \RuntimeException('A worker ended ' . self::formatEnd($status) . '.' . $this->collectErrors());
1 ✔
574
                        }
575
                }
576

577
                foreach ($this->inProgress as [$path, $since]) {
1 ✔
578
                        if (microtime(as_float: true) - $since > $this->taskTimeout) {
1 ✔
579
                                throw new \RuntimeException("A worker has spent more than $this->taskTimeout s on `$path`; a rule has most likely looped." . $this->collectErrors());
1 ✔
580
                        }
581
                }
582

583
                if (
584
                        $this->sockets === []
1 ✔
585
                        && $this->accepted < count($this->workers)
1 ✔
586
                        && microtime(as_float: true) - $this->spawnedAt > $this->connectTimeout
1 ✔
587
                ) {
588
                        throw new \RuntimeException("A worker has not connected within $this->connectTimeout s." . $this->collectErrors());
1 ✔
589
                }
590

591
                if (!$running && $resultsMissing) {
1 ✔
UNCOV
592
                        throw new \RuntimeException('The workers ended before processing every file.' . $this->collectErrors());
×
593
                }
594
        }
1 ✔
595

596

597
        /**
598
         * How a worker that failed ended, given a moment to end, because its connection closes before its process is gone;
599
         * null where none has failed.
600
         */
601
        private function findWorkerFailure(): ?string
602
        {
603
                $deadline = microtime(as_float: true) + self::EndTimeout;
1 ✔
604
                do {
605
                        foreach ($this->workers as [$process]) {
1 ✔
606
                                $status = proc_get_status($process);
1 ✔
607
                                if (!$status['running'] && $status['exitcode'] !== 0) {
1 ✔
608
                                        return self::formatEnd($status);
1 ✔
609
                                }
610
                        }
611

612
                        usleep(10_000);
1 ✔
613
                } while (microtime(as_float: true) < $deadline);
1 ✔
614

UNCOV
615
                return null;
×
616
        }
617

618

619
        /**
620
         * How a process ended, for a message: its exit code, one of Windows in the form it is known by (`0xC0000005` for a
621
         * crash of PHP itself), or the signal that ended it.
622
         * @param  array{signaled: bool, termsig: int, exitcode: int}  $status
623
         */
624
        private static function formatEnd(array $status): string
625
        {
626
                $code = $status['exitcode'];
1 ✔
627
                return match (true) {
628
                        $status['signaled'] => "on signal {$status['termsig']}",
1 ✔
629
                        PHP_OS_FAMILY === 'Windows' && ($code < 0 || $code > 0xFFFF) => sprintf('with code 0x%08X', $code & 0xFFFFFFFF),
1 ✔
630
                        default => "with code $code",
1 ✔
631
                };
632
        }
633

634

635
        private function collectErrors(): string
636
        {
637
                $errors = '';
1 ✔
638
                foreach ($this->workers as [, $output]) {
1 ✔
639
                        $errors .= trim((string) @file_get_contents($output)); // @ file may have been deleted meanwhile
1 ✔
640
                }
641

642
                return $errors === '' ? '' : "\n$errors";
1 ✔
643
        }
644

645

646
        private function stop(): void
647
        {
648
                foreach ($this->workers as [$process, $output]) {
1 ✔
649
                        if (proc_get_status($process)['running']) {
1 ✔
650
                                proc_terminate($process);
1 ✔
651
                        }
652

653
                        proc_close($process);
1 ✔
654
                        @unlink($output); // @ file may have been deleted meanwhile
1 ✔
655
                }
656

657
                $this->workers = $this->sockets = $this->inProgress = $this->buffers = [];
1 ✔
658
                $this->accepted = $this->pending = 0;
1 ✔
659
                $this->read = null;
1 ✔
660
        }
1 ✔
661
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc