Fix caching when random is enabled.

From #6725.