This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Last revision Both sides next revision
rfc:object_scope_prng [2021/01/25 00:27]
zeriyoshi update 1.3
rfc:object_scope_prng [2021/04/14 12:12]
zeriyoshi close vote
Line 1: Line 1:
 ====== PHP RFC: Object scoped RNG Implementations. ====== ====== PHP RFC: Object scoped RNG Implementations. ======
-  * Version: 1.3 +  * Version: 2.1 (Implementation: 1.3) 
-  * Date: 2021-01-25+  * Date: 2020-12-20
   * Author: Go Kudo <zeriyoshi@gmail.com>   * Author: Go Kudo <zeriyoshi@gmail.com>
-  * Status: Under Discussion+  * Status: Voting
   * Implementation: https://github.com/php/php-src/pull/6568   * Implementation: https://github.com/php/php-src/pull/6568
   * First Published at: https://wiki.php.net/rfc/object_scope_prng   * First Published at: https://wiki.php.net/rfc/object_scope_prng
 ===== Introduction ===== ===== Introduction =====
- +PHP currently implements an RNG based on the Mersenne Twister, which can be used with mt_srand() and mt_rand().
-PHP currently provides the mt_srand() and mt_rand() functions based on the Meresenne Twister as PRNGs. +
-However, since these functions keep their state in global space, unintended function calls may cause inconsistency even for the same seed value.+
 <code php> <code php>
