Skip to content

Add a warning about the subtle global state in legacy random functions#5414

Open
anthonyryan1 wants to merge 1 commit intophp:masterfrom
anthonyryan1:master
Open

Add a warning about the subtle global state in legacy random functions#5414
anthonyryan1 wants to merge 1 commit intophp:masterfrom
anthonyryan1:master

Conversation

@anthonyryan1
Copy link

@anthonyryan1 anthonyryan1 requested a review from TimWolla as a code owner March 7, 2026 03:07
Copy link
Member

@TimWolla TimWolla left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. I need to think about this a little more. Perhaps it's best to also have a generic “global state bad” message on the affected functions and just mention the fork gotcha in an “aside”.

@TimWolla TimWolla requested a review from Girgias March 9, 2026 21:16
@anthonyryan1 anthonyryan1 changed the title Add a warning about the footgun that is combining legacy MT random functions and pcntl_fork Add a warning about the subtle global state in legacy random functions Mar 10, 2026
@anthonyryan1 anthonyryan1 requested a review from Girgias March 10, 2026 18:36
@anthonyryan1
Copy link
Author

I've refocused this on simply being a warning on the legacy random pages. Let me know if you'd like to see any other changes or improvements.

I've left pcntl out entirely, because arguably this problem is just that these functions still exist and the flaw is their use, rather than any overlap with pcntl.

Comment on lines +36 to +37
This function shares a global state with other functions.
These functions can alter each other's outputs, regardless of scope.
Copy link
Member

@TimWolla TimWolla Mar 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the direction. Here's a suggestion that I feel is a little more precise (and hopefully not much more complicated to understand):

This function uses the global Mt19937 (“Mersenne Twister”) instance as the source of randomness and thus shares its state with all other functions using the global Mt19937. Using any of these functions affects the output of all the other functions, regardless of scope.

In particular seeding the Mt19937 instance with a fixed value using <function>mt_srand</function> or <function>srand</function> to generate a repeatable output sequence affects <emph>all</emph> following calls, unless the instance is reseeded with a random seed afterwards.

And of course, the existing warning that there are only 2^32 seeds applies …

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pcntl_fork() should reseed the MT rand in all children

3 participants