Skip to content

Commit

Permalink
Fix the seed of RandomLocalState to be 64bit instead of 32bits
Browse files Browse the repository at this point in the history
This is connected to raising RandomEngine to use 64bit state, see duckdb#13920, but
initialization need to be done on full range otherwise entropy is limited when many repeated statement are executed.

Note that here we only solve the problem for RandomLocalState.
A wider rework of the RandomEngine API migth be also handy.

Test case provided by @taniabogatsch

Fixes duckdb/duckdb-rs#331
Fixes marcboeker/go-duckdb#339
  • Loading branch information
carlopi committed Dec 28, 2024
1 parent ab8c909 commit e53eaac
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 4 deletions.
5 changes: 3 additions & 2 deletions extension/core_functions/scalar/random/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
namespace duckdb {

struct RandomLocalState : public FunctionLocalState {
explicit RandomLocalState(uint32_t seed) : random_engine(seed) {
explicit RandomLocalState(uint64_t seed) : random_engine(0) {
random_engine.SetSeed(seed);
}

RandomEngine random_engine;
Expand All @@ -30,7 +31,7 @@ static unique_ptr<FunctionLocalState> RandomInitLocalState(ExpressionState &stat
FunctionData *bind_data) {
auto &random_engine = RandomEngine::Get(state.GetContext());
lock_guard<mutex> guard(random_engine.lock);
return make_uniq<RandomLocalState>(random_engine.NextRandomInteger());
return make_uniq<RandomLocalState>(random_engine.NextRandomInteger64());
}

ScalarFunction RandomFun::GetFunction() {
Expand Down
2 changes: 1 addition & 1 deletion src/common/random_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ uint32_t RandomEngine::NextRandomInteger32(uint32_t min, uint32_t max) {
return min + static_cast<uint32_t>(NextRandom32() * double(max - min));
}

void RandomEngine::SetSeed(uint32_t seed) {
void RandomEngine::SetSeed(uint64_t seed) {
random_state->pcg.seed(seed);
}

Expand Down
2 changes: 1 addition & 1 deletion src/include/duckdb/common/random_engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class RandomEngine {
uint32_t NextRandomInteger(uint32_t min, uint32_t max);
uint64_t NextRandomInteger64();

void SetSeed(uint32_t seed);
void SetSeed(uint64_t seed);

static RandomEngine &Get(ClientContext &context);

Expand Down

0 comments on commit e53eaac

Please sign in to comment.