-mt_srand(1234)+\mt_srand(1234); // Seeding internal MT state. 
-foo(); +\mt_rand(); // Generate random number.
-mt_rand() === 411284887; // false +
- +
-function foo() { +
-    mt_rand(); // code added +
 </code> </code>
-This is inappropriate for applications that require consistency in the generated values (game logictest codeetc.)+The shuffle()str_shuffle()and array_rand(functions are also available.
-These global states also affect the forked child processes. In fact, the EasySwoole Swoole extension based framework has been alerted to this behavior[5]+
-In other languagesRNGs are implemented as objectsso this problem doesn't exists. [3] [4]+<code php> 
 +$array = [0 => 'foo'1 => 'bar'2 => 'baz']
 +\shuffle($array); // Shuffling array using internal MT state. 
 +\str_shuffle('foobar'); // Shuffling string using internal MT state. 
 +\array_rand($array, 1); // Randomize array using internal MT state. 
-The global state of MT is also used by other functions that use random numbersand this problem is further exacerbated when the consistency of the results is required by seeding with specific values. (Of courseyou are right that such usage is a bad example.)+However, the current implementation of the Mersenne Twister keeps the state in the global scopewhich can easily be unrepeatable with additional code.
 <code php> <code php>
-mt_srand(1234); +\mt_srand(1234); 
-$arr = [1, 2, 34, 5]+\str_shuffle('foobar'); // Result "afroob"always consistent. 
-shuffle($arr); + 
-echo print_r($arr, true); // Result is always consistent.+\mt_srand(1234)
 +\str_shuffle('foobar'); // Result "rfoaob"
-/* +function example_of_additional_code() { 
-Array +    \mt_rand(); // Unintended changes in internal MT state! 
-    [0] => 3 +
-    [1] => 2 +
-    [2] => 5 +
-    [3] => 4 +
-    [4] => 1 +
 </code> </code>
-Therefore, it may be a good idea to consider deprecating global state-dependent RNG functions in the future.+This is fine if you want to get a completely random resultbut it is inconsistent with the existence of the mt_srand() function, which accepts arbitrary seed values. Reproducible results are necessary for implementations that need to be reproduced, such as game logic or test code.
-One currently possible userland solution is to implement the PRNG in pure PHP. There is actually userland library [1]but it is not fast enough for PHP at the momentincluding with JIT (Benchmark results are available at Open Issues.)+On the other hand, if you want to get true "completely" random result, the results of the shuffle()str_shuffle(), and array_rand() functions are not cryptographically secure. This is due to the use of Mersenne Twister internally.
-This implementation will also allow us to support the PHP paradigmwhich will become even more complex in the future.+The first way to work around this problem is to implement RNG in PHP. In factsuch a library exists and is available.
-I have created an extension for PHP to improve these [2]. This could be used to consider what specific goals this RFC is trying to achieve.+However, the PHP implementation of RNG has execution speed issues. This is also the case in PHP 8.x when JIT is enabled.
-===== Proposal =====+**PHP 8.1-dev** 
 +<code shell> 
 +$ git clone "https://github.com/savvot/random" 
 +$ time ./php -r 'require __DIR__ . "/random/src/AbstractRand.php"; require __DIR__ . "/random/src/XorShiftRand.php"; $r new Savvot\Random\XorShiftRand(1234); for ($i 0; $i < 1000000; $i++) { $r->random(); }'
-Implements an object-scoped PRNG in PHP.+real    0m0.745s 
 +user    0m0.744s 
 +sys     0m0.000s 
-When this proposal is introduced, the code can be written as follows:+**PHP 8.1-dev + OPcache JIT** 
 +<code shell> 
 +$ git clone "https://github.com/savvot/random" 
 +$ time ./php -dzend_extension="$(pwd)/../../modules/opcache.so" -dopcache.jit_buffer_size=100M -dopcache.enable_cli=1 -r 'require __DIR__ . "/random/src/AbstractRand.php"; require __DIR__ . "/random/src/XorShiftRand.php"; $r = new Savvot\Random\XorShiftRand(1234); for ($i = 0; $i < 1000000; $i++) { $r->random(); }'
-<code php> +real    0m0.083s 
-$seed = 1234; +user    0m0.081s 
-$rng = new \RNG\MT19937($seed); +sys     0m0.002s 
-$array = [1, 2, 3, 4, 5];+</code>
-mt_srand(4321); mt_rand(); // Does not affect to $rng.+**RFC Implementation (based PHP 8.1-dev)** 
 +<code shell> 
 +$ time ./php -r '$r = new \RNG\XorShift128Plus(1234); for ($i = 0; $i < 1000000; $i++) { rng_next($r); }'
-shuffle($array, $rng); // Result is always consistent.+real    0m0.021s 
 +user    0m0.010s 
 +sys     0m0.011s 
-// Allow user-implemented RNG+RFC has been passed and Fiber will be introduced in PHP 8.1. Implementations with unpredictable execution order, such as Fiber, make this problem worse. 
 +For example (with amphp), the following results are difficult for the user to be aware of and are not guaranteed to be consistent in the future.
-class FixedNumberGenerator implements RNGInterface +<code php> 
-{ +use function Amp\defer; 
-    protected int $count = 0+use function Amp\delay
-     + 
-    public function next(): int +function task(int $i): void { 
-    { +    global $running; 
-        return $this->count++;+ 
 +    while ($running) 
 +        delay(250); 
 +        echo "${i} : " . mt_rand() . "\n";
     }     }
 } }
-echo str_shuffle('Hello', new FixedNumberGenerator()); /Result: olleH+mt_srand(1234); 
 +$running = true; 
 +defer(fn() => task(1)); 
 +defer(fn() => task(2)); 
 +defer(fn() => task(3)); 
 +defer(fn() => task(4)); 
 +$running = false; 
 +1 : 411284887 
 +4 : 1068724585 
 +2 : 1335968403 
 +3 : 1756294682 
 +1 : 940013158 
 +3 : 1314500282 
 +4 : 1686544716 
 +2 : 1656482812 
 +1 : 1674985287 
 +2 : 1848274264 
 +3 : 585388171 
 +4 : 323490420 
 +4 : 593702477 
 +3 : 426315791 
 +2 : 1722007381 
 +1 : 1750549071 
 </code> </code>
-The following are the implementation details. +In addition, problems with having state in the global scope have been reported in some extensionsFor example, the Swoole extension notes that the use of mt_rand() requires reinitialization in the process after forking.
-Firstit provides the following interface.+
-The next64() method is used to generate int values beyond 32 bits in a 64-bit environmentThis definition is also required in a 32-bit environment.+https://www.easyswoole.com/En/Other/random.html 
 +===== Proposal ===== 
 +Implements class-based object scoped PRNG into PHP. 
 +First, implement the following interface. This is a hypothetical PHP code.' 
 +Basically, this interface are supposed to be used as arguments to one of the functions. In other words, the next() and next64() methods are not intended to be called directlynext64() returns an invalid value in a 32-bit environment.
 <code php> <code php>
Line 95: Line 141:
 interface RNGInterface interface RNGInterface
 { {
 +    /** Generates 32bit pseudo random number. */
     public function next(): int;     public function next(): int;
 +    /** Genrates 64bit pseudo random nunber */
     public function next64(): int;     public function next64(): int;
 } }
 </code> </code>
