From d61150b12651e6f04db2bf625b65933d31e6a5c7 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Tue, 20 Oct 2026 09:22:50 +0200 Subject: [PATCH] fix(fork): reseed mt_rand in every message child A forked child inherits the server's Mersenne Twister state. Once the server has drawn one mt_rand() (react/dns does for DNS query ids), every message child continued from the same state, so array_rand(), rand() and shuffle() returned the same values in each one. In learn-atc, question.random kept serving the same two questions in turn (#3088). prepareChild() now calls mt_srand(), with a fork test for both the fix and the failure mode. Co-Authored-By: Claude Opus 5.5 (1M context) --- AGENTS.md | 3 ++ src/Server/ChildProcesses.php | 22 ++++++++++- tests/Server/ChildProcessesTest.php | 60 +++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e6967f0..bd2652a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,9 @@ Consequences — internalize these, they change how you write handlers: known hazard; prefer a real queued **Job** for anything heavy or that must survive. - **State does not carry over between messages** except via `wsSession()` (§6) or the cache. Each child gets a *fresh* DB connection and purged Redis/cache singletons. +- **Each child reseeds `mt_rand`** (`ChildProcesses::reseedRandom()`), so `rand()`, + `array_rand()` and `shuffle()` differ per message. Without it every child continues + the parent's generator state and draws the same numbers. - **Concurrency is capped** by `config('websockets.max_concurrent_children')` (protects MySQL `max_connections`); excess messages queue in memory and run as children free up. - **A child never outlives the server.** Right after fork the child closes its copy of the diff --git a/src/Server/ChildProcesses.php b/src/Server/ChildProcesses.php index d71e91c..efbbd3d 100644 --- a/src/Server/ChildProcesses.php +++ b/src/Server/ChildProcesses.php @@ -213,8 +213,9 @@ final class ChildProcesses * Run in a freshly forked child, before any handler code. * * Closes the child's copy of every registered listening socket, forgets - * the parent's child bookkeeping (siblings are not this child's children) - * and gives the server's signals their default dispositions back. + * the parent's child bookkeeping (siblings are not this child's children), + * gives the server's signals their default dispositions back and reseeds + * the random number generator. * * @return int number of listening sockets closed */ @@ -226,10 +227,27 @@ final class ChildProcesses self::$terminating = false; self::restoreDefaultSignals(); + self::reseedRandom(); return $closed; } + /** + * Give this process its own Mersenne Twister seed. + * + * A forked child inherits the parent's generator state. Once the server + * has drawn a single mt_rand() (react/dns does for every DNS query id), + * every message child continues from the same state, so mt_rand(), rand(), + * array_rand(), shuffle() and str_shuffle() return the same values in each + * one (learn-atc #3088: question.random served the same two questions in + * turn). random_int() and random_bytes() use the OS CSPRNG and are not + * affected. + */ + public static function reseedRandom(): void + { + mt_srand(); + } + /** * Close this process's copy of every registered listening socket. * diff --git a/tests/Server/ChildProcessesTest.php b/tests/Server/ChildProcessesTest.php index 30e3d5c..3f81729 100644 --- a/tests/Server/ChildProcessesTest.php +++ b/tests/Server/ChildProcessesTest.php @@ -236,6 +236,66 @@ class ChildProcessesTest extends TestCase $this->assertTrue($ticked); } + public function test_children_that_ran_prepare_child_draw_different_random_numbers() + { + // learn-atc #3088: question.random served the same two questions in + // turn, because every message child picked the same array_rand() index. + $draws = $this->childDraws(6, function () { + ChildProcesses::prepareChild(); + }); + + $this->assertCount(6, $draws); + $this->assertGreaterThan(1, count(array_unique($draws)), 'Every child drew ' . $draws[0] . '.'); + } + + public function test_children_that_did_not_reseed_draw_the_same_random_numbers() + { + // The failure mode the fix removes: proves the test above is meaningful. + $draws = $this->childDraws(6, function () { + // inherits the parent's Mersenne Twister state + }); + + $this->assertCount(6, $draws); + $this->assertCount(1, array_unique($draws)); + } + + /** + * Seed the Mersenne Twister in this process, as the server does once it + * has drawn any mt_rand() (react/dns does for its query ids), then fork + * $children children that run $setup and report one array_rand() pick. + * + * @return int[] + */ + private function childDraws(int $children, callable $setup): array + { + mt_rand(); + $pool = range(1, 1000); + $draws = []; + + for ($i = 0; $i < $children; $i++) { + $pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); + + $pid = pcntl_fork(); + $this->assertNotSame(-1, $pid, 'fork failed'); + + if ($pid === 0) { + fclose($pair[0]); + $setup(); + fwrite($pair[1], $pool[array_rand($pool)] . "\n"); + $this->exitChild(0); + } + + $this->spawned[] = $pid; + fclose($pair[1]); + stream_set_timeout($pair[0], 5); + $draws[] = (int) trim((string) fgets($pair[0])); + fclose($pair[0]); + pcntl_waitpid($pid, $status); + } + + return $draws; + } + /** * Fork a child that runs $setup, tells the parent it is ready, then waits * to be killed.