m2geval / php /pokio_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
25b3e24 verified
{"repo_name": "pokio", "file_name": "/pokio/src/Environment.php", "inference_info": {"prefix_code": "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class Environment\n{\n /**\n * Cached value for maxProcesses to avoid redundant computations.\n */\n private static ?int $maxProcesses = null;\n\n /**\n * The number of processes that can be run in parallel.\n */\n ", "suffix_code": "\n\n /**\n * Whether the current environment supports forking.\n */\n public static function supportsFork(): bool\n {\n return extension_loaded('pcntl')\n && extension_loaded('posix')\n && class_exists('FFI');\n }\n\n /**\n * Get the total memory of the system in bytes.\n *\n * @param string $os (default: PHP_OS_FAMILY) The operating system family.\n * @param string|null $memInfo (default: null) The memory information string (used for testing on linux).\n */\n private static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n {\n if ($os === 'Linux') {\n $memInfo = $memInfo ?? @file_get_contents('/proc/meminfo');\n\n if (! $memInfo || ! preg_match('/MemTotal:\\s+(\\d+) kB/', $memInfo, $matches)) {\n throw new RuntimeException('Unable to determine total memory on Linux');\n }\n\n return (int) $matches[1] * 1024;\n }\n\n if ($os === 'Darwin') {\n return (int) shell_exec('sysctl -n hw.memsize');\n }\n\n throw new RuntimeException(\"Unsupported OS: $os\");\n }\n}\n", "middle_code": "public static function maxProcesses(): int\n {\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n $cpuCores = (int) shell_exec('getconf _NPROCESSORS_ONLN');\n if ($cpuCores <= 0) {\n $cpuCores = 1;\n }\n $ioFactor = (int) getenv('FORK_IO_FACTOR') ?: 3;\n $maxByCpu = $cpuCores * $ioFactor;\n $totalMemory = self::getTotalMemory(PHP_OS_FAMILY);\n $perProcessMemory = (int) getenv('FORK_MEM_PER_PROC') ?: 100 * 1024 * 1024; \n $maxByMemory = intdiv($totalMemory, $perProcessMemory);\n $maxProcesses = min($maxByCpu, $maxByMemory);\n self::$maxProcesses = max(1, $maxProcesses);\n return self::$maxProcesses;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/pokio/src/Runtime/Fork/ForkRuntime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Kernel;\nuse Pokio\\Promise;\nuse Pokio\\UnwaitedFutureManager;\nuse RuntimeException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ForkRuntime implements Runtime\n{\n /**\n * The PIDs of the currently running processes.\n *\n * @var array<int, true>\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n\n // Adding a little sleep to prevent busy-waiting and CPU\n // starvation, allowing other processes to run in the\n // meantime. -------------------------------------\n\n usleep(1000);\n }\n\n $ipc = IPC::create();\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n\n // @codeCoverageIgnoreStart\n try {\n $result = $callback();\n\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n\n $data = serialize($result);\n\n $ipc->put($data);\n\n exit(0);\n // @codeCoverageIgnoreEnd\n }\n\n self::$processes[$pid] = true;\n\n /** @var Future<TResult> $future */\n // @phpstan-ignore-next-line\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n\n return $future;\n }\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse FFI;\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal readonly class IPC\n{\n private const string FILE_PREFIX = '/tmp/ipc_mem_';\n\n // POSIX constants\n private const int O_RDWR = 0x0002;\n\n private const int O_CREAT = 0x0040;\n\n private const int PROT_READ = 0x1;\n\n private const int PROT_WRITE = 0x2;\n\n private const int MAP_SHARED = 0x01;\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n private function __construct(\n private string $path,\n ) {\n //\n }\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n public static function create(): self\n {\n $id = bin2hex(random_bytes(8));\n $path = self::FILE_PREFIX.$id;\n touch($path);\n\n return new self($path);\n }\n\n /**\n * Writes data to the memory block.\n */\n public function put(string $data): void\n {\n // @codeCoverageIgnoreStart\n $ffi = self::libc();\n $length = mb_strlen($data, '8bit');\n\n $fd = $ffi->open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Kernel.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse LogicException;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Runtime\\Fork\\ForkRuntime;\nuse Pokio\\Runtime\\Sync\\SyncRuntime;\n\n/**\n * @internal\n */\nfinal class Kernel\n{\n /**\n * The kernel's singleton.\n */\n private static ?self $instance = null;\n\n /**\n * The sync runtime instance.\n */\n private Runtime $syncRuntime;\n\n /**\n * The async runtime instance.\n */\n private Runtime $asyncRuntime;\n\n /**\n * The process ID of the orchestrator.\n */\n private function __construct(\n private readonly int $orchestratorPid,\n ) {\n //\n }\n\n /**\n * The process ID of the orchestrator.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self((int) getmypid());\n }\n\n /**\n * Specifies that pokio should use the fork as the async runtime.\n */\n public function useFork(): void\n {\n if (Environment::supportsFork() === false) {\n throw new LogicException('Fork is not supported on this environment.');\n }\n\n $this->asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Support;\n\nuse Closure;\nuse ReflectionFunction;\nuse ReflectionNamedType;\nuse ReflectionUnionType;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal readonly class Reflection\n{\n /**\n * Checks if the given callback is catchable.\n *\n * @param Closure(Throwable): mixed $callback\n */\n public static function isCatchable(Closure $callback, Throwable $throwable): bool\n {\n $reflection = new ReflectionFunction($callback);\n $parameters = $reflection->getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array<int, ReflectionNamedType> $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Pokio\\Contracts\\Future;\n\n/**\n * @internal\n */\nfinal class UnwaitedFutureManager\n{\n /**\n * Holds the singleton instance of the unwaited future manager.\n */\n private static ?self $instance = null;\n\n /**\n * Creates a new future manager instance.\n *\n * @param array<string, Future<mixed>> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future<mixed> $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future<mixed> $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Promise.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\PromiseAlreadyStarted;\nuse Pokio\\Runtime\\Sync\\SyncFuture;\nuse Pokio\\Support\\Reflection;\nuse Throwable;\n\n/**\n * @template TReturn\n *\n * @internal\n */\nfinal class Promise\n{\n /**\n * The process ID when the promise was created.\n */\n private readonly string $pid;\n\n /**\n * The result of the asynchronous operation.\n *\n * @var Future<TReturn>|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self<TThenReturn>\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self<TReturn|TCatchReturn>\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self<TReturn>\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse ReflectionClass;\nuse ReflectionException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ThrowableCapsule\n{\n /**\n * Creates a new throwable capsule instance.\n */\n public function __construct(public Throwable $throwable)\n {\n //\n }\n\n /**\n * Serializes the throwable capsule.\n *\n * @return array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/types/Async.php", "<?php\n\ndeclare(strict_types=1);\n\nuse function PHPStan\\Testing\\assertType;\n\n$promise = async(fn () => 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array<int, string>', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\n\n/**\n * Represents the result of a forked process.\n *\n * @template TResult\n *\n * @implements Future<TResult>\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Functions.php", "<?php\n\ndeclare(strict_types=1);\n\nuse Pokio\\Kernel;\nuse Pokio\\Pokio;\nuse Pokio\\Promise;\n\nif (! function_exists('async')) {\n /**\n * Runs a callback asynchronously and returns a promise.\n *\n * @template TReturn\n *\n * @param Closure(): TReturn $callback\n * @return Promise<TReturn>\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array<int, Promise<TReturn>>|Promise<TReturn> $promises\n * @return ($promises is array ? array<int, TReturn> : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\nuse Pokio\\Promise;\n\n/**\n * @internal\n *\n * @template TResult\n *\n * @implements Future<TResult>\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\n\n/**\n * @internal\n */\nfinal readonly class SyncRuntime implements Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/src/Pokio.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\n/**\n * @internal\n */\nfinal readonly class Pokio\n{\n /**\n * Specifies that Pokio should use the fork runtime for asynchronous operations.\n */\n public function useFork(): void\n {\n Kernel::instance()->useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Contracts/Runtime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\nuse Closure;\n\ninterface Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Exceptions/PromiseAlreadyStarted.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class PromiseAlreadyStarted extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been started.');\n }\n}\n"], ["/pokio/src/Exceptions/FutureAlreadyAwaited.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class FutureAlreadyAwaited extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been resolved.');\n }\n}\n"], ["/pokio/src/Contracts/Future.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\n/**\n * @internal\n *\n * @template TResult\n */\ninterface Future\n{\n /**\n * The result of the asynchronous operation.\n *\n * @return TResult\n */\n public function await(): mixed;\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool;\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:28:12", "created_task_model": "DeepSeek-R1", "function_skeleton": "public static function maxProcesses () : int {}", "code_description": "This code segment functions to: Calculate the maximum allowable parallel processes based on available system resources and configurable parameters, utilizing CPU core count and memory constraints with environment-variable customization of scaling factors."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\npublic static function maxProcesses(): int\n{\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n\n try {\n $os = PHP_OS_FAMILY;\n $cpuCores = 1;\n\n if ($os === 'Linux') {\n $cpuinfo = @file_get_contents('/proc/cpuinfo');\n if ($cpuinfo !== false) {\n preg_match_all('/^processor\\s*:\\s*\\d+/m', $cpuinfo, $matches);\n $cpuCores = count($matches[0]) ?: 1;\n } else {\n $nproc = shell_exec('nproc');\n $cpuCores = $nproc !== null ? (int)$nproc : 1;\n }\n } elseif ($os === 'Darwin') {\n $ncpu = shell_exec('sysctl -n hw.ncpu');\n $cpuCores = $ncpu !== null ? (int)$ncpu : 1;\n }\n\n $totalMemory = self::getTotalMemory();\n $memoryPerProcess = 100 * 1024 * 1024; // 100MB per process\n $memoryBased = (int) ($totalMemory / $memoryPerProcess);\n\n self::$maxProcesses = max(1, min($cpuCores, $memoryBased));\n } catch (RuntimeException) {\n // Fallback to 4 processes if memory detection fails\n self::$maxProcesses = 4;\n }\n\n return self::$maxProcesses;\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-29-03"}, "editdistance_info": {"edit_distance": 31.3725, "calculate_time": "2025-08-20 21:29:03", "true_code_clean": "public static function maxProcesses(): int\n {\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n $cpuCores = (int) shell_exec('getconf _NPROCESSORS_ONLN');\n if ($cpuCores <= 0) {\n $cpuCores = 1;\n }\n $ioFactor = (int) getenv('FORK_IO_FACTOR') ?: 3;\n $maxByCpu = $cpuCores * $ioFactor;\n $totalMemory = self::getTotalMemory(PHP_OS_FAMILY);\n $perProcessMemory = (int) getenv('FORK_MEM_PER_PROC') ?: 100 * 1024 * 1024; \n $maxByMemory = intdiv($totalMemory, $perProcessMemory);\n $maxProcesses = min($maxByCpu, $maxByMemory);\n self::$maxProcesses = max(1, $maxProcesses);\n return self::$maxProcesses;\n }", "predict_code_clean": "public static function maxProcesses(): int\n{\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n try {\n $os = PHP_OS_FAMILY;\n $cpuCores = 1;\n if ($os === 'Linux') {\n $cpuinfo = @file_get_contents('/proc/cpuinfo');\n if ($cpuinfo !== false) {\n preg_match_all('/^processor\\s*:\\s*\\d+/m', $cpuinfo, $matches);\n $cpuCores = count($matches[0]) ?: 1;\n } else {\n $nproc = shell_exec('nproc');\n $cpuCores = $nproc !== null ? (int)$nproc : 1;\n }\n } elseif ($os === 'Darwin') {\n $ncpu = shell_exec('sysctl -n hw.ncpu');\n $cpuCores = $ncpu !== null ? (int)$ncpu : 1;\n }\n $totalMemory = self::getTotalMemory();\n $memoryPerProcess = 100 * 1024 * 1024; \n $memoryBased = (int) ($totalMemory / $memoryPerProcess);\n self::$maxProcesses = max(1, min($cpuCores, $memoryBased));\n } catch (RuntimeException) {\n self::$maxProcesses = 4;\n }\n return self::$maxProcesses;\n}"}}
{"repo_name": "pokio", "file_name": "/pokio/src/Environment.php", "inference_info": {"prefix_code": "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class Environment\n{\n /**\n * Cached value for maxProcesses to avoid redundant computations.\n */\n private static ?int $maxProcesses = null;\n\n /**\n * The number of processes that can be run in parallel.\n */\n public static function maxProcesses(): int\n {\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n\n $cpuCores = (int) shell_exec('getconf _NPROCESSORS_ONLN');\n\n // @codeCoverageIgnoreStart\n if ($cpuCores <= 0) {\n $cpuCores = 1;\n }\n // @codeCoverageIgnoreEnd\n\n $ioFactor = (int) getenv('FORK_IO_FACTOR') ?: 3;\n $maxByCpu = $cpuCores * $ioFactor;\n\n $totalMemory = self::getTotalMemory(PHP_OS_FAMILY);\n\n $perProcessMemory = (int) getenv('FORK_MEM_PER_PROC') ?: 100 * 1024 * 1024; // 100MB\n $maxByMemory = intdiv($totalMemory, $perProcessMemory);\n\n $maxProcesses = min($maxByCpu, $maxByMemory);\n\n self::$maxProcesses = max(1, $maxProcesses);\n\n return self::$maxProcesses;\n }\n\n /**\n * Whether the current environment supports forking.\n */\n public static function supportsFork(): bool\n {\n return extension_loaded('pcntl')\n && extension_loaded('posix')\n && class_exists('FFI');\n }\n\n /**\n * Get the total memory of the system in bytes.\n *\n * @param string $os (default: PHP_OS_FAMILY) The operating system family.\n * @param string|null $memInfo (default: null) The memory information string (used for testing on linux).\n */\n ", "suffix_code": "\n}\n", "middle_code": "private static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n {\n if ($os === 'Linux') {\n $memInfo = $memInfo ?? @file_get_contents('/proc/meminfo');\n if (! $memInfo || ! preg_match('/MemTotal:\\s+(\\d+) kB/', $memInfo, $matches)) {\n throw new RuntimeException('Unable to determine total memory on Linux');\n }\n return (int) $matches[1] * 1024;\n }\n if ($os === 'Darwin') {\n return (int) shell_exec('sysctl -n hw.memsize');\n }\n throw new RuntimeException(\"Unsupported OS: $os\");\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/pokio/src/Runtime/Fork/ForkRuntime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Kernel;\nuse Pokio\\Promise;\nuse Pokio\\UnwaitedFutureManager;\nuse RuntimeException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ForkRuntime implements Runtime\n{\n /**\n * The PIDs of the currently running processes.\n *\n * @var array<int, true>\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n\n // Adding a little sleep to prevent busy-waiting and CPU\n // starvation, allowing other processes to run in the\n // meantime. -------------------------------------\n\n usleep(1000);\n }\n\n $ipc = IPC::create();\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n\n // @codeCoverageIgnoreStart\n try {\n $result = $callback();\n\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n\n $data = serialize($result);\n\n $ipc->put($data);\n\n exit(0);\n // @codeCoverageIgnoreEnd\n }\n\n self::$processes[$pid] = true;\n\n /** @var Future<TResult> $future */\n // @phpstan-ignore-next-line\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n\n return $future;\n }\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse FFI;\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal readonly class IPC\n{\n private const string FILE_PREFIX = '/tmp/ipc_mem_';\n\n // POSIX constants\n private const int O_RDWR = 0x0002;\n\n private const int O_CREAT = 0x0040;\n\n private const int PROT_READ = 0x1;\n\n private const int PROT_WRITE = 0x2;\n\n private const int MAP_SHARED = 0x01;\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n private function __construct(\n private string $path,\n ) {\n //\n }\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n public static function create(): self\n {\n $id = bin2hex(random_bytes(8));\n $path = self::FILE_PREFIX.$id;\n touch($path);\n\n return new self($path);\n }\n\n /**\n * Writes data to the memory block.\n */\n public function put(string $data): void\n {\n // @codeCoverageIgnoreStart\n $ffi = self::libc();\n $length = mb_strlen($data, '8bit');\n\n $fd = $ffi->open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Kernel.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse LogicException;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Runtime\\Fork\\ForkRuntime;\nuse Pokio\\Runtime\\Sync\\SyncRuntime;\n\n/**\n * @internal\n */\nfinal class Kernel\n{\n /**\n * The kernel's singleton.\n */\n private static ?self $instance = null;\n\n /**\n * The sync runtime instance.\n */\n private Runtime $syncRuntime;\n\n /**\n * The async runtime instance.\n */\n private Runtime $asyncRuntime;\n\n /**\n * The process ID of the orchestrator.\n */\n private function __construct(\n private readonly int $orchestratorPid,\n ) {\n //\n }\n\n /**\n * The process ID of the orchestrator.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self((int) getmypid());\n }\n\n /**\n * Specifies that pokio should use the fork as the async runtime.\n */\n public function useFork(): void\n {\n if (Environment::supportsFork() === false) {\n throw new LogicException('Fork is not supported on this environment.');\n }\n\n $this->asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse ReflectionClass;\nuse ReflectionException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ThrowableCapsule\n{\n /**\n * Creates a new throwable capsule instance.\n */\n public function __construct(public Throwable $throwable)\n {\n //\n }\n\n /**\n * Serializes the throwable capsule.\n *\n * @return array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Support;\n\nuse Closure;\nuse ReflectionFunction;\nuse ReflectionNamedType;\nuse ReflectionUnionType;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal readonly class Reflection\n{\n /**\n * Checks if the given callback is catchable.\n *\n * @param Closure(Throwable): mixed $callback\n */\n public static function isCatchable(Closure $callback, Throwable $throwable): bool\n {\n $reflection = new ReflectionFunction($callback);\n $parameters = $reflection->getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array<int, ReflectionNamedType> $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Pokio\\Contracts\\Future;\n\n/**\n * @internal\n */\nfinal class UnwaitedFutureManager\n{\n /**\n * Holds the singleton instance of the unwaited future manager.\n */\n private static ?self $instance = null;\n\n /**\n * Creates a new future manager instance.\n *\n * @param array<string, Future<mixed>> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future<mixed> $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future<mixed> $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Promise.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\PromiseAlreadyStarted;\nuse Pokio\\Runtime\\Sync\\SyncFuture;\nuse Pokio\\Support\\Reflection;\nuse Throwable;\n\n/**\n * @template TReturn\n *\n * @internal\n */\nfinal class Promise\n{\n /**\n * The process ID when the promise was created.\n */\n private readonly string $pid;\n\n /**\n * The result of the asynchronous operation.\n *\n * @var Future<TReturn>|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self<TThenReturn>\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self<TReturn|TCatchReturn>\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self<TReturn>\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/types/Async.php", "<?php\n\ndeclare(strict_types=1);\n\nuse function PHPStan\\Testing\\assertType;\n\n$promise = async(fn () => 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array<int, string>', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\n\n/**\n * Represents the result of a forked process.\n *\n * @template TResult\n *\n * @implements Future<TResult>\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Functions.php", "<?php\n\ndeclare(strict_types=1);\n\nuse Pokio\\Kernel;\nuse Pokio\\Pokio;\nuse Pokio\\Promise;\n\nif (! function_exists('async')) {\n /**\n * Runs a callback asynchronously and returns a promise.\n *\n * @template TReturn\n *\n * @param Closure(): TReturn $callback\n * @return Promise<TReturn>\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array<int, Promise<TReturn>>|Promise<TReturn> $promises\n * @return ($promises is array ? array<int, TReturn> : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\nuse Pokio\\Promise;\n\n/**\n * @internal\n *\n * @template TResult\n *\n * @implements Future<TResult>\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\n\n/**\n * @internal\n */\nfinal readonly class SyncRuntime implements Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/src/Pokio.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\n/**\n * @internal\n */\nfinal readonly class Pokio\n{\n /**\n * Specifies that Pokio should use the fork runtime for asynchronous operations.\n */\n public function useFork(): void\n {\n Kernel::instance()->useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Contracts/Runtime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\nuse Closure;\n\ninterface Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Exceptions/PromiseAlreadyStarted.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class PromiseAlreadyStarted extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been started.');\n }\n}\n"], ["/pokio/src/Exceptions/FutureAlreadyAwaited.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class FutureAlreadyAwaited extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been resolved.');\n }\n}\n"], ["/pokio/src/Contracts/Future.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\n/**\n * @internal\n *\n * @template TResult\n */\ninterface Future\n{\n /**\n * The result of the asynchronous operation.\n *\n * @return TResult\n */\n public function await(): mixed;\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool;\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:28:12", "created_task_model": "DeepSeek-R1", "function_skeleton": "private static function getTotalMemory (string $os = PHP_OS_FAMILY, ?string $memInfo = null) : int {}", "code_description": "This code segment functions to: Retrieve the total system memory capacity through operating system-specific interfaces, normalize the extracted values into a consistent byte-based format, and enforce compatibility checks for supported platforms while handling measurement unit conversions."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\nprivate static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n{\n switch ($os) {\n case 'Linux':\n $content = $memInfo ?? @file_get_contents('/proc/meminfo');\n if ($content === false || !preg_match('/MemTotal:\\s+(\\d+)\\s+kB/', $content, $matches)) {\n return 0;\n }\n return (int)$matches[1] * 1024;\n case 'Darwin':\n $output = shell_exec('sysctl -n hw.memsize');\n return $output !== null ? (int)$output : 0;\n case 'BSD':\n $output = shell_exec('sysctl -n hw.physmem');\n return $output !== null ? (int)$output : 0;\n case 'Windows':\n $output = shell_exec('wmic memorychip get capacity');\n if ($output === null) {\n return 0;\n }\n $total = 0;\n $lines = explode(\"\\n\", trim($output));\n array_shift($lines);\n foreach ($lines as $line) {\n $capacity = trim($line);\n if (is_numeric($capacity)) {\n $total += (int)$capacity;\n }\n }\n return $total;\n default:\n return 0;\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 21-29-08"}, "editdistance_info": {"edit_distance": 29.5533, "calculate_time": "2025-08-20 21:29:08", "true_code_clean": "private static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n {\n if ($os === 'Linux') {\n $memInfo = $memInfo ?? @file_get_contents('/proc/meminfo');\n if (! $memInfo || ! preg_match('/MemTotal:\\s+(\\d+) kB/', $memInfo, $matches)) {\n throw new RuntimeException('Unable to determine total memory on Linux');\n }\n return (int) $matches[1] * 1024;\n }\n if ($os === 'Darwin') {\n return (int) shell_exec('sysctl -n hw.memsize');\n }\n throw new RuntimeException(\"Unsupported OS: $os\");\n }", "predict_code_clean": "private static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n{\n switch ($os) {\n case 'Linux':\n $content = $memInfo ?? @file_get_contents('/proc/meminfo');\n if ($content === false || !preg_match('/MemTotal:\\s+(\\d+)\\s+kB/', $content, $matches)) {\n return 0;\n }\n return (int)$matches[1] * 1024;\n case 'Darwin':\n $output = shell_exec('sysctl -n hw.memsize');\n return $output !== null ? (int)$output : 0;\n case 'BSD':\n $output = shell_exec('sysctl -n hw.physmem');\n return $output !== null ? (int)$output : 0;\n case 'Windows':\n $output = shell_exec('wmic memorychip get capacity');\n if ($output === null) {\n return 0;\n }\n $total = 0;\n $lines = explode(\"\\n\", trim($output));\n array_shift($lines);\n foreach ($lines as $line) {\n $capacity = trim($line);\n if (is_numeric($capacity)) {\n $total += (int)$capacity;\n }\n }\n return $total;\n default:\n return 0;\n }\n}"}}
{"repo_name": "pokio", "file_name": "/pokio/src/Runtime/Fork/ForkRuntime.php", "inference_info": {"prefix_code": "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Kernel;\nuse Pokio\\Promise;\nuse Pokio\\UnwaitedFutureManager;\nuse RuntimeException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ForkRuntime implements Runtime\n{\n /**\n * The PIDs of the currently running processes.\n *\n * @var array<int, true>\n */\n private static array $processes = [];\n\n /**\n * Creates a new fork runtime instance.\n */\n public function __construct(private int $maxProcesses)\n {\n //\n }\n\n /**\n * Cleans up any remaining processes on destruction, if any.\n */\n public function __destruct()\n {\n if (Kernel::instance()->isOrchestrator()) {\n foreach (array_keys(self::$processes) as $pid) {\n pcntl_waitpid($pid, $status);\n }\n }\n }\n\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n ", "suffix_code": "\n\n /**\n * Waits for a process to finish and removes it from the list of processes.\n */\n private function waitForProcess(): void\n {\n $pid = pcntl_wait($status, WNOHANG);\n\n if ($pid > 0) {\n unset(self::$processes[$pid]);\n }\n }\n}\n", "middle_code": "public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n usleep(1000);\n }\n $ipc = IPC::create();\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n try {\n $result = $callback();\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n $data = serialize($result);\n $ipc->put($data);\n exit(0);\n }\n self::$processes[$pid] = true;\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n return $future;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "php", "sub_task_type": null}, "context_code": [["/pokio/src/Promise.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\PromiseAlreadyStarted;\nuse Pokio\\Runtime\\Sync\\SyncFuture;\nuse Pokio\\Support\\Reflection;\nuse Throwable;\n\n/**\n * @template TReturn\n *\n * @internal\n */\nfinal class Promise\n{\n /**\n * The process ID when the promise was created.\n */\n private readonly string $pid;\n\n /**\n * The result of the asynchronous operation.\n *\n * @var Future<TReturn>|null\n */\n private ?Future $future = null;\n\n /**\n * Creates a new promise instance.\n *\n * @param Closure(): TReturn $callback\n */\n public function __construct(\n private readonly Closure $callback\n ) {\n $this->pid = (string) getmypid();\n }\n\n /**\n * Resolves the promise when the object is destroyed.\n */\n public function __destruct()\n {\n if ((string) getmypid() !== $this->pid) {\n return;\n }\n\n $this->defer();\n\n assert($this->future instanceof Future);\n\n if ($this->future->awaited()) {\n return;\n }\n\n UnwaitedFutureManager::instance()->schedule($this->future);\n }\n\n /**\n * Invokes the promise, defering the callback to be executed immediately.\n *\n * @return TReturn\n */\n public function __invoke(): mixed\n {\n return $this->resolve();\n }\n\n /**\n * Defer the given callback to be executed asynchronously.\n */\n public function defer(): void\n {\n $this->future ??= Kernel::instance()->runtime()->defer($this->callback);\n }\n\n /**\n * Resolves the promise.\n *\n * @return TReturn\n */\n public function resolve(): mixed\n {\n $this->defer();\n\n assert($this->future instanceof Future);\n\n return $this->future->await();\n }\n\n /**\n * Adds a then callback to the promise.\n *\n * @template TThenReturn\n *\n * @param Closure(TReturn): TThenReturn $then\n * @return self<TThenReturn>\n */\n public function then(Closure $then): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n // @phpstan-ignore-next-line\n return new self(function () use ($callback, $then) {\n $result = $callback();\n\n if ($result instanceof Promise) {\n // @phpstan-ignore-next-line\n return $result->then($then);\n }\n\n return $then($result);\n });\n }\n\n /**\n * Adds a catch callback to the promise.\n *\n * @template TCatchReturn\n *\n * @param Closure(Throwable): TCatchReturn $catch\n * @return self<TReturn|TCatchReturn>\n */\n public function catch(Closure $catch): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $catch) {\n try {\n return $callback();\n } catch (Throwable $throwable) {\n if (! Reflection::isCatchable($catch, $throwable)) {\n throw $throwable;\n }\n\n return ($catch)($throwable);\n }\n });\n }\n\n /**\n * Adds a finally callback to the promise.\n *\n * @param Closure(): void $finally\n * @return self<TReturn>\n */\n public function finally(Closure $finally): self\n {\n $this->ignore();\n\n $callback = $this->callback;\n\n return new self(function () use ($callback, $finally) {\n try {\n return $callback();\n } finally {\n ($finally)();\n }\n });\n }\n\n /**\n * Ignores the promise, effectively discarding the result.\n */\n private function ignore(): void\n {\n if ($this->future instanceof Future) {\n throw new PromiseAlreadyStarted();\n }\n\n // @phpstan-ignore-next-line\n $this->future = new SyncFuture(static fn () => null);\n }\n}\n"], ["/pokio/src/Runtime/Fork/ForkFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\n\n/**\n * Represents the result of a forked process.\n *\n * @template TResult\n *\n * @implements Future<TResult>\n *\n * @internal\n */\nfinal class ForkFuture implements Future\n{\n /**\n * Whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new fork result instance.\n */\n public function __construct(\n private readonly int $pid,\n private readonly IPC $memory,\n private readonly Closure $onWait,\n ) {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult|null\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n pcntl_waitpid($this->pid, $status);\n\n if (! file_exists($this->memory->path()) || filesize($this->memory->path()) === 0) {\n return null;\n }\n\n $this->onWait->__invoke($this->pid);\n\n /** @var TResult $result */\n $result = unserialize($this->memory->pop());\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/UnwaitedFutureManager.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse Pokio\\Contracts\\Future;\n\n/**\n * @internal\n */\nfinal class UnwaitedFutureManager\n{\n /**\n * Holds the singleton instance of the unwaited future manager.\n */\n private static ?self $instance = null;\n\n /**\n * Creates a new future manager instance.\n *\n * @param array<string, Future<mixed>> $queue\n */\n private function __construct(\n private array $queue,\n ) {\n //\n }\n\n /**\n * Called when the future manager is destructed.\n */\n public function __destruct()\n {\n $this->run();\n }\n\n /**\n * Fetches the singleton instance of the future manager.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self(\n [],\n );\n }\n\n /**\n * Flushes the execution queue, removing all scheduled futures.\n */\n public function flush(): void\n {\n $this->queue = [];\n }\n\n /**\n * Schedules a future for execution.\n *\n * @param Future<mixed> $future\n */\n public function schedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n $this->queue[$hash] = $future;\n }\n\n /**\n * Unschedules a future, removing it from the execution queue.\n *\n * @param Future<mixed> $future\n */\n public function unschedule(Future $future): void\n {\n $hash = spl_object_hash($future);\n\n if (isset($this->queue[$hash])) {\n unset($this->queue[$hash]);\n }\n }\n\n /**\n * Runs all scheduled futures, resolving them in the order they were added.\n */\n public function run(): void\n {\n $queue = $this->queue;\n\n foreach ($queue as $future) {\n $future->await();\n\n $this->unschedule($future);\n }\n\n if (count($this->queue) > 0) {\n $this->run();\n }\n }\n}\n"], ["/pokio/src/Environment.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class Environment\n{\n /**\n * Cached value for maxProcesses to avoid redundant computations.\n */\n private static ?int $maxProcesses = null;\n\n /**\n * The number of processes that can be run in parallel.\n */\n public static function maxProcesses(): int\n {\n if (self::$maxProcesses !== null) {\n return self::$maxProcesses;\n }\n\n $cpuCores = (int) shell_exec('getconf _NPROCESSORS_ONLN');\n\n // @codeCoverageIgnoreStart\n if ($cpuCores <= 0) {\n $cpuCores = 1;\n }\n // @codeCoverageIgnoreEnd\n\n $ioFactor = (int) getenv('FORK_IO_FACTOR') ?: 3;\n $maxByCpu = $cpuCores * $ioFactor;\n\n $totalMemory = self::getTotalMemory(PHP_OS_FAMILY);\n\n $perProcessMemory = (int) getenv('FORK_MEM_PER_PROC') ?: 100 * 1024 * 1024; // 100MB\n $maxByMemory = intdiv($totalMemory, $perProcessMemory);\n\n $maxProcesses = min($maxByCpu, $maxByMemory);\n\n self::$maxProcesses = max(1, $maxProcesses);\n\n return self::$maxProcesses;\n }\n\n /**\n * Whether the current environment supports forking.\n */\n public static function supportsFork(): bool\n {\n return extension_loaded('pcntl')\n && extension_loaded('posix')\n && class_exists('FFI');\n }\n\n /**\n * Get the total memory of the system in bytes.\n *\n * @param string $os (default: PHP_OS_FAMILY) The operating system family.\n * @param string|null $memInfo (default: null) The memory information string (used for testing on linux).\n */\n private static function getTotalMemory(string $os = PHP_OS_FAMILY, ?string $memInfo = null): int\n {\n if ($os === 'Linux') {\n $memInfo = $memInfo ?? @file_get_contents('/proc/meminfo');\n\n if (! $memInfo || ! preg_match('/MemTotal:\\s+(\\d+) kB/', $memInfo, $matches)) {\n throw new RuntimeException('Unable to determine total memory on Linux');\n }\n\n return (int) $matches[1] * 1024;\n }\n\n if ($os === 'Darwin') {\n return (int) shell_exec('sysctl -n hw.memsize');\n }\n\n throw new RuntimeException(\"Unsupported OS: $os\");\n }\n}\n"], ["/pokio/src/Kernel.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\nuse LogicException;\nuse Pokio\\Contracts\\Runtime;\nuse Pokio\\Runtime\\Fork\\ForkRuntime;\nuse Pokio\\Runtime\\Sync\\SyncRuntime;\n\n/**\n * @internal\n */\nfinal class Kernel\n{\n /**\n * The kernel's singleton.\n */\n private static ?self $instance = null;\n\n /**\n * The sync runtime instance.\n */\n private Runtime $syncRuntime;\n\n /**\n * The async runtime instance.\n */\n private Runtime $asyncRuntime;\n\n /**\n * The process ID of the orchestrator.\n */\n private function __construct(\n private readonly int $orchestratorPid,\n ) {\n //\n }\n\n /**\n * The process ID of the orchestrator.\n */\n public static function instance(): self\n {\n return self::$instance ??= new self((int) getmypid());\n }\n\n /**\n * Specifies that pokio should use the fork as the async runtime.\n */\n public function useFork(): void\n {\n if (Environment::supportsFork() === false) {\n throw new LogicException('Fork is not supported on this environment.');\n }\n\n $this->asyncRuntime = new ForkRuntime(Environment::maxProcesses());\n }\n\n /**\n * Specifies that pokio should use the sync runtime.\n */\n public function useSync(): void\n {\n $this->asyncRuntime = $this->syncRuntime ??= new SyncRuntime();\n }\n\n /**\n * Resolves pokio's current runtime.\n */\n public function runtime(): Runtime\n {\n if (self::instance()->isOrchestrator() === false) {\n return $this->syncRuntime ??= new SyncRuntime();\n }\n\n return $this->asyncRuntime ??= (function () {\n if (Environment::supportsFork()) {\n return new ForkRuntime(Environment::maxProcesses());\n }\n\n return $this->syncRuntime ??= new SyncRuntime();\n })();\n }\n\n /**\n * Whether the current process is the orchestrator.\n */\n public function isOrchestrator(): bool\n {\n return $this->orchestratorPid === getmypid();\n }\n}\n"], ["/pokio/src/Runtime/Fork/IPC.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse FFI;\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal readonly class IPC\n{\n private const string FILE_PREFIX = '/tmp/ipc_mem_';\n\n // POSIX constants\n private const int O_RDWR = 0x0002;\n\n private const int O_CREAT = 0x0040;\n\n private const int PROT_READ = 0x1;\n\n private const int PROT_WRITE = 0x2;\n\n private const int MAP_SHARED = 0x01;\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n private function __construct(\n private string $path,\n ) {\n //\n }\n\n /**\n * Creates a new IPC memory block using a memory-mapped file.\n */\n public static function create(): self\n {\n $id = bin2hex(random_bytes(8));\n $path = self::FILE_PREFIX.$id;\n touch($path);\n\n return new self($path);\n }\n\n /**\n * Writes data to the memory block.\n */\n public function put(string $data): void\n {\n // @codeCoverageIgnoreStart\n $ffi = self::libc();\n $length = mb_strlen($data, '8bit');\n\n $fd = $ffi->open($this->path, self::O_RDWR | self::O_CREAT, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for writing');\n }\n\n $ffi->ftruncate($fd, $length);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ | self::PROT_WRITE, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to write');\n }\n\n $ffi->memcpy($ptr, $data, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n // @codeCoverageIgnoreEnd\n }\n\n /**\n * Reads and clears data from the memory block.\n */\n public function pop(): string\n {\n $ffi = self::libc();\n\n $fd = $ffi->open($this->path, self::O_RDWR, 0600);\n if ($fd < 0) {\n throw new RuntimeException('Failed to open file for reading');\n }\n\n $length = filesize($this->path);\n\n $ptr = $ffi->mmap(null, $length, self::PROT_READ, self::MAP_SHARED, $fd, 0);\n $intptr = $ffi->cast('intptr_t', $ptr);\n\n // @phpstan-ignore-next-line\n if ($intptr === null || $intptr->cdata === -1) {\n throw new RuntimeException('mmap failed to read');\n }\n\n $data = FFI::string($ptr, $length);\n $ffi->munmap($ptr, $length);\n $ffi->close($fd);\n unlink($this->path);\n\n return $data;\n }\n\n /**\n * Returns the path to the IPC memory block.\n */\n public function path(): string\n {\n return $this->path;\n }\n\n /**\n * Loads libc and defines function bindings.\n */\n private static function libc(): FFI\n {\n static $ffi = null;\n\n if ($ffi === null) {\n $lib = PHP_OS_FAMILY === 'Darwin' ? 'libc.dylib' : 'libc.so.6';\n\n $ffi = FFI::cdef('\n void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset);\n int munmap(void* addr, size_t length);\n int open(const char *pathname, int flags, int mode);\n int close(int fd);\n int ftruncate(int fd, off_t length);\n void* memcpy(void* dest, const void* src, size_t n);\n ', $lib);\n }\n\n return $ffi; // @phpstan-ignore-line\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncFuture.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Exceptions\\FutureAlreadyAwaited;\nuse Pokio\\Promise;\n\n/**\n * @internal\n *\n * @template TResult\n *\n * @implements Future<TResult>\n */\nfinal class SyncFuture implements Future\n{\n /**\n * Indicates whether the result has been awaited.\n */\n private bool $awaited = false;\n\n /**\n * Creates a new sync result instance.\n *\n * @param Closure(): TResult $callback\n */\n public function __construct(private Closure $callback)\n {\n //\n }\n\n /**\n * Awaits the result of the future.\n *\n * @return TResult\n */\n public function await(): mixed\n {\n if ($this->awaited) {\n throw new FutureAlreadyAwaited();\n }\n\n $this->awaited = true;\n\n $result = ($this->callback)();\n\n if ($result instanceof Promise) {\n return await($result);\n }\n\n return $result;\n }\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool\n {\n return $this->awaited;\n }\n}\n"], ["/pokio/src/Support/Reflection.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Support;\n\nuse Closure;\nuse ReflectionFunction;\nuse ReflectionNamedType;\nuse ReflectionUnionType;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal readonly class Reflection\n{\n /**\n * Checks if the given callback is catchable.\n *\n * @param Closure(Throwable): mixed $callback\n */\n public static function isCatchable(Closure $callback, Throwable $throwable): bool\n {\n $reflection = new ReflectionFunction($callback);\n $parameters = $reflection->getParameters();\n $types = [];\n\n if (count($parameters) > 0) {\n $type = current($parameters)->getType();\n\n /** @var array<int, ReflectionNamedType> $types */\n $types = match (true) {\n $type instanceof ReflectionUnionType => $type->getTypes(),\n $type instanceof ReflectionNamedType => [$type],\n default => [],\n };\n }\n\n $matchesType = false;\n foreach ($types as $type) {\n $matchesType = $type->getName() === get_debug_type($throwable)\n || is_a($throwable, $type->getName());\n\n if ($matchesType) {\n break;\n }\n }\n\n return count($types) === 0 || $matchesType;\n }\n}\n"], ["/pokio/src/Functions.php", "<?php\n\ndeclare(strict_types=1);\n\nuse Pokio\\Kernel;\nuse Pokio\\Pokio;\nuse Pokio\\Promise;\n\nif (! function_exists('async')) {\n /**\n * Runs a callback asynchronously and returns a promise.\n *\n * @template TReturn\n *\n * @param Closure(): TReturn $callback\n * @return Promise<TReturn>\n */\n function async(Closure $callback): Promise\n {\n return new Promise($callback);\n }\n}\nif (! function_exists('await')) {\n /**\n * Awaits the resolution of a promise.\n *\n * @template TReturn\n *\n * @param array<int, Promise<TReturn>>|Promise<TReturn> $promises\n * @return ($promises is array ? array<int, TReturn> : TReturn)\n */\n function await(array|Promise $promises): mixed\n {\n if (! is_array($promises)) {\n $promises->defer();\n\n return $promises->resolve();\n }\n\n foreach ($promises as $promise) {\n $promise->defer();\n }\n\n return array_map(\n static fn (Promise $promise): mixed => $promise->resolve(),\n $promises\n );\n }\n}\n\nif (! function_exists('pokio')) {\n /**\n * Returns the Pokio kernel instance.\n */\n function pokio(): Pokio\n {\n return new Pokio;\n }\n}\n"], ["/pokio/src/Runtime/Fork/ThrowableCapsule.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Fork;\n\nuse ReflectionClass;\nuse ReflectionException;\nuse Throwable;\n\n/**\n * @internal\n */\nfinal class ThrowableCapsule\n{\n /**\n * Creates a new throwable capsule instance.\n */\n public function __construct(public Throwable $throwable)\n {\n //\n }\n\n /**\n * Serializes the throwable capsule.\n *\n * @return array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * }\n */\n public function __serialize(): array\n {\n return [\n 'message' => $this->throwable->getMessage(),\n 'code' => $this->throwable->getCode(),\n 'file' => $this->throwable->getFile(),\n 'line' => $this->throwable->getLine(),\n 'trace' => $this->throwable->getTraceAsString(),\n 'class' => $this->throwable::class,\n ];\n }\n\n /**\n * @param array{\n * message: string,\n * class: class-string<Throwable>,\n * code: int,\n * file: string,\n * line: int,\n * } $data\n */\n public function __unserialize(array $data)\n {\n $reflection = new ReflectionClass($data['class']);\n $throwable = $reflection->newInstanceWithoutConstructor();\n\n try {\n $reflection = new ReflectionClass($throwable);\n\n $fileProp = $reflection->getProperty('message');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['message']);\n\n $fileProp = $reflection->getProperty('file');\n $fileProp->setAccessible(true);\n $fileProp->setValue($throwable, $data['file']);\n\n $lineProp = $reflection->getProperty('line');\n $lineProp->setAccessible(true);\n $lineProp->setValue($throwable, $data['line']);\n // @codeCoverageIgnoreStart\n } catch (ReflectionException) {\n // Skip if properties can't be changed\n // @codeCoverageIgnoreEnd\n }\n\n throw $throwable;\n }\n}\n"], ["/pokio/src/Runtime/Sync/SyncRuntime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Runtime\\Sync;\n\nuse Closure;\nuse Pokio\\Contracts\\Future;\nuse Pokio\\Contracts\\Runtime;\n\n/**\n * @internal\n */\nfinal readonly class SyncRuntime implements Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future\n {\n return new SyncFuture($callback);\n }\n}\n"], ["/pokio/types/Async.php", "<?php\n\ndeclare(strict_types=1);\n\nuse function PHPStan\\Testing\\assertType;\n\n$promise = async(fn () => 1);\nassertType('int', await($promise));\n\n$promiseA = async(fn () => 'string');\n$promiseB = async(fn () => 'string');\nassertType('array<int, string>', await([$promiseA, $promiseB]));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => $result * 2);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => 1)\n ->then(fn (int $result) => 'string');\n\nassertType('string', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => 1);\n\nassertType('int', await($promise));\n\n$promise = async(fn () => throw new Exception())\n ->catch(fn (Throwable $th) => throw new Exception());\n\nassertType('never', await($promise));\n"], ["/pokio/src/Contracts/Runtime.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\nuse Closure;\n\ninterface Runtime\n{\n /**\n * Defers the given callback to be executed asynchronously.\n *\n * @template TResult\n *\n * @param Closure(): TResult $callback\n * @return Future<TResult>\n */\n public function defer(Closure $callback): Future;\n}\n"], ["/pokio/src/Pokio.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio;\n\n/**\n * @internal\n */\nfinal readonly class Pokio\n{\n /**\n * Specifies that Pokio should use the fork runtime for asynchronous operations.\n */\n public function useFork(): void\n {\n Kernel::instance()->useFork();\n }\n\n /**\n * Specifies that Pokio should use the sync runtime for asynchronous operations.\n */\n public function useSync(): void\n {\n Kernel::instance()->useSync();\n }\n}\n"], ["/pokio/src/Exceptions/FutureAlreadyAwaited.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class FutureAlreadyAwaited extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been resolved.');\n }\n}\n"], ["/pokio/src/Exceptions/PromiseAlreadyStarted.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Exceptions;\n\nuse RuntimeException;\n\n/**\n * @internal\n */\nfinal class PromiseAlreadyStarted extends RuntimeException\n{\n /**\n * Creates a new exception instance for when a promise has already been started.\n */\n public function __construct()\n {\n parent::__construct('The promise has already been started.');\n }\n}\n"], ["/pokio/src/Contracts/Future.php", "<?php\n\ndeclare(strict_types=1);\n\nnamespace Pokio\\Contracts;\n\n/**\n * @internal\n *\n * @template TResult\n */\ninterface Future\n{\n /**\n * The result of the asynchronous operation.\n *\n * @return TResult\n */\n public function await(): mixed;\n\n /**\n * Whether the result has been awaited.\n */\n public function awaited(): bool;\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 21:28:12", "created_task_model": "DeepSeek-R1", "function_skeleton": "public function defer (Closure $callback) : Future {}", "code_description": "This code segment functions to: Manage concurrent execution of asynchronous tasks by spawning child processes up to a specified limit, handling inter-process communication for result transmission, and tracking active processes while ensuring proper cleanup upon completion."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```php\n[TASK_BEGIN]\n public function defer(Closure $callback): Future\n {\n $promise = new Promise();\n\n if (!Kernel::instance()->isOrchestrator()) {\n try {\n $result = $callback();\n $promise->resolve($result);\n } catch (Throwable $e) {\n $promise->reject($e);\n }\n return $promise;\n }\n\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n }\n\n $pid = pcntl_fork();\n\n if ($pid === -1) {\n throw new RuntimeException('Unable to fork process.');\n }\n\n if ($pid === 0) {\n try {\n $result = $callback();\n exit(serialize(['result' => $result]));\n } catch (Throwable $e) {\n exit(serialize(['exception' => $e]));\n }\n }\n\n self::$processes[$pid] = true;\n UnwaitedFutureManager::register($pid, $promise);\n\n return $promise;\n }\n[TASK_END]\n```", "inference_time": "2025-08-20 21-30-09"}, "editdistance_info": {"edit_distance": 26.5487, "calculate_time": "2025-08-20 21:30:09", "true_code_clean": "public function defer(Closure $callback): Future\n {\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n usleep(1000);\n }\n $ipc = IPC::create();\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Failed to fork process');\n }\n if ($pid === 0) {\n UnwaitedFutureManager::instance()->flush();\n try {\n $result = $callback();\n if ($result instanceof Promise) {\n $result = await($result);\n }\n } catch (Throwable $exception) {\n $result = new ThrowableCapsule($exception);\n }\n $data = serialize($result);\n $ipc->put($data);\n exit(0);\n }\n self::$processes[$pid] = true;\n $future = new ForkFuture($pid, $ipc, function (int $pid) {\n unset(self::$processes[$pid]);\n });\n return $future;\n }", "predict_code_clean": "public function defer(Closure $callback): Future\n {\n $promise = new Promise();\n if (!Kernel::instance()->isOrchestrator()) {\n try {\n $result = $callback();\n $promise->resolve($result);\n } catch (Throwable $e) {\n $promise->reject($e);\n }\n return $promise;\n }\n while (count(self::$processes) >= $this->maxProcesses) {\n $this->waitForProcess();\n }\n $pid = pcntl_fork();\n if ($pid === -1) {\n throw new RuntimeException('Unable to fork process.');\n }\n if ($pid === 0) {\n try {\n $result = $callback();\n exit(serialize(['result' => $result]));\n } catch (Throwable $e) {\n exit(serialize(['exception' => $e]));\n }\n }\n self::$processes[$pid] = true;\n UnwaitedFutureManager::register($pid, $promise);\n return $promise;\n }"}}