-Next, make some changes to the existing functions and add some new ones.+The next step is to implement the RNG classes that implement this interface. This RFC proposes implementations of XorShift128+, MT19937 (similar to mt_srand()), and OS provided (similar to random_bytes()).
-<code php> +These implementations are done in C and are fast. Howeverby implementing RNGInterface, we can do the same thing in PHP code.
-function shuffle(array &$array?RNG\RNGInterface $rng = null): bool {} +
-function str_shuffle(string $string?RNG\RNGInterface $rng = null): string {} +
-function array_rand(array $array, int $num = 1, ?RNG\RNGInterface $rng = null): int|string|array {} +
-/** Generates a sequence of bytes for a specified range using RNG. */ +
-function rng_bytes(RNG\RNGInterface $rng, int $length): string {} +
-/** Generates a random number in range, likes random_int() */ +
-function rng_int(RNG\RNGInterface $rng, int $min, int $max): int [} +
-/** Generates 32bit raw random number using RNG */ +
-function rng_next(RNG\RNGInterface $rng, bool $unsigned = true): int{} +
-/** +
-  * Generates 64bit raw random number using RNG +
-  *  +
-  * @throws \ValueError Throws on 32bit environment. +
-  */ +
-function rng_next64(RNG\RNGInterface $rng, bool $unsigned = true): int{} +
- +
-Existing RNG-specifying functions will now be able to explicitly specify the source of the RNG. This makes it clear that these functions are using the RNG internally. +
- +
-Finally, we provide an RNG class that implements these interfaces. +
-At this time, considering support for XorShift128+ , MT19937 and OS.+
 <code php> <code php>
 namespace RNG; namespace RNG;
-class XorShift128Plus implements RNGInterface {} // use XorShift128+ algorithm +class XorShift128Plus implements RNGInterface // Fast modern PRNG. 
-class MT19937 implements RNGInterface {} // use MT19937 algorithm +
-class OS implements RNGInterface {} // use php_random_bytes() internal API (OS provided+    public function __construct(int $seed) {} 
-</code>+    public function next(): int {} 
 +    public function next64(): int {} 
 +    public function __serialize(): array {} 
 +    public function __unserialize(array $data): void {} 
-Basically, these classes are supposed to be used as arguments to one of the functionsIn other words, the next() and next64() methods are not intended to be called directly.+class MT19937 implements RNGInterface // Completely consistent \mt_srand() and \mt_rand() implementation. 
 +    public function __construct(int $seed) {} 
 +    public function next(): int {} 
 +    public function next64(): int {} 
 +    public function __serialize(): array {} 
 +    public function __unserialize(array $data): void {} 
-This is for proper handling of next64() in a 32-bit environment and to improve interoperability with the mt_rand() function. The mt_rand() function performs a bit shift on the result and always returns an unsigned integer.+class OS implements RNGInterface // // Cryptographically Secure PRNG. 
 +    public function next(): int {} 
 +    public function next64(): int {} 
 +Some RNG implementations can serialize state using the standard PHP serialization methods (serialize() and unserialize() function). This is useful for the purpose of storing state.
 <code php> <code php>
 +$rng = new RNG\XorShift128Plus(1234);
 +$serialized_string = \serialize($rng);
 +$rng2 = \unserialize($serialized_string);
 +\rng_next($rng) === rng_next($rng2); // true
