1 (edited by svl 2008-01-18 15:50)

Topic: mt_rand() not random enough

Hi, we're running a large punbb forum (freshly migrated from UBB - of all places) on windows 2003 (not my choice), and the primary way for members on this forum to navigate is through the "new posts since your last visit" and "recent topics" searches. We're getting quite a few error reports however on the "Unable to insert search results". Turning on PUN_DEBUG, and randomly reloading those pages quite a few times (with clicks to topics and marking read and such - so I don't have reliable steps to reproduce) I get the following error report:

File: C:\AppServ\www\bbs\search.php
Line: 416

PunBB reported: Unable to insert search results

Database reported: Duplicate entry '1794661802' for key 1 (Errno: 1062)

key 1 is the search id, which is defined as mt_rand(1, 2147483647);
At a guess, this randomizing function is run maybe 500-1000 times an hour. And we're getting a couple of collisions per hour! This is rather insane. I don't know if the root cause is windows, or whatever, but I think it would be really good if a better unique id could be generated as the primary key for the search_cache table. (Maybe the last x digits of timestamp concatenated with a (shorter) random value to prevent a collision from the page being loaded multiple times at the exact same time?)

Re: mt_rand() not random enough

mt_rand() is about as random as you can get without using much more complex algorithms hmm

A solution would be to generate a few random numbers, look them up and use the first one that isn't taken.

Re: mt_rand() not random enough

Try removing the call to mt_srand from common.php. That should solve the issue.

4

Re: mt_rand() not random enough

Ah! That makes a lot of sense. I already was having major issues trying to reproduce mt_rand()s lack of randomness.
Thanks a lot!