Issue Bug Closed

#107337Session Garbage collection probability is calculated wrongly (off by one and non-uniform) and inefficient

S P 08/27/25, 09:35 updated 12/02/25, 13:58

Description

(relevant for all verson since “forever”, selected 13 because it is the current LTS, but also present in main branch)

https://github.com/TYPO3/typo3/blob/main/typo3/sysext/core/Classes/Session/UserSessionManager.php#L284

if (random_int(0, mt_getrandmax()) % 100 <= $garbageCollectionProbability)

Modulo 100 results in a maximum of 99, so comparing to less or equal will make a garbageCollectionProbability of 99 succeed always. Which is not how probabilities work (only 100 should be always ).

Also, why such complicated way of getting a number between 0 and 99 in the first place? Why not just random_int(0, 99) (without modulo)? The method random_int is guaranteed to be based on a uniform distribution. What the current implementation does is actually “deforming” away from the uniform distribution, because due to the modulo against a probably non-multiple maximum of the divisor, some numbers are a tiny bit more likely than others (namely all the remainders modulo 100 above the last multiple of 100 of mt_getrandmax() which are statistically more likely to appear because of this)

I suggest simplifying this to

if (random_int(0, 99) < $garbageCollectionProbability)

which would behave like it seemed to be intended originally and by the naming of the variables.

And since this is not cryptographically relevant, maybe even consider using just rand() instead of random_int(), because it is way faster:

if (rand(0, 99) < $garbageCollectionProbability)

Reviews 2