-// If the second argument is true (default)rng_next() performs bit shifting like mt_rand() and always returns an unsigned integer. +For existing functions that use RNGs, make changes to accept these classes as arguments. If an argument is specifiedthe function will use that RNG instead of the internal MT.
-mt_srand(1234); +
-$mt_state = new \RNG\MT19937(1234); +
-mt_rand() === rng_next($mt_state); // true+
-// If false, it will return the value as is. This is exactly the same result as $rng->next(). +<code php
-mt_rand() === rng_next($mt_statefalse); // false+function shuffle(array &$array?RNG\RNGInterface $rng = null): bool {}
-// This is useful if you want to use the numbers generated by the RNG directly. +function str_shuffle(string $string, ?RNG\RNGInterface $rng = null): string {} 
-rng_next(new \RNG\MT19937(1234), false) === 822569775; // true+ 
 +function array_rand(array $arrayint $num 1, ?RNG\RNGInterface $rng null): int|string|array {}
 </code> </code>
-Some RNG implementations (currently XorShift128+ and MT19937) can serialize state using the standard PHP serialization methods (serialize() and unserialize() function)This is useful for the purpose of storing state.+Finally, implement a function that can generate values from RNGs, such as the mt_rand(), random_bytes() function. If the $unsigned argument is false, it will return the value generated by the RNG as is.
 <code php> <code php>
