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) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-20 09:22:50 +02:00
parent 35ed320202
commit d61150b126
3 changed files with 83 additions and 2 deletions

View File

@ -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. 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 - **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. 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 - **Concurrency is capped** by `config('websockets.max_concurrent_children')` (protects
MySQL `max_connections`); excess messages queue in memory and run as children free up. 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 - **A child never outlives the server.** Right after fork the child closes its copy of the

View File

@ -213,8 +213,9 @@ final class ChildProcesses
* Run in a freshly forked child, before any handler code. * Run in a freshly forked child, before any handler code.
* *
* Closes the child's copy of every registered listening socket, forgets * Closes the child's copy of every registered listening socket, forgets
* the parent's child bookkeeping (siblings are not this child's children) * the parent's child bookkeeping (siblings are not this child's children),
* and gives the server's signals their default dispositions back. * gives the server's signals their default dispositions back and reseeds
* the random number generator.
* *
* @return int number of listening sockets closed * @return int number of listening sockets closed
*/ */
@ -226,10 +227,27 @@ final class ChildProcesses
self::$terminating = false; self::$terminating = false;
self::restoreDefaultSignals(); self::restoreDefaultSignals();
self::reseedRandom();
return $closed; 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. * Close this process's copy of every registered listening socket.
* *

View File

@ -236,6 +236,66 @@ class ChildProcessesTest extends TestCase
$this->assertTrue($ticked); $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 * Fork a child that runs $setup, tells the parent it is ready, then waits
* to be killed. * to be killed.