Skip to content

Implement deterministic RAND(N) and improve unseeded RAND() translation#341

Open
wp-fuse wants to merge 2 commits intoWordPress:trunkfrom
wp-fuse:fix/rand-implementation
Open

Implement deterministic RAND(N) and improve unseeded RAND() translation#341
wp-fuse wants to merge 2 commits intoWordPress:trunkfrom
wp-fuse:fix/rand-implementation

Conversation

@wp-fuse
Copy link
Copy Markdown

@wp-fuse wp-fuse commented Mar 30, 2026

Summary

This PR improves the MySQL-compatible RAND() support in the AST-based SQLite driver. It replaces the previous generic implementation with a bit-exact MySQL Linear Congruential Generator (LCG) and a robust SQLite-level translation for unseeded calls.

Technical Changes

  1. Seeded RAND(N):
    • Refactored the rand() UDF in WP_SQLite_PDO_User_Defined_Functions to use an instance-local LCG.
    • Implemented MySQL’s specific 30-bit seed initialization constants (0x10001, 55555555, 0x10000001) to ensure bit-exact deterministic output for given seeds, as requested in the previous review.
    • Removed mt_srand() and mt_rand() usage to prevent PHP global state pollution.
  2. Unseeded RAND():
    • Updated the AST node translation in WP_PDO_MySQL_On_SQLite to use:
      ((RANDOM() & 0x7FFFFFFFFFFFFFFF) / 9223372036854775808.0).
    • This bitwise approach avoids integer overflow issues inherent to ABS(-9223372036854775808) in SQLite and ensures an unbiased distribution in the [0, 1) range.
  3. Cleanup: This is a standalone PR following the feedback to separate the RAND() fix from other compatibility layers. All string-replacement hacks and non-AST layers have been excluded.

Validation

  • PHPUnit: All 795 tests in the official test suite are passing.
  • CS: Verified against WordPress Coding Standards via phpcs.

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.

1 participant