-$rng = new RNG\XorShift128Plus(1234);+function rng_bytes(RNG\RNGInterface $rng, int $length): string {} // simlar random_bytes()
-rng_next($rng);+function rng_int(RNG\RNGInterface $rng, int $min, int $max): int {} // simlar mt_rand(with optional arguments
-$serialized_string = serialize($rng);+function rng_next(RNG\RNGInterface $rng, bool $unsigned = true): int {} // simlar mt_rand(without optional arguments
-$rng2 = unserialize($serialized_string); +/** @throws ValueError */ 
- +function rng_next64(RNG\RNGInterface $rng, bool $unsigned true): int {} // Generates 64bit random number
-rng_next($rng=== rng_next($rng2)// true+
 </code> </code>
-===== Backward Incompatible Changes =====+The rng_next64() function will throw a ValueError exception if 64-bit integer is not available on the platform.
-With the provides of new classes, some class names (or namespaceswill no longer be available in userland.+This is for proper handling of next64() in a 32-bit environment and to improve interoperability with the mt_rand() function. The mt_rand() function performs a bit shift on the result and always returns an unsigned integer.
-Some of the functions that use RNGs will have additional optional $rng arguments.+<code php> 
 +// If the second argument is true (default), rng_next() performs bit shifting like mt_rand() and always returns an unsigned integer. 
 +$mt_state = new \RNG\MT19937(1234); 
 +\mt_rand() === \rng_next($mt_state); // true 
 +// If false, it will return the value as is. This is exactly the same result as $rng->next(). 
 +\mt_rand() === \rng_next($mt_state, false); // false 
 +// This is useful if you want to use the numbers generated by the RNG directly. 
 +\rng_next(new \RNG\MT19937(1234), false) === 822569775; // true 
 +===== Backward Incompatible Changes ===== 
 +A new optional argument will be added to the existing arguments below. If you are using reflection for these functions, this may cause problems.
   * shuffle()   * shuffle()
Line 184: Line 251:
 ==== To Existing Extensions ==== ==== To Existing Extensions ====
-orng [[https://pecl.php.net/package/orng]] : it is a PECL extension that provides almost the same functionality. If the interface is provided by the core in the future, it will need to be supported. And that's me.+none
 ==== To Opcache ==== ==== To Opcache ====
Line 196: Line 263:
 ===== Open Issues ===== ===== Open Issues =====
 +=== In other languages, what methods do you use to get around this problem? ===
 +Similar to this proposal, a class-based implementation is in place.
-=== With JIT, won't the userland implementation reach a useful speed? === +  * C# https://docs.microsoft.com/en-us/dotnet/api/system.random 
-Comparing the speed of the userland implementation of XorShift128+ and the orng extension.+  * Java https://docs.oracle.com/javase/8/docs/api/java/util/Random.html
-**PHP 8.0** +===== Unaffected PHP Functionality ===== 
-<code shell> +It does not affect any related existing functions.
-$ time php -r 'require __DIR__ . "/vendor/savvot/random/src/AbstractRand.php"; require __DIR__ . "/vendor/savvot/random/src/XorShiftRand.php"; $r new Savvot\Random\XorShiftRand(1234); for ($i 0; $i < 1000000; $i++) { $r->random(); }' +
- +
-real 0m0.441s +
-user 0m0.429s +
-sys 0m0.010s +
-</code> +
- +
-**PHP 8.0 + OPcache JIT** +
-<code shell> +
-$ time php -dopcache.jit_buffer_size=100M -dopcache.enable_cli=1 -r 'require __DIR__ . "/vendor/savvot/random/src/AbstractRand.php"; require __DIR__ . "/vendor/savvot/random/src/XorShiftRand.php"; $r new Savvot\Random\XorShiftRand(1234); for ($i 0; $i < 1000000; $i++) { $r->random(); }' +
- +
-real 0m0.155s +
-user 0m0.139s +
-sys 0m0.015s +
-</code> +
- +
-**PHP 8.0 + orng** +
-<code shell> +
-$ time php -r '$r = new \ORNG\XorShift128Plus(1234); for ($i 0; $i < 1000000; $i++) { $r->next(); }' +
- +
-real 0m0.056s +
-user 0m0.048s +
-sys 0m0.008s +
-This provides a significant improvement, but still slow from the C implementation. 
-=== Why do we need this feature in the core and not in the extension? === 
-In order to use the features related to pseudo-random numbers that PHP currently provides, an understanding of the core is required. If this proposal is implemented, users will be able to use pseudo-random numbers under the easy to understand concept of objects. This is a useful improvement to the overall functionality of the language. 
-===== Unaffected PHP Functionality ===== 
-It does not affect any related existing functions. (However, in the case of Type II, non-destructive arguments will be added.) 
   * mt_srand()   * mt_srand()
   * mt_rand()   * mt_rand()
-===== Proposed Voting Choices ===== +===== Vote ===== 
-Yes/No, requiring 2/3 majority+Voting opens 2021-04-01 and 2021-04-15 at 00:00:00 EDT. 2/3 required to accept.
-There are a few additional options for implementation. +<doodle title="Add object-scoped RNG" auth="zeriyoshi" voteType="single" closed="true">
- +
-<doodle title="Add object-scoped RNG" auth="user" voteType="single" closed="true">+
    * Yes    * Yes
    * No    * No
-<doodle title="To which namespace should these classes and interfaces belong?" auth="user" voteType="single" closed="true"> 
-   * Top Level (\RNGInterface) 
-   * "RNG" namespace (\RNG\RNGInterface) 
-   * "PHP\RNG" namespace (\PHP\RNG\RNGInterface) 
 </doodle> </doodle>
 ===== Patches and Tests ===== ===== Patches and Tests =====
   * https://github.com/php/php-src/pull/6568   * https://github.com/php/php-src/pull/6568
-===== References ===== 
-  * [1] https://github.com/savvot/random 
-  * [2] https://github.com/zeriyoshi/php-ext-orng 
-  * [3] https://docs.microsoft.com/en-us/dotnet/api/system.random 
-  * [4] https://docs.oracle.com/javase/8/docs/api/java/util/Random.html 
-  * [5] https://www.easyswoole.com/En/Other/random.html 
rfc/object_scope_prng.txt · Last modified: 2021/04/14 14:38 by zeriyoshi