From 5f6be83108b0dd022e63bcbd9944b4876ad783ab Mon Sep 17 00:00:00 2001 From: Dirkjan Bussink Date: Tue, 19 Mar 2024 10:38:28 +0100 Subject: [PATCH] Migrate to math/rand/v2 (#15513) Signed-off-by: Dirkjan Bussink --- examples/compose/client.go | 4 +- go/bucketpool/bucketpool_test.go | 12 +- go/cmd/vtclient/cli/vtclient.go | 4 +- .../vreplication/vdiff/vdiff_env_test.go | 4 +- go/cmd/vttestserver/cli/main_test.go | 4 +- .../colldata/uca_contraction_test.go | 9 +- go/mysql/collations/colldata/uca_test.go | 4 +- go/mysql/conn_test.go | 6 +- go/mysql/decimal/decimal_test.go | 8 +- go/mysql/decimal/mysql_test.go | 10 +- go/mysql/endtoend/query_test.go | 4 +- go/mysql/query_benchmark_test.go | 4 +- go/pools/numbered_test.go | 4 +- go/pools/resource_pool.go | 4 +- .../benchmarking/legacy/resource_pool.go | 4 +- .../smartconnpool/benchmarking/load_test.go | 2 +- go/sqltypes/testing.go | 20 +-- go/stats/counters_test.go | 6 +- .../backup/vtctlbackup/pitr_test_framework.go | 4 +- go/test/endtoend/cluster/cluster_process.go | 5 +- .../onlineddl/revert/onlineddl_revert_test.go | 10 +- .../scheduler/onlineddl_scheduler_test.go | 8 +- .../onlineddl_vrepl_mini_stress_test.go | 10 +- .../onlineddl_vrepl_stress_suite_test.go | 14 +- .../vrepl/schemadiff_vrepl_suite_test.go | 4 +- .../buffer/buffer_test_helpers.go | 4 +- go/test/endtoend/vreplication/cluster_test.go | 4 +- .../fk_ext_load_generator_test.go | 6 +- go/test/endtoend/vreplication/fk_test.go | 8 +- .../vreplication/initial_data_test.go | 6 +- .../endtoend/vreplication/wrappers_test.go | 6 +- .../vtgate/foreignkey/fk_fuzz_test.go | 132 +++++++++--------- .../foreignkey/stress/fk_stress_test.go | 16 +-- .../endtoend/vtgate/foreignkey/utils_test.go | 10 +- .../queries/benchmark/benchmark_test.go | 4 +- .../endtoend/vtgate/queries/kill/main_test.go | 2 +- .../vtgate/queries/random/query_gen.go | 110 +++++++-------- .../vtgate/queries/random/query_gen_test.go | 62 -------- .../vtgate/queries/random/random_expr_test.go | 7 +- .../vtgate/queries/random/random_test.go | 5 +- go/test/stress/stress.go | 2 +- go/timer/randticker.go | 5 +- .../internal/sync/sync_internal_test.go | 4 +- go/viperutil/internal/sync/sync_test.go | 6 +- go/vt/discovery/tablet_picker.go | 4 +- go/vt/discovery/topology_watcher_test.go | 4 +- go/vt/key/destination.go | 4 +- go/vt/mysqlctl/xtrabackupengine_test.go | 7 +- go/vt/schemadiff/schema_test.go | 2 +- go/vt/sqlparser/normalizer_test.go | 12 +- go/vt/sqlparser/parse_test.go | 4 +- go/vt/sqlparser/precedence_test.go | 6 +- go/vt/sqlparser/random_expr.go | 38 +++-- go/vt/sqlparser/rewriter_test.go | 3 +- go/vt/sqlparser/walker_test.go | 5 +- go/vt/tableacl/testlib/testlib.go | 4 +- go/vt/throttler/demo/throttler_demo.go | 4 +- go/vt/topo/memorytopo/memorytopo.go | 4 +- go/vt/topo/zk2topo/zk_conn.go | 4 +- go/vt/topotools/shard_test.go | 4 +- go/vt/vtadmin/cluster/cluster.go | 6 +- .../cluster/discovery/discovery_consul.go | 6 +- .../cluster/discovery/discovery_json.go | 6 +- .../discovery/fakediscovery/discovery.go | 6 +- go/vt/vtadmin/debug/debug_test.go | 10 +- go/vt/vtadmin/internal/backoff/backoff.go | 4 +- go/vt/vtadmin/internal/rand/rand.go | 44 ------ go/vt/vtctl/vdiff_env_test.go | 4 +- go/vt/vterrors/errors_test.go | 2 +- go/vt/vtgate/endtoend/oltp_test.go | 26 ++-- go/vt/vtgate/engine/aggregations_test.go | 6 +- go/vt/vtgate/engine/route.go | 4 +- go/vt/vtgate/evalengine/api_compare_test.go | 2 +- .../evalengine/integration/fuzz_test.go | 14 +- go/vt/vtgate/fakerpcvtgateconn/conn.go | 4 +- go/vt/vtgate/planbuilder/plan_test.go | 2 +- .../planbuilder/predicate_rewrite_test.go | 12 +- go/vt/vtgate/semantics/table_set_test.go | 4 +- go/vt/vtgate/tabletgateway.go | 6 +- go/vt/vthash/highway/highwayhash_test.go | 5 +- go/vt/vtorc/logic/topology_recovery.go | 2 +- go/vt/vttablet/endtoend/queries_test.go | 4 +- .../grpctmclient/cached_client_flaky_test.go | 10 +- go/vt/vttablet/tabletmanager/tm_init.go | 5 +- .../tabletserver/messager/message_manager.go | 2 +- .../tabletserver/query_engine_test.go | 8 +- .../tabletserver/query_executor_test.go | 14 +- .../tabletserver/throttle/throttler.go | 2 +- .../tabletserver/txthrottler/tx_throttler.go | 4 +- .../vstreamer/packet_size_test.go | 13 +- go/vt/vttest/environment.go | 4 +- go/vt/vttest/randomdata.go | 33 ++--- go/vt/wrangler/traffic_switcher_env_test.go | 8 +- go/vt/wrangler/vdiff_env_test.go | 4 +- go/vt/wrangler/wrangler_env_test.go | 4 +- test/client/client.go | 4 +- 96 files changed, 407 insertions(+), 563 deletions(-) delete mode 100644 go/test/endtoend/vtgate/queries/random/query_gen_test.go delete mode 100644 go/vt/vtadmin/internal/rand/rand.go diff --git a/examples/compose/client.go b/examples/compose/client.go index 95d6b4f4815..1fb4a4eb463 100644 --- a/examples/compose/client.go +++ b/examples/compose/client.go @@ -27,7 +27,7 @@ package main import ( "fmt" - "math/rand" + "math/rand/v2" "os" "time" @@ -59,7 +59,7 @@ func main() { fmt.Printf("begin failed: %v\n", err) os.Exit(1) } - page := rand.Intn(100) + 1 + page := rand.IntN(100) + 1 timeCreated := time.Now().UnixNano() if _, err := tx.Exec("INSERT INTO messages (page,time_created_ns,message) VALUES (?,?,?)", page, timeCreated, "V is for speed"); err != nil { diff --git a/go/bucketpool/bucketpool_test.go b/go/bucketpool/bucketpool_test.go index af9693a523f..dc3baaa289d 100644 --- a/go/bucketpool/bucketpool_test.go +++ b/go/bucketpool/bucketpool_test.go @@ -17,7 +17,7 @@ limitations under the License. package bucketpool import ( - "math/rand" + "math/rand/v2" "testing" "github.com/stretchr/testify/assert" @@ -118,13 +118,13 @@ func TestPoolWeirdMaxSize(t *testing.T) { func TestFuzz(t *testing.T) { maxTestSize := 16384 for range 20000 { - minSize := rand.Intn(maxTestSize) + minSize := rand.IntN(maxTestSize) if minSize == 0 { minSize = 1 } - maxSize := rand.Intn(maxTestSize-minSize) + minSize + maxSize := rand.IntN(maxTestSize-minSize) + minSize p := New(minSize, maxSize) - bufSize := rand.Intn(maxTestSize) + bufSize := rand.IntN(maxTestSize) buf := p.Get(bufSize) require.Len(t, *buf, bufSize, "unexpected buf length") sPool := p.findPool(bufSize) @@ -143,7 +143,7 @@ func BenchmarkPool(b *testing.B) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { - randomSize := rand.Intn(pool.maxSize) + randomSize := rand.IntN(pool.maxSize) data := pool.Get(randomSize) pool.Put(data) } @@ -156,7 +156,7 @@ func BenchmarkPoolGet(b *testing.B) { b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { - randomSize := rand.Intn(pool.maxSize) + randomSize := rand.IntN(pool.maxSize) data := pool.Get(randomSize) _ = data } diff --git a/go/cmd/vtclient/cli/vtclient.go b/go/cmd/vtclient/cli/vtclient.go index 949af851ab4..44b47c38dc7 100644 --- a/go/cmd/vtclient/cli/vtclient.go +++ b/go/cmd/vtclient/cli/vtclient.go @@ -22,7 +22,7 @@ import ( "encoding/json" "fmt" "io" - "math/rand" + "math/rand/v2" "os" "sort" "sync" @@ -174,7 +174,7 @@ func _run(cmd *cobra.Command, args []string) (*results, error) { go func() { if useRandom { for { - seqChan <- rand.Intn(maxSeqID-minSeqID) + minSeqID + seqChan <- rand.IntN(maxSeqID-minSeqID) + minSeqID } } else { for i := minSeqID; i < maxSeqID; i++ { diff --git a/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff_env_test.go b/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff_env_test.go index 10d7762acde..b42c2c55072 100644 --- a/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff_env_test.go +++ b/go/cmd/vtctldclient/command/vreplication/vdiff/vdiff_env_test.go @@ -21,7 +21,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -88,7 +88,7 @@ func newTestVDiffEnv(t testing.TB, ctx context.Context, sourceShards, targetShar env.tmc.testEnv = env // Generate a unique dialer name. - dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { env.mu.Lock() defer env.mu.Unlock() diff --git a/go/cmd/vttestserver/cli/main_test.go b/go/cmd/vttestserver/cli/main_test.go index 98a49b5bc4e..802f2533202 100644 --- a/go/cmd/vttestserver/cli/main_test.go +++ b/go/cmd/vttestserver/cli/main_test.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "os/exec" "path" "strings" @@ -426,7 +426,7 @@ func resetConfig(conf vttest.Config) { } func randomPort() int { - v := rand.Int31n(20000) + v := rand.Int32N(20000) return int(v + 10000) } diff --git a/go/mysql/collations/colldata/uca_contraction_test.go b/go/mysql/collations/colldata/uca_contraction_test.go index d09b2a6d982..a3511a07df6 100644 --- a/go/mysql/collations/colldata/uca_contraction_test.go +++ b/go/mysql/collations/colldata/uca_contraction_test.go @@ -19,7 +19,7 @@ package colldata import ( "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "os" "sort" "testing" @@ -203,14 +203,13 @@ func (s *strgen) generate(length int, freq float64) (out []byte) { return flat[i] < flat[j] }) - gen := rand.New(rand.NewSource(0xDEADBEEF)) out = make([]byte, 0, length) for len(out) < length { - if gen.Float64() < freq { - cnt := s.contractions[rand.Intn(len(s.contractions))] + if rand.Float64() < freq { + cnt := s.contractions[rand.IntN(len(s.contractions))] out = append(out, cnt...) } else { - cp := flat[rand.Intn(len(flat))] + cp := flat[rand.IntN(len(flat))] out = append(out, string(cp)...) } } diff --git a/go/mysql/collations/colldata/uca_test.go b/go/mysql/collations/colldata/uca_test.go index e00fb5fd6d1..5eb51fed67e 100644 --- a/go/mysql/collations/colldata/uca_test.go +++ b/go/mysql/collations/colldata/uca_test.go @@ -19,7 +19,7 @@ package colldata import ( "bytes" "fmt" - "math/rand" + "math/rand/v2" "slices" "sort" "strings" @@ -1002,7 +1002,7 @@ func TestUCACollationOrder(t *testing.T) { ary := slices.Clone(sorted) for i := range ary { - j := rand.Intn(i + 1) + j := rand.IntN(i + 1) ary[i], ary[j] = ary[j], ary[i] } slices.SortFunc(ary, func(a, b string) int { diff --git a/go/mysql/conn_test.go b/go/mysql/conn_test.go index 69ba1fa5e0c..64b97052ead 100644 --- a/go/mysql/conn_test.go +++ b/go/mysql/conn_test.go @@ -23,7 +23,7 @@ import ( "encoding/binary" "encoding/hex" "fmt" - "math/rand" + "math/rand/v2" "net" "strconv" "strings" @@ -744,7 +744,7 @@ func TestEOFOrLengthEncodedIntFuzz(t *testing.T) { }() for i := 0; i < 100; i++ { - bytes := make([]byte, rand.Intn(16)+1) + bytes := make([]byte, rand.IntN(16)+1) _, err := crypto_rand.Read(bytes) require.NoError(t, err, "error doing rand.Read") @@ -990,7 +990,7 @@ var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func randSeq(n int) string { b := make([]rune, n) for i := range b { - b[i] = letters[rand.Intn(len(letters))] + b[i] = letters[rand.IntN(len(letters))] } return string(b) } diff --git a/go/mysql/decimal/decimal_test.go b/go/mysql/decimal/decimal_test.go index 3499ab8f802..6a6cf001231 100644 --- a/go/mysql/decimal/decimal_test.go +++ b/go/mysql/decimal/decimal_test.go @@ -20,7 +20,7 @@ package decimal import ( "math" - "math/rand" + "math/rand/v2" "reflect" "strconv" "strings" @@ -142,13 +142,12 @@ func TestNewFromFloat(t *testing.T) { func TestNewFromFloatRandom(t *testing.T) { n := 0 - rng := rand.New(rand.NewSource(0xdead1337)) for { n++ if n == 10 { break } - in := (rng.Float64() - 0.5) * math.MaxFloat64 * 2 + in := (rand.Float64() - 0.5) * math.MaxFloat64 * 2 want, err := NewFromString(strconv.FormatFloat(in, 'f', -1, 64)) if err != nil { t.Error(err) @@ -176,13 +175,12 @@ func TestNewFromFloatQuick(t *testing.T) { func TestNewFromFloat32Random(t *testing.T) { n := 0 - rng := rand.New(rand.NewSource(0xdead1337)) for { n++ if n == 10 { break } - in := float32((rng.Float64() - 0.5) * math.MaxFloat32 * 2) + in := float32((rand.Float64() - 0.5) * math.MaxFloat32 * 2) want, err := NewFromString(strconv.FormatFloat(float64(in), 'f', -1, 32)) if err != nil { t.Error(err) diff --git a/go/mysql/decimal/mysql_test.go b/go/mysql/decimal/mysql_test.go index 1668c4377db..d1b0c52169b 100644 --- a/go/mysql/decimal/mysql_test.go +++ b/go/mysql/decimal/mysql_test.go @@ -21,13 +21,12 @@ import ( "encoding/json" "math" "math/big" - "math/rand" + "math/rand/v2" "os" "path" "strconv" "strings" "testing" - "time" ) func TestDecimalAdd(t *testing.T) { @@ -366,10 +365,8 @@ func TestRoundtripStress(t *testing.T) { count = 100 } - rng := rand.New(rand.NewSource(time.Now().UnixNano())) - for n := 0; n < count; n++ { - fb := strconv.AppendFloat(nil, rng.NormFloat64(), 'f', -1, 64) + fb := strconv.AppendFloat(nil, rand.NormFloat64(), 'f', -1, 64) d, err := NewFromMySQL(fb) if err != nil { t.Fatalf("failed to parse %q: %v", fb, err) @@ -383,10 +380,9 @@ func TestRoundtripStress(t *testing.T) { func BenchmarkFormatting(b *testing.B) { const Count = 10000 - var rng = rand.New(rand.NewSource(time.Now().UnixNano())) var parsed = make([]Decimal, 0, Count) for i := 0; i < Count; i++ { - parsed = append(parsed, NewFromFloat(rng.NormFloat64())) + parsed = append(parsed, NewFromFloat(rand.NormFloat64())) } b.Run("StringFixed(8)", func(b *testing.B) { diff --git a/go/mysql/endtoend/query_test.go b/go/mysql/endtoend/query_test.go index 847d1274854..3436d045071 100644 --- a/go/mysql/endtoend/query_test.go +++ b/go/mysql/endtoend/query_test.go @@ -19,7 +19,7 @@ package endtoend import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strings" "testing" @@ -151,7 +151,7 @@ func TestLargeQueries(t *testing.T) { randString := func(n int) string { b := make([]byte, n) for i := range b { - b[i] = letterBytes[rand.Intn(len(letterBytes))] + b[i] = letterBytes[rand.IntN(len(letterBytes))] } return string(b) } diff --git a/go/mysql/query_benchmark_test.go b/go/mysql/query_benchmark_test.go index a9c44dbf50c..357bc8997ed 100644 --- a/go/mysql/query_benchmark_test.go +++ b/go/mysql/query_benchmark_test.go @@ -18,7 +18,7 @@ package mysql import ( "context" - "math/rand" + "math/rand/v2" "net" "strings" "testing" @@ -98,7 +98,7 @@ func benchmarkQuery(b *testing.B, threads int, query string, mkCfg mkListenerCfg execQuery := query if execQuery == "" { // generate random query - n := rand.Intn(maxPacketSize-len(benchmarkQueryPrefix)) + 1 + n := rand.IntN(maxPacketSize-len(benchmarkQueryPrefix)) + 1 execQuery = benchmarkQueryPrefix + strings.Repeat("x", n) } diff --git a/go/pools/numbered_test.go b/go/pools/numbered_test.go index 826af8253b8..50be453c925 100644 --- a/go/pools/numbered_test.go +++ b/go/pools/numbered_test.go @@ -17,7 +17,7 @@ limitations under the License. package pools import ( - "math/rand" + "math/rand/v2" "strings" "testing" @@ -99,7 +99,7 @@ func BenchmarkRegisterUnregisterParallel(b *testing.B) { b.SetParallelism(200) b.RunParallel(func(pb *testing.PB) { for pb.Next() { - id := rand.Int63() + id := rand.Int64() p.Register(id, val) p.Unregister(id, "some reason") } diff --git a/go/pools/resource_pool.go b/go/pools/resource_pool.go index 939b73fa66c..2a20cf67acd 100644 --- a/go/pools/resource_pool.go +++ b/go/pools/resource_pool.go @@ -22,7 +22,7 @@ import ( "context" "errors" "fmt" - "math/rand" + "math/rand/v2" "sync" "sync/atomic" "time" @@ -419,7 +419,7 @@ func (rp *ResourcePool) extendedMaxLifetime() time.Duration { if maxLifetime == 0 { return 0 } - return time.Duration(maxLifetime + rand.Int63n(maxLifetime)) + return time.Duration(maxLifetime + rand.Int64N(maxLifetime)) } // MaxLifetimeClosed returns the count of resources closed due to refresh timeout. diff --git a/go/pools/smartconnpool/benchmarking/legacy/resource_pool.go b/go/pools/smartconnpool/benchmarking/legacy/resource_pool.go index df8c44e1530..33547349860 100644 --- a/go/pools/smartconnpool/benchmarking/legacy/resource_pool.go +++ b/go/pools/smartconnpool/benchmarking/legacy/resource_pool.go @@ -20,7 +20,7 @@ import ( "context" "errors" "fmt" - "math/rand" + "math/rand/v2" "sync" "sync/atomic" "time" @@ -576,7 +576,7 @@ func (rp *ResourcePool) extendedMaxLifetime() time.Duration { if maxLifetime == 0 { return 0 } - return time.Duration(maxLifetime + rand.Int63n(maxLifetime)) + return time.Duration(maxLifetime + rand.Int64N(maxLifetime)) } // MaxLifetimeClosed returns the count of resources closed due to refresh timeout. diff --git a/go/pools/smartconnpool/benchmarking/load_test.go b/go/pools/smartconnpool/benchmarking/load_test.go index 537daf2c357..e97537bca0c 100644 --- a/go/pools/smartconnpool/benchmarking/load_test.go +++ b/go/pools/smartconnpool/benchmarking/load_test.go @@ -21,7 +21,7 @@ import ( "encoding/json" "fmt" "math" - "math/rand" + "math/rand/v2" "os" "sort" "sync" diff --git a/go/sqltypes/testing.go b/go/sqltypes/testing.go index 649462333c7..2fd9ee9c2be 100644 --- a/go/sqltypes/testing.go +++ b/go/sqltypes/testing.go @@ -21,7 +21,7 @@ import ( "encoding/base64" "encoding/hex" "fmt" - "math/rand" + "math/rand/v2" "strconv" "strings" "time" @@ -181,7 +181,7 @@ func TestRandomValues() (Value, Value) { } func randomNumericType(i int) Value { - r := rand.Intn(len(numericTypes)) + r := rand.IntN(len(numericTypes)) return numericTypes[r](i) } @@ -201,7 +201,7 @@ var numericTypes = []func(int) Value{ type RandomGenerator func() Value func randomBytes() []byte { - b := make([]byte, rand.Intn(128)) + b := make([]byte, rand.IntN(128)) _, _ = crand.Read(b) return b } @@ -211,13 +211,13 @@ var RandomGenerators = map[Type]RandomGenerator{ return NULL }, Int8: func() Value { - return NewInt8(int8(rand.Intn(255))) + return NewInt8(int8(rand.IntN(255))) }, Int32: func() Value { - return NewInt32(rand.Int31()) + return NewInt32(rand.Int32()) }, Int64: func() Value { - return NewInt64(rand.Int63()) + return NewInt64(rand.Int64()) }, Uint32: func() Value { return NewUint32(rand.Uint32()) @@ -229,7 +229,7 @@ var RandomGenerators = map[Type]RandomGenerator{ return NewFloat64(rand.ExpFloat64()) }, Decimal: func() Value { - dec := fmt.Sprintf("%d.%d", rand.Intn(999999999), rand.Intn(999999999)) + dec := fmt.Sprintf("%d.%d", rand.IntN(999999999), rand.IntN(999999999)) if rand.Int()&0x1 == 1 { dec = "-" + dec } @@ -255,11 +255,11 @@ var RandomGenerators = map[Type]RandomGenerator{ }, TypeJSON: func() Value { var j string - switch rand.Intn(6) { + switch rand.IntN(6) { case 0: j = "null" case 1: - i := rand.Int63() + i := rand.Int64() if rand.Int()&0x1 == 1 { i = -i } @@ -286,6 +286,6 @@ func randTime() time.Time { max := time.Date(2070, 1, 0, 0, 0, 0, 0, time.UTC).Unix() delta := max - min - sec := rand.Int63n(delta) + min + sec := rand.Int64N(delta) + min return time.Unix(sec, 0) } diff --git a/go/stats/counters_test.go b/go/stats/counters_test.go index 22d6e769d3d..72eb11e1a10 100644 --- a/go/stats/counters_test.go +++ b/go/stats/counters_test.go @@ -18,7 +18,7 @@ package stats import ( "expvar" - "math/rand" + "math/rand/v2" "reflect" "sort" "strings" @@ -189,13 +189,11 @@ func BenchmarkCountersTailLatency(b *testing.B) { b.ResetTimer() b.SetParallelism(100) // The actual number of goroutines is 100*GOMAXPROCS b.RunParallel(func(pb *testing.PB) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - var start time.Time for pb.Next() { // sleep between 0~200ms to simulate 10 QPS per goroutine. - time.Sleep(time.Duration(r.Int63n(200)) * time.Millisecond) + time.Sleep(time.Duration(rand.Int64N(200)) * time.Millisecond) start = time.Now() benchCounter.Add("c1", 1) c <- time.Since(start) diff --git a/go/test/endtoend/backup/vtctlbackup/pitr_test_framework.go b/go/test/endtoend/backup/vtctlbackup/pitr_test_framework.go index 6270c023eab..64e058dfe65 100644 --- a/go/test/endtoend/backup/vtctlbackup/pitr_test_framework.go +++ b/go/test/endtoend/backup/vtctlbackup/pitr_test_framework.go @@ -19,7 +19,7 @@ package vtctlbackup import ( "context" "fmt" - "math/rand" + "math/rand/v2" "testing" "time" @@ -209,7 +209,7 @@ func ExecTestIncrementalBackupAndRestoreToPos(t *testing.T, tcase *PITRTestCase) // Also, we give the replica a chance to catch up. time.Sleep(postWriteSleepDuration) // randomly flush binary logs 0, 1 or 2 times - FlushBinaryLogsOnReplica(t, 0, rand.Intn(3)) + FlushBinaryLogsOnReplica(t, 0, rand.IntN(3)) waitForReplica(t, 0) recordRowsPerPosition(t) // configure --incremental-from-pos to either: diff --git a/go/test/endtoend/cluster/cluster_process.go b/go/test/endtoend/cluster/cluster_process.go index 0233b2ac1ea..3ef4e8a1b3b 100644 --- a/go/test/endtoend/cluster/cluster_process.go +++ b/go/test/endtoend/cluster/cluster_process.go @@ -22,7 +22,7 @@ import ( "flag" "fmt" "io" - "math/rand" + "math/rand/v2" "net" "os" "os/exec" @@ -776,7 +776,6 @@ func NewBareCluster(cell string, hostname string) *LocalProcessCluster { _ = os.Setenv("VTDATAROOT", cluster.CurrentVTDATAROOT) log.Infof("Created cluster on %s. ReusingVTDATAROOT=%v", cluster.CurrentVTDATAROOT, cluster.ReusingVTDATAROOT) - rand.Seed(time.Now().UTC().UnixNano()) return cluster } @@ -1223,7 +1222,7 @@ func (cluster *LocalProcessCluster) GetAndReserveTabletUID() int { } func getRandomNumber(maxNumber int32, baseNumber int) int { - return int(rand.Int31n(maxNumber)) + baseNumber + return int(rand.Int32N(maxNumber)) + baseNumber } func getVtStartPort() int { diff --git a/go/test/endtoend/onlineddl/revert/onlineddl_revert_test.go b/go/test/endtoend/onlineddl/revert/onlineddl_revert_test.go index 672e79c0985..9a63ac29960 100644 --- a/go/test/endtoend/onlineddl/revert/onlineddl_revert_test.go +++ b/go/test/endtoend/onlineddl/revert/onlineddl_revert_test.go @@ -20,7 +20,7 @@ import ( "context" "flag" "fmt" - "math/rand" + "math/rand/v2" "os" "path" "strings" @@ -1282,7 +1282,7 @@ func getCreateTableStatement(t *testing.T, tablet *cluster.Vttablet, tableName s } func generateInsert(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(insertRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1306,7 +1306,7 @@ func generateInsert(t *testing.T, conn *mysql.Conn) error { } func generateUpdate(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(updateRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1330,7 +1330,7 @@ func generateUpdate(t *testing.T, conn *mysql.Conn) error { } func generateDelete(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(deleteRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1369,7 +1369,7 @@ func runSingleConnection(ctx context.Context, t *testing.T, done *int64) { log.Infof("Terminating single connection") return } - switch rand.Int31n(3) { + switch rand.Int32N(3) { case 0: err = generateInsert(t, conn) case 1: diff --git a/go/test/endtoend/onlineddl/scheduler/onlineddl_scheduler_test.go b/go/test/endtoend/onlineddl/scheduler/onlineddl_scheduler_test.go index e0f665ff278..883b1e43831 100644 --- a/go/test/endtoend/onlineddl/scheduler/onlineddl_scheduler_test.go +++ b/go/test/endtoend/onlineddl/scheduler/onlineddl_scheduler_test.go @@ -22,7 +22,7 @@ import ( "flag" "fmt" "io" - "math/rand" + "math/rand/v2" "os" "path" "strings" @@ -1615,7 +1615,7 @@ func testDeclarative(t *testing.T) { var uuids []string generateInsert := func(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(insertRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1639,7 +1639,7 @@ func testDeclarative(t *testing.T) { } generateUpdate := func(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(updateRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1663,7 +1663,7 @@ func testDeclarative(t *testing.T) { } generateDelete := func(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(deleteRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) diff --git a/go/test/endtoend/onlineddl/vrepl_stress/onlineddl_vrepl_mini_stress_test.go b/go/test/endtoend/onlineddl/vrepl_stress/onlineddl_vrepl_mini_stress_test.go index 84c1ea7165c..770f7f3ee93 100644 --- a/go/test/endtoend/onlineddl/vrepl_stress/onlineddl_vrepl_mini_stress_test.go +++ b/go/test/endtoend/onlineddl/vrepl_stress/onlineddl_vrepl_mini_stress_test.go @@ -20,7 +20,7 @@ import ( "context" "flag" "fmt" - "math/rand" + "math/rand/v2" "os" "path" "runtime" @@ -428,7 +428,7 @@ func getCreateTableStatement(t *testing.T, tablet *cluster.Vttablet, tableName s } func generateInsert(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(insertRowStatement, id, nextOpOrder()) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -452,7 +452,7 @@ func generateInsert(t *testing.T, conn *mysql.Conn) error { } func generateUpdate(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(updateRowStatement, nextOpOrder(), id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -476,7 +476,7 @@ func generateUpdate(t *testing.T, conn *mysql.Conn) error { } func generateDelete(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(deleteRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -514,7 +514,7 @@ func runSingleConnection(ctx context.Context, t *testing.T, sleepInterval time.D defer ticker.Stop() for { - switch rand.Int31n(3) { + switch rand.Int32N(3) { case 0: err = generateInsert(t, conn) case 1: diff --git a/go/test/endtoend/onlineddl/vrepl_stress_suite/onlineddl_vrepl_stress_suite_test.go b/go/test/endtoend/onlineddl/vrepl_stress_suite/onlineddl_vrepl_stress_suite_test.go index 0db25088bd0..a3fa676d40b 100644 --- a/go/test/endtoend/onlineddl/vrepl_stress_suite/onlineddl_vrepl_stress_suite_test.go +++ b/go/test/endtoend/onlineddl/vrepl_stress_suite/onlineddl_vrepl_stress_suite_test.go @@ -31,7 +31,7 @@ import ( "context" "flag" "fmt" - "math/rand" + "math/rand/v2" "os" "path" "strings" @@ -515,7 +515,7 @@ func TestSchemaChange(t *testing.T) { t.Run("migrate", func(t *testing.T) { require.NotEmpty(t, testcase.alterStatement) - hintText := fmt.Sprintf("hint-after-alter-%d", rand.Int31n(int32(maxTableRows))) + hintText := fmt.Sprintf("hint-after-alter-%d", rand.Int32N(int32(maxTableRows))) hintStatement := fmt.Sprintf(alterHintStatement, hintText) fullStatement := fmt.Sprintf("%s, %s", hintStatement, testcase.alterStatement) @@ -644,10 +644,10 @@ func getCreateTableStatement(t *testing.T, tablet *cluster.Vttablet, tableName s } func generateInsert(t *testing.T, conn *mysql.Conn, autoIncInsert bool) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(insertRowStatement, id, -id, id, id, nextOpOrder()) if autoIncInsert { - id = rand.Int31() + id = rand.Int32() query = fmt.Sprintf(insertRowAutoIncStatement, -id, id, id, nextOpOrder()) } qr, err := conn.ExecuteFetch(query, 1000, true) @@ -658,7 +658,7 @@ func generateInsert(t *testing.T, conn *mysql.Conn, autoIncInsert bool) error { } func generateUpdate(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(updateRowStatement, nextOpOrder(), id) qr, err := conn.ExecuteFetch(query, 1000, true) if err == nil && qr != nil { @@ -668,7 +668,7 @@ func generateUpdate(t *testing.T, conn *mysql.Conn) error { } func generateDelete(t *testing.T, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(deleteRowStatement, id) qr, err := conn.ExecuteFetch(query, 1000, true) if err == nil && qr != nil { @@ -697,7 +697,7 @@ func runSingleConnection(ctx context.Context, t *testing.T, autoIncInsert bool, log.Infof("Terminating single connection") return } - switch rand.Int31n(3) { + switch rand.Int32N(3) { case 0: err = generateInsert(t, conn, autoIncInsert) case 1: diff --git a/go/test/endtoend/schemadiff/vrepl/schemadiff_vrepl_suite_test.go b/go/test/endtoend/schemadiff/vrepl/schemadiff_vrepl_suite_test.go index 79c3b62ebea..79cb4a0174e 100644 --- a/go/test/endtoend/schemadiff/vrepl/schemadiff_vrepl_suite_test.go +++ b/go/test/endtoend/schemadiff/vrepl/schemadiff_vrepl_suite_test.go @@ -281,8 +281,8 @@ func testSingle(t *testing.T, testName string) { // hints := &schemadiff.DiffHints{AutoIncrementStrategy: schemadiff.AutoIncrementIgnore} // // count := 20 // // for i := 0; i < count; i++ { -// // fromTestTableSchema := fromTestTableSchemas[rand.Intn(len(fromTestTableSchemas))] -// // toTestTableSchema := toTestTableSchemas[rand.Intn(len(toTestTableSchemas))] +// // fromTestTableSchema := fromTestTableSchemas[rand.IntN(len(fromTestTableSchemas))] +// // toTestTableSchema := toTestTableSchemas[rand.IntN(len(toTestTableSchemas))] // // testName := fmt.Sprintf("%s/%s", fromTestTableSchema.testName, toTestTableSchema.testName) // // t.Run(testName, func(t *testing.T) { // // validateDiff(t, fromTestTableSchema.tableSchema, toTestTableSchema.tableSchema, hints) diff --git a/go/test/endtoend/tabletgateway/buffer/buffer_test_helpers.go b/go/test/endtoend/tabletgateway/buffer/buffer_test_helpers.go index 96cbab6fcd8..ca4fe5f6094 100644 --- a/go/test/endtoend/tabletgateway/buffer/buffer_test_helpers.go +++ b/go/test/endtoend/tabletgateway/buffer/buffer_test_helpers.go @@ -33,7 +33,7 @@ import ( "encoding/json" "fmt" "io" - "math/rand" + "math/rand/v2" "net/http" "sync" "testing" @@ -174,7 +174,7 @@ func updateExecute(c *threadParams, conn *mysql.Conn) error { // Sleep between [0, 1] seconds to prolong the time the transaction is in // flight. This is more realistic because applications are going to keep // their transactions open for longer as well. - dur := time.Duration(rand.Int31n(1000)) * time.Millisecond + dur := time.Duration(rand.Int32N(1000)) * time.Millisecond if c.slowQueries { dur = dur + 1*time.Second } diff --git a/go/test/endtoend/vreplication/cluster_test.go b/go/test/endtoend/vreplication/cluster_test.go index 6fd63edb200..1863cba2b60 100644 --- a/go/test/endtoend/vreplication/cluster_test.go +++ b/go/test/endtoend/vreplication/cluster_test.go @@ -19,7 +19,7 @@ package vreplication import ( "fmt" "io" - "math/rand" + "math/rand/v2" "net/http" "os" "os/exec" @@ -156,7 +156,7 @@ type Tablet struct { } func setTempVtDataRoot() string { - dirSuffix := 100000 + rand.Intn(999999-100000) // 6 digits + dirSuffix := 100000 + rand.IntN(999999-100000) // 6 digits if debugMode { vtdataroot = originalVtdataroot } else { diff --git a/go/test/endtoend/vreplication/fk_ext_load_generator_test.go b/go/test/endtoend/vreplication/fk_ext_load_generator_test.go index 12b5871781f..dc058c0574b 100644 --- a/go/test/endtoend/vreplication/fk_ext_load_generator_test.go +++ b/go/test/endtoend/vreplication/fk_ext_load_generator_test.go @@ -19,7 +19,7 @@ package vreplication import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strings" "testing" "time" @@ -301,7 +301,7 @@ func (lg *SimpleLoadGenerator) Start() error { return default: } - op := rand.Intn(100) + op := rand.IntN(100) switch { case op < 50: // 50% chance to insert lg.insert() @@ -388,7 +388,7 @@ func (lg *SimpleLoadGenerator) insert() { require.NoError(t, err) require.NotNil(t, qr) // Insert one or more children, some with valid foreign keys, some without. - for i := 0; i < rand.Intn(4)+1; i++ { + for i := 0; i < rand.IntN(4)+1; i++ { currentChildId++ if i == 3 && lg.overrideConstraints { query = fmt.Sprintf(insertChildQueryOverrideConstraints, lg.keyspace, currentChildId, currentParentId+1000000) diff --git a/go/test/endtoend/vreplication/fk_test.go b/go/test/endtoend/vreplication/fk_test.go index 8a495ecb817..a75b6727fdc 100644 --- a/go/test/endtoend/vreplication/fk_test.go +++ b/go/test/endtoend/vreplication/fk_test.go @@ -19,7 +19,7 @@ package vreplication import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strconv" "testing" "time" @@ -200,7 +200,7 @@ func (ls *fkLoadSimulator) simulateLoad() { default: } // Decide operation based on random number - op := rand.Intn(100) + op := rand.IntN(100) switch { case op < 50: // 50% chance to insert ls.insert() @@ -256,7 +256,7 @@ func (ls *fkLoadSimulator) insert() { qr := ls.exec(insertQuery) require.NotNil(t, qr) // insert one or more children, some with valid foreign keys, some without. - for i := 0; i < rand.Intn(4)+1; i++ { + for i := 0; i < rand.IntN(4)+1; i++ { currentChildId++ if i == 3 { insertQuery = fmt.Sprintf("INSERT /*+ SET_VAR(foreign_key_checks=0) */ INTO child (id, parent_id) VALUES (%d, %d)", currentChildId, currentParentId+1000000) @@ -282,7 +282,7 @@ func (ls *fkLoadSimulator) getRandomId() int64 { } func (ls *fkLoadSimulator) update() { - updateQuery := fmt.Sprintf("UPDATE parent SET name = 'parent%d' WHERE id = %d", rand.Intn(1000)+1, ls.getRandomId()) + updateQuery := fmt.Sprintf("UPDATE parent SET name = 'parent%d' WHERE id = %d", rand.IntN(1000)+1, ls.getRandomId()) ls.exec(updateQuery) } diff --git a/go/test/endtoend/vreplication/initial_data_test.go b/go/test/endtoend/vreplication/initial_data_test.go index 23f699563e2..ea34ef7fddf 100644 --- a/go/test/endtoend/vreplication/initial_data_test.go +++ b/go/test/endtoend/vreplication/initial_data_test.go @@ -18,7 +18,7 @@ package vreplication import ( "fmt" - "math/rand" + "math/rand/v2" "os" "testing" @@ -65,8 +65,8 @@ func insertJSONValues(t *testing.T) { numJsonValues := len(jsonValues) for id <= NumJSONRows { id++ - j1 := rand.Intn(numJsonValues) - j2 := rand.Intn(numJsonValues) + j1 := rand.IntN(numJsonValues) + j2 := rand.IntN(numJsonValues) query := fmt.Sprintf(q, id, jsonValues[j1], jsonValues[j2]) execVtgateQuery(t, vtgateConn, "product:0", query) } diff --git a/go/test/endtoend/vreplication/wrappers_test.go b/go/test/endtoend/vreplication/wrappers_test.go index 2d4949b60dc..5c7e01aa155 100644 --- a/go/test/endtoend/vreplication/wrappers_test.go +++ b/go/test/endtoend/vreplication/wrappers_test.go @@ -17,7 +17,7 @@ limitations under the License. package vreplication import ( - "math/rand" + "math/rand/v2" "strconv" "github.com/stretchr/testify/require" @@ -90,7 +90,7 @@ func newMoveTables(vc *VitessCluster, mt *moveTablesWorkflow, flavor workflowFla mt.vc = vc var mt2 iMoveTables if flavor == workflowFlavorRandom { - flavor = workflowFlavors[rand.Intn(len(workflowFlavors))] + flavor = workflowFlavors[rand.IntN(len(workflowFlavors))] } switch flavor { case workflowFlavorVtctl: @@ -287,7 +287,7 @@ func newReshard(vc *VitessCluster, rs *reshardWorkflow, flavor workflowFlavor) i rs.vc = vc var rs2 iReshard if flavor == workflowFlavorRandom { - flavor = workflowFlavors[rand.Intn(len(workflowFlavors))] + flavor = workflowFlavors[rand.IntN(len(workflowFlavors))] } switch flavor { case workflowFlavorVtctl: diff --git a/go/test/endtoend/vtgate/foreignkey/fk_fuzz_test.go b/go/test/endtoend/vtgate/foreignkey/fk_fuzz_test.go index d430c31e35a..2f1a703b54a 100644 --- a/go/test/endtoend/vtgate/foreignkey/fk_fuzz_test.go +++ b/go/test/endtoend/vtgate/foreignkey/fk_fuzz_test.go @@ -19,7 +19,7 @@ package foreignkey import ( "database/sql" "fmt" - "math/rand" + "math/rand/v2" "sync" "sync/atomic" "testing" @@ -96,7 +96,7 @@ func newFuzzer(concurrency int, maxValForId int, maxValForCol int, insertShare i // The returned set is a list of strings, because for prepared statements, we have to run // set queries first and then the final query eventually. func (fz *fuzzer) generateQuery() []string { - val := rand.Intn(fz.insertShare + fz.updateShare + fz.deleteShare) + val := rand.IntN(fz.insertShare + fz.updateShare + fz.deleteShare) if val < fz.insertShare { switch fz.queryFormat { case OlapSQLQueries, SQLQueries: @@ -128,66 +128,66 @@ func (fz *fuzzer) generateQuery() []string { } func getInsertType() string { - return []string{"insert", "replace"}[rand.Intn(2)] + return []string{"insert", "replace"}[rand.IntN(2)] } // generateInsertDMLQuery generates an INSERT query from the parameters for the fuzzer. func (fz *fuzzer) generateInsertDMLQuery(insertType string) string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] setVarFkChecksVal := fz.getSetVarFkChecksVal() if tableName == "fk_t20" { - colValue := rand.Intn(1 + fz.maxValForCol) - col2Value := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) + col2Value := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s %vinto %v (id, col, col2) values (%v, %v, %v)", insertType, setVarFkChecksVal, tableName, idValue, convertIntValueToString(colValue), convertIntValueToString(col2Value)) } else if isMultiColFkTable(tableName) { - colaValue := rand.Intn(1 + fz.maxValForCol) - colbValue := rand.Intn(1 + fz.maxValForCol) + colaValue := rand.IntN(1 + fz.maxValForCol) + colbValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s %vinto %v (id, cola, colb) values (%v, %v, %v)", insertType, setVarFkChecksVal, tableName, idValue, convertIntValueToString(colaValue), convertIntValueToString(colbValue)) } else { - colValue := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s %vinto %v (id, col) values (%v, %v)", insertType, setVarFkChecksVal, tableName, idValue, convertIntValueToString(colValue)) } } // generateUpdateDMLQuery generates an UPDATE query from the parameters for the fuzzer. func (fz *fuzzer) generateUpdateDMLQuery() string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] setVarFkChecksVal := fz.getSetVarFkChecksVal() - updWithLimit := rand.Intn(2) - limitCount := rand.Intn(3) + updWithLimit := rand.IntN(2) + limitCount := rand.IntN(3) if tableName == "fk_t20" { - colValue := convertIntValueToString(rand.Intn(1 + fz.maxValForCol)) - col2Value := convertIntValueToString(rand.Intn(1 + fz.maxValForCol)) + colValue := convertIntValueToString(rand.IntN(1 + fz.maxValForCol)) + col2Value := convertIntValueToString(rand.IntN(1 + fz.maxValForCol)) if updWithLimit == 0 { return fmt.Sprintf("update %v%v set col = %v, col2 = %v where id = %v", setVarFkChecksVal, tableName, colValue, col2Value, idValue) } return fmt.Sprintf("update %v%v set col = %v, col2 = %v order by id limit %v", setVarFkChecksVal, tableName, colValue, col2Value, limitCount) } else if isMultiColFkTable(tableName) { - if rand.Intn(2) == 0 { - colaValue := convertIntValueToString(rand.Intn(1 + fz.maxValForCol)) - colbValue := convertIntValueToString(rand.Intn(1 + fz.maxValForCol)) + if rand.IntN(2) == 0 { + colaValue := convertIntValueToString(rand.IntN(1 + fz.maxValForCol)) + colbValue := convertIntValueToString(rand.IntN(1 + fz.maxValForCol)) if fz.concurrency > 1 { - colaValue = fz.generateExpression(rand.Intn(4)+1, "cola", "colb", "id") - colbValue = fz.generateExpression(rand.Intn(4)+1, "cola", "colb", "id") + colaValue = fz.generateExpression(rand.IntN(4)+1, "cola", "colb", "id") + colbValue = fz.generateExpression(rand.IntN(4)+1, "cola", "colb", "id") } if updWithLimit == 0 { return fmt.Sprintf("update %v%v set cola = %v, colb = %v where id = %v", setVarFkChecksVal, tableName, colaValue, colbValue, idValue) } return fmt.Sprintf("update %v%v set cola = %v, colb = %v order by id limit %v", setVarFkChecksVal, tableName, colaValue, colbValue, limitCount) } else { - colValue := fz.generateExpression(rand.Intn(4)+1, "cola", "colb", "id") - colToUpdate := []string{"cola", "colb"}[rand.Intn(2)] + colValue := fz.generateExpression(rand.IntN(4)+1, "cola", "colb", "id") + colToUpdate := []string{"cola", "colb"}[rand.IntN(2)] if updWithLimit == 0 { return fmt.Sprintf("update %v set %v = %v where id = %v", tableName, colToUpdate, colValue, idValue) } return fmt.Sprintf("update %v set %v = %v order by id limit %v", tableName, colToUpdate, colValue, limitCount) } } else { - colValue := fz.generateExpression(rand.Intn(4)+1, "col", "id") + colValue := fz.generateExpression(rand.IntN(4)+1, "col", "id") if updWithLimit == 0 { return fmt.Sprintf("update %v%v set col = %v where id = %v", setVarFkChecksVal, tableName, colValue, idValue) } @@ -197,22 +197,22 @@ func (fz *fuzzer) generateUpdateDMLQuery() string { // generateDeleteDMLQuery generates a DELETE query using 1 table from the parameters for the fuzzer. func (fz *fuzzer) generateSingleDeleteDMLQuery() string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) setVarFkChecksVal := fz.getSetVarFkChecksVal() - delWithLimit := rand.Intn(2) + delWithLimit := rand.IntN(2) if delWithLimit == 0 { return fmt.Sprintf("delete %vfrom %v where id = %v", setVarFkChecksVal, fkTables[tableId], idValue) } - limitCount := rand.Intn(3) + limitCount := rand.IntN(3) return fmt.Sprintf("delete %vfrom %v order by id limit %v", setVarFkChecksVal, fkTables[tableId], limitCount) } // generateMultiDeleteDMLQuery generates a DELETE query using 2 tables from the parameters for the fuzzer. func (fz *fuzzer) generateMultiDeleteDMLQuery() string { - tableId := rand.Intn(len(fkTables)) - tableId2 := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + tableId2 := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) setVarFkChecksVal := fz.getSetVarFkChecksVal() query := fmt.Sprintf("delete %v%v from %v join %v using (id) where %v.id = %v", setVarFkChecksVal, fkTables[tableId], fkTables[tableId], fkTables[tableId2], fkTables[tableId], idValue) return query @@ -220,7 +220,7 @@ func (fz *fuzzer) generateMultiDeleteDMLQuery() string { // generateDeleteDMLQuery generates a DELETE query from the parameters for the fuzzer. func (fz *fuzzer) generateDeleteDMLQuery() string { - multiTableDelete := rand.Intn(2) + 1 + multiTableDelete := rand.IntN(2) + 1 if multiTableDelete == 1 { return fz.generateSingleDeleteDMLQuery() } @@ -374,8 +374,8 @@ func (fz *fuzzer) stop() { // getPreparedDeleteQueries gets the list of queries to run for executing an DELETE using prepared statements. func (fz *fuzzer) getPreparedDeleteQueries() []string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) return []string{ fmt.Sprintf("prepare stmt_del from 'delete from %v where id = ?'", fkTables[tableId]), fmt.Sprintf("SET @id = %v", idValue), @@ -385,12 +385,12 @@ func (fz *fuzzer) getPreparedDeleteQueries() []string { // getPreparedInsertQueries gets the list of queries to run for executing an INSERT using prepared statements. func (fz *fuzzer) getPreparedInsertQueries(insertType string) []string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] if tableName == "fk_t20" { - colValue := rand.Intn(1 + fz.maxValForCol) - col2Value := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) + col2Value := rand.IntN(1 + fz.maxValForCol) return []string{ fmt.Sprintf("prepare stmt_insert from '%s into fk_t20 (id, col, col2) values (?, ?, ?)'", insertType), fmt.Sprintf("SET @id = %v", idValue), @@ -399,8 +399,8 @@ func (fz *fuzzer) getPreparedInsertQueries(insertType string) []string { "execute stmt_insert using @id, @col, @col2", } } else if isMultiColFkTable(tableName) { - colaValue := rand.Intn(1 + fz.maxValForCol) - colbValue := rand.Intn(1 + fz.maxValForCol) + colaValue := rand.IntN(1 + fz.maxValForCol) + colbValue := rand.IntN(1 + fz.maxValForCol) return []string{ fmt.Sprintf("prepare stmt_insert from '%s into %v (id, cola, colb) values (?, ?, ?)'", insertType, tableName), fmt.Sprintf("SET @id = %v", idValue), @@ -409,7 +409,7 @@ func (fz *fuzzer) getPreparedInsertQueries(insertType string) []string { "execute stmt_insert using @id, @cola, @colb", } } else { - colValue := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) return []string{ fmt.Sprintf("prepare stmt_insert from '%s into %v (id, col) values (?, ?)'", insertType, tableName), fmt.Sprintf("SET @id = %v", idValue), @@ -421,12 +421,12 @@ func (fz *fuzzer) getPreparedInsertQueries(insertType string) []string { // getPreparedUpdateQueries gets the list of queries to run for executing an UPDATE using prepared statements. func (fz *fuzzer) getPreparedUpdateQueries() []string { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] if tableName == "fk_t20" { - colValue := rand.Intn(1 + fz.maxValForCol) - col2Value := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) + col2Value := rand.IntN(1 + fz.maxValForCol) return []string{ "prepare stmt_update from 'update fk_t20 set col = ?, col2 = ? where id = ?'", fmt.Sprintf("SET @id = %v", idValue), @@ -435,8 +435,8 @@ func (fz *fuzzer) getPreparedUpdateQueries() []string { "execute stmt_update using @col, @col2, @id", } } else if isMultiColFkTable(tableName) { - colaValue := rand.Intn(1 + fz.maxValForCol) - colbValue := rand.Intn(1 + fz.maxValForCol) + colaValue := rand.IntN(1 + fz.maxValForCol) + colbValue := rand.IntN(1 + fz.maxValForCol) return []string{ fmt.Sprintf("prepare stmt_update from 'update %v set cola = ?, colb = ? where id = ?'", tableName), fmt.Sprintf("SET @id = %v", idValue), @@ -445,7 +445,7 @@ func (fz *fuzzer) getPreparedUpdateQueries() []string { "execute stmt_update using @cola, @colb, @id", } } else { - colValue := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) return []string{ fmt.Sprintf("prepare stmt_update from 'update %v set col = ? where id = ?'", tableName), fmt.Sprintf("SET @id = %v", idValue), @@ -457,7 +457,7 @@ func (fz *fuzzer) getPreparedUpdateQueries() []string { // generateParameterizedQuery generates a parameterized query for the query format PreparedStatementPacket. func (fz *fuzzer) generateParameterizedQuery() (query string, params []any) { - val := rand.Intn(fz.insertShare + fz.updateShare + fz.deleteShare) + val := rand.IntN(fz.insertShare + fz.updateShare + fz.deleteShare) if val < fz.insertShare { return fz.generateParameterizedInsertQuery(getInsertType()) } @@ -469,46 +469,46 @@ func (fz *fuzzer) generateParameterizedQuery() (query string, params []any) { // generateParameterizedInsertQuery generates a parameterized INSERT query for the query format PreparedStatementPacket. func (fz *fuzzer) generateParameterizedInsertQuery(insertType string) (query string, params []any) { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] if tableName == "fk_t20" { - colValue := rand.Intn(1 + fz.maxValForCol) - col2Value := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) + col2Value := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s into %v (id, col, col2) values (?, ?, ?)", insertType, tableName), []any{idValue, convertIntValueToString(colValue), convertIntValueToString(col2Value)} } else if isMultiColFkTable(tableName) { - colaValue := rand.Intn(1 + fz.maxValForCol) - colbValue := rand.Intn(1 + fz.maxValForCol) + colaValue := rand.IntN(1 + fz.maxValForCol) + colbValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s into %v (id, cola, colb) values (?, ?, ?)", insertType, tableName), []any{idValue, convertIntValueToString(colaValue), convertIntValueToString(colbValue)} } else { - colValue := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("%s into %v (id, col) values (?, ?)", insertType, tableName), []any{idValue, convertIntValueToString(colValue)} } } // generateParameterizedUpdateQuery generates a parameterized UPDATE query for the query format PreparedStatementPacket. func (fz *fuzzer) generateParameterizedUpdateQuery() (query string, params []any) { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) tableName := fkTables[tableId] if tableName == "fk_t20" { - colValue := rand.Intn(1 + fz.maxValForCol) - col2Value := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) + col2Value := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("update %v set col = ?, col2 = ? where id = ?", tableName), []any{convertIntValueToString(colValue), convertIntValueToString(col2Value), idValue} } else if isMultiColFkTable(tableName) { - colaValue := rand.Intn(1 + fz.maxValForCol) - colbValue := rand.Intn(1 + fz.maxValForCol) + colaValue := rand.IntN(1 + fz.maxValForCol) + colbValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("update %v set cola = ?, colb = ? where id = ?", tableName), []any{convertIntValueToString(colaValue), convertIntValueToString(colbValue), idValue} } else { - colValue := rand.Intn(1 + fz.maxValForCol) + colValue := rand.IntN(1 + fz.maxValForCol) return fmt.Sprintf("update %v set col = ? where id = ?", tableName), []any{convertIntValueToString(colValue), idValue} } } // generateParameterizedDeleteQuery generates a parameterized DELETE query for the query format PreparedStatementPacket. func (fz *fuzzer) generateParameterizedDeleteQuery() (query string, params []any) { - tableId := rand.Intn(len(fkTables)) - idValue := 1 + rand.Intn(fz.maxValForId) + tableId := rand.IntN(len(fkTables)) + idValue := 1 + rand.IntN(fz.maxValForId) return fmt.Sprintf("delete from %v where id = ?", fkTables[tableId]), []any{idValue} } @@ -517,7 +517,7 @@ func (fz *fuzzer) getSetVarFkChecksVal() string { if fz.concurrency != 1 || fz.noFkSetVar { return "" } - val := rand.Intn(3) + val := rand.IntN(3) if val == 0 { return "" } diff --git a/go/test/endtoend/vtgate/foreignkey/stress/fk_stress_test.go b/go/test/endtoend/vtgate/foreignkey/stress/fk_stress_test.go index 175314a8fed..73baad2615b 100644 --- a/go/test/endtoend/vtgate/foreignkey/stress/fk_stress_test.go +++ b/go/test/endtoend/vtgate/foreignkey/stress/fk_stress_test.go @@ -20,7 +20,7 @@ import ( "context" "flag" "fmt" - "math/rand" + "math/rand/v2" "os" "path" "runtime" @@ -1005,8 +1005,8 @@ func isFKError(err error) bool { } func generateInsert(t *testing.T, tableName string, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) - parentId := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) + parentId := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(insertRowStatement, tableName, id, parentId) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1036,11 +1036,11 @@ func generateInsert(t *testing.T, tableName string, conn *mysql.Conn) error { func generateUpdate(t *testing.T, tableName string, conn *mysql.Conn) error { // Most of the UPDATEs we run are "normal" updates, but the minority will actually change the // `id` column itself, which is the FOREIGN KEY parent column for some of the tables. - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(updateRowStatement, tableName, id) if tableName == parentTableName || tableName == childTableName { - if rand.Intn(4) == 0 { - updatedId := rand.Int31n(int32(maxTableRows)) + if rand.IntN(4) == 0 { + updatedId := rand.Int32N(int32(maxTableRows)) query = fmt.Sprintf(updateRowIdStatement, tableName, updatedId, id) } } @@ -1070,7 +1070,7 @@ func generateUpdate(t *testing.T, tableName string, conn *mysql.Conn) error { } func generateDelete(t *testing.T, tableName string, conn *mysql.Conn) error { - id := rand.Int31n(int32(maxTableRows)) + id := rand.Int32N(int32(maxTableRows)) query := fmt.Sprintf(deleteRowStatement, tableName, id) qr, err := conn.ExecuteFetch(query, 1000, true) @@ -1109,7 +1109,7 @@ func runSingleConnection(ctx context.Context, t *testing.T, tableName string, sl require.Nil(t, err) for { - switch rand.Int31n(3) { + switch rand.Int32N(3) { case 0: _ = generateInsert(t, tableName, conn) case 1: diff --git a/go/test/endtoend/vtgate/foreignkey/utils_test.go b/go/test/endtoend/vtgate/foreignkey/utils_test.go index 9d4c53145b0..39267e9234a 100644 --- a/go/test/endtoend/vtgate/foreignkey/utils_test.go +++ b/go/test/endtoend/vtgate/foreignkey/utils_test.go @@ -20,7 +20,7 @@ import ( "context" "database/sql" "fmt" - "math/rand" + "math/rand/v2" "slices" "strings" "testing" @@ -55,16 +55,16 @@ func (fz *fuzzer) generateExpression(length int, cols ...string) string { return expr } rhsExpr := fz.generateExpression(length-1, cols...) - op := supportedOpps[rand.Intn(len(supportedOpps))] + op := supportedOpps[rand.IntN(len(supportedOpps))] return fmt.Sprintf("%v %s (%v)", expr, op, rhsExpr) } // getColOrInt gets a column or an integer/NULL literal with equal probability. func (fz *fuzzer) getColOrInt(cols ...string) string { - if len(cols) == 0 || rand.Intn(2) == 0 { - return convertIntValueToString(rand.Intn(1 + fz.maxValForCol)) + if len(cols) == 0 || rand.IntN(2) == 0 { + return convertIntValueToString(rand.IntN(1 + fz.maxValForCol)) } - return cols[rand.Intn(len(cols))] + return cols[rand.IntN(len(cols))] } // convertIntValueToString converts the given value to a string diff --git a/go/test/endtoend/vtgate/queries/benchmark/benchmark_test.go b/go/test/endtoend/vtgate/queries/benchmark/benchmark_test.go index 3fd7edd14de..5ebb8c5e422 100644 --- a/go/test/endtoend/vtgate/queries/benchmark/benchmark_test.go +++ b/go/test/endtoend/vtgate/queries/benchmark/benchmark_test.go @@ -18,7 +18,7 @@ package dml import ( "fmt" - "math/rand" + "math/rand/v2" "strconv" "strings" "testing" @@ -52,7 +52,7 @@ func getRandomString(size int) string { var str strings.Builder for i := 0; i < size; i++ { - str.WriteByte(byte(rand.Intn(27) + 97)) + str.WriteByte(byte(rand.IntN(27) + 97)) } return str.String() } diff --git a/go/test/endtoend/vtgate/queries/kill/main_test.go b/go/test/endtoend/vtgate/queries/kill/main_test.go index cc74be24336..99608030246 100644 --- a/go/test/endtoend/vtgate/queries/kill/main_test.go +++ b/go/test/endtoend/vtgate/queries/kill/main_test.go @@ -21,7 +21,7 @@ import ( _ "embed" "flag" "fmt" - "math/rand" + "math/rand/v2" "os" "strconv" "strings" diff --git a/go/test/endtoend/vtgate/queries/random/query_gen.go b/go/test/endtoend/vtgate/queries/random/query_gen.go index 3f8fccb05bb..1974386c360 100644 --- a/go/test/endtoend/vtgate/queries/random/query_gen.go +++ b/go/test/endtoend/vtgate/queries/random/query_gen.go @@ -18,7 +18,7 @@ package random import ( "fmt" - "math/rand" + "math/rand/v2" "slices" "vitess.io/vitess/go/slice" @@ -36,7 +36,6 @@ const testFailingQueries = false type ( // selectGenerator generates select statements selectGenerator struct { - r *rand.Rand genConfig sqlparser.ExprGeneratorConfig maxTables int maxAggrs int @@ -74,19 +73,18 @@ var _ sqlparser.ExprGenerator = (*column)(nil) var _ sqlparser.QueryGenerator = (*selectGenerator)(nil) var _ sqlparser.QueryGenerator = (*queryGenerator)(nil) -func newQueryGenerator(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig, maxTables, maxAggrs, maxGBs int, schemaTables []tableT) *queryGenerator { +func newQueryGenerator(genConfig sqlparser.ExprGeneratorConfig, maxTables, maxAggrs, maxGBs int, schemaTables []tableT) *queryGenerator { return &queryGenerator{ - selGen: newSelectGenerator(r, genConfig, maxTables, maxAggrs, maxGBs, schemaTables), + selGen: newSelectGenerator(genConfig, maxTables, maxAggrs, maxGBs, schemaTables), } } -func newSelectGenerator(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig, maxTables, maxAggrs, maxGBs int, schemaTables []tableT) *selectGenerator { +func newSelectGenerator(genConfig sqlparser.ExprGeneratorConfig, maxTables, maxAggrs, maxGBs int, schemaTables []tableT) *selectGenerator { if maxTables <= 0 { log.Fatalf("maxTables must be at least 1, currently %d\n", maxTables) } return &selectGenerator{ - r: r, genConfig: genConfig, maxTables: maxTables, maxAggrs: maxAggrs, @@ -140,7 +138,7 @@ func (t *tableT) clone() *tableT { } } -func (c *column) Generate(_ *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { +func (c *column) Generate(genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { if c.typ == genConfig.Type || genConfig.Type == "" { return c.getASTExpr() } @@ -148,11 +146,11 @@ func (c *column) Generate(_ *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) return nil } -func (t *tableT) Generate(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { +func (t *tableT) Generate(genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { colsCopy := slices.Clone(t.cols) for len(colsCopy) > 0 { - idx := r.Intn(len(colsCopy)) + idx := rand.IntN(len(colsCopy)) randCol := colsCopy[idx] if randCol.typ == genConfig.Type || genConfig.Type == "" { return randCol.getASTExpr() @@ -168,26 +166,26 @@ func (t *tableT) Generate(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) // Generate generates a subquery based on sg // TODO: currently unused; generate random expressions with union -func (sg *selectGenerator) Generate(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { +func (sg *selectGenerator) Generate(genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { var schemaTablesCopy []tableT for _, tbl := range sg.schemaTables { schemaTablesCopy = append(schemaTablesCopy, *tbl.clone()) } - newSG := newQueryGenerator(r, genConfig, sg.maxTables, sg.maxAggrs, sg.maxGBs, schemaTablesCopy) + newSG := newQueryGenerator(genConfig, sg.maxTables, sg.maxAggrs, sg.maxGBs, schemaTablesCopy) newSG.randomQuery() return &sqlparser.Subquery{Select: newSG.selGen.sel} } // Generate generates a subquery based on qg -func (qg *queryGenerator) Generate(r *rand.Rand, genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { +func (qg *queryGenerator) Generate(genConfig sqlparser.ExprGeneratorConfig) sqlparser.Expr { var schemaTablesCopy []tableT for _, tbl := range qg.selGen.schemaTables { schemaTablesCopy = append(schemaTablesCopy, *tbl.clone()) } - newQG := newQueryGenerator(r, genConfig, qg.selGen.maxTables, qg.selGen.maxAggrs, qg.selGen.maxGBs, schemaTablesCopy) + newQG := newQueryGenerator(genConfig, qg.selGen.maxTables, qg.selGen.maxAggrs, qg.selGen.maxGBs, schemaTablesCopy) newQG.randomQuery() return &sqlparser.Subquery{Select: newQG.stmt} @@ -197,7 +195,7 @@ func (sg *selectGenerator) IsQueryGenerator() {} func (qg *queryGenerator) IsQueryGenerator() {} func (qg *queryGenerator) randomQuery() { - if qg.selGen.r.Intn(10) < 1 && testFailingQueries { + if rand.IntN(10) < 1 && testFailingQueries { qg.createUnion() } else { qg.selGen.randomSelect() @@ -209,12 +207,12 @@ func (qg *queryGenerator) randomQuery() { func (qg *queryGenerator) createUnion() { union := &sqlparser.Union{} - if qg.selGen.r.Intn(2) < 1 { + if rand.IntN(2) < 1 { union.Distinct = true } // specify between 1-4 columns - qg.selGen.genConfig.NumCols = qg.selGen.r.Intn(4) + 1 + qg.selGen.genConfig.NumCols = rand.IntN(4) + 1 qg.randomQuery() union.Left = qg.stmt @@ -232,7 +230,7 @@ func (sg *selectGenerator) randomSelect() { sg.sel.SetComments(sqlparser.Comments{"/*vt+ PLANNER=Gen4 */"}) // select distinct (fails with group by bigint) - isDistinct := sg.r.Intn(2) < 1 + isDistinct := rand.IntN(2) < 1 if isDistinct { sg.sel.MakeDistinct() } @@ -242,7 +240,7 @@ func (sg *selectGenerator) randomSelect() { // canAggregate determines if the query will have // aggregate columns, group by, and having - canAggregate := sg.r.Intn(4) < 3 + canAggregate := rand.IntN(4) < 3 var ( grouping, aggregates []column @@ -258,7 +256,7 @@ func (sg *selectGenerator) randomSelect() { } // having - isHaving := sg.r.Intn(2) < 1 + isHaving := rand.IntN(2) < 1 // TODO: having creates a lot of results mismatched if isHaving && testFailingQueries { sg.createHavingPredicates(grouping) @@ -280,7 +278,7 @@ func (sg *selectGenerator) randomSelect() { // add random expression to select // TODO: random expressions cause a lot of failures - isRandomExpr := sg.r.Intn(2) < 1 && testFailingQueries + isRandomExpr := rand.IntN(2) < 1 && testFailingQueries // TODO: selecting a random expression potentially with columns creates // TODO: only_full_group_by related errors in Vitess @@ -288,7 +286,7 @@ func (sg *selectGenerator) randomSelect() { if canAggregate && testFailingQueries { exprGenerators = slice.Map(tables, func(t tableT) sqlparser.ExprGenerator { return &t }) // add scalar subqueries - if sg.r.Intn(10) < 1 { + if rand.IntN(10) < 1 { exprGenerators = append(exprGenerators, sg) } } @@ -325,14 +323,14 @@ func (sg *selectGenerator) randomSelect() { // can add both aggregate and grouping columns to order by // TODO: order fails with distinct and outer joins - isOrdered := sg.r.Intn(2) < 1 && (!isDistinct || testFailingQueries) && (!isJoin || testFailingQueries) + isOrdered := rand.IntN(2) < 1 && (!isDistinct || testFailingQueries) && (!isJoin || testFailingQueries) if isOrdered || (!canAggregate && sg.genConfig.SingleRow) /* TODO: might be redundant */ { sg.createOrderBy() } // only add a limit if there is an ordering // TODO: limit fails a lot - isLimit := sg.r.Intn(2) < 1 && len(sg.sel.OrderBy) > 0 && testFailingQueries + isLimit := rand.IntN(2) < 1 && len(sg.sel.OrderBy) > 0 && testFailingQueries if isLimit || (!canAggregate && sg.genConfig.SingleRow) /* TODO: might be redundant */ { sg.createLimit() } @@ -345,7 +343,7 @@ func (sg *selectGenerator) randomSelect() { sg.schemaTables = append(sg.schemaTables, newTable) // derived tables (partially unsupported) - if sg.r.Intn(10) < 1 { + if rand.IntN(10) < 1 { sg.randomSelect() } } @@ -353,24 +351,24 @@ func (sg *selectGenerator) randomSelect() { func (sg *selectGenerator) createTablesAndJoin() ([]tableT, bool) { var tables []tableT // add at least one of original emp/dept tables - tables = append(tables, sg.schemaTables[sg.r.Intn(2)]) + tables = append(tables, sg.schemaTables[rand.IntN(2)]) tables[0].setAlias("tbl0") sg.sel.From = append(sg.sel.From, newAliasedTable(tables[0], "tbl0")) - numTables := sg.r.Intn(sg.maxTables) + numTables := rand.IntN(sg.maxTables) for i := 0; i < numTables; i++ { - tables = append(tables, randomEl(sg.r, sg.schemaTables)) + tables = append(tables, randomEl(sg.schemaTables)) alias := fmt.Sprintf("tbl%d", i+1) sg.sel.From = append(sg.sel.From, newAliasedTable(tables[i+1], alias)) tables[i+1].setAlias(alias) } // TODO: outer joins produce results mismatched - isJoin := sg.r.Intn(2) < 1 && testFailingQueries + isJoin := rand.IntN(2) < 1 && testFailingQueries if isJoin { // TODO: do nested joins - newTable := randomEl(sg.r, sg.schemaTables) + newTable := randomEl(sg.schemaTables) alias := fmt.Sprintf("tbl%d", numTables+1) newTable.setAlias(alias) tables = append(tables, newTable) @@ -392,7 +390,7 @@ func (sg *selectGenerator) createJoin(tables []tableT) { joinPredicate := sqlparser.AndExpressions(sg.createJoinPredicates(tables)...) joinCondition := sqlparser.NewJoinCondition(joinPredicate, nil) newTable := newAliasedTable(tables[n], fmt.Sprintf("tbl%d", n)) - sg.sel.From[n-1] = sqlparser.NewJoinTableExpr(sg.sel.From[n-1], getRandomJoinType(sg.r), newTable, joinCondition) + sg.sel.From[n-1] = sqlparser.NewJoinTableExpr(sg.sel.From[n-1], getRandomJoinType(), newTable, joinCondition) } // returns 1-3 random expressions based on the last two elements of tables @@ -405,7 +403,7 @@ func (sg *selectGenerator) createJoinPredicates(tables []tableT) sqlparser.Exprs exprGenerators := []sqlparser.ExprGenerator{&tables[len(tables)-2], &tables[len(tables)-1]} // add scalar subqueries // TODO: subqueries fail - if sg.r.Intn(10) < 1 && testFailingQueries { + if rand.IntN(10) < 1 && testFailingQueries { exprGenerators = append(exprGenerators, sg) } @@ -417,10 +415,10 @@ func (sg *selectGenerator) createGroupBy(tables []tableT) (grouping []column) { if sg.maxGBs <= 0 { return } - numGBs := sg.r.Intn(sg.maxGBs + 1) + numGBs := rand.IntN(sg.maxGBs + 1) for i := 0; i < numGBs; i++ { - tblIdx := sg.r.Intn(len(tables)) - col := randomEl(sg.r, tables[tblIdx].cols) + tblIdx := rand.IntN(len(tables)) + col := randomEl(tables[tblIdx].cols) // TODO: grouping by a date column sometimes errors if col.typ == "date" && !testFailingQueries { continue @@ -428,7 +426,7 @@ func (sg *selectGenerator) createGroupBy(tables []tableT) (grouping []column) { sg.sel.GroupBy = append(sg.sel.GroupBy, col.getASTExpr()) // add to select - if sg.r.Intn(2) < 1 { + if rand.IntN(2) < 1 { sg.sel.SelectExprs = append(sg.sel.SelectExprs, newAliasedColumn(col, "")) grouping = append(grouping, col) } @@ -444,7 +442,7 @@ func (sg *selectGenerator) aliasGroupingColumns(grouping []column) []column { } for i := range grouping { - if sg.r.Intn(2) < 1 { + if rand.IntN(2) < 1 { if aliasedExpr, ok := sg.sel.SelectExprs[i].(*sqlparser.AliasedExpr); ok { alias := fmt.Sprintf("cgroup%d", i) aliasedExpr.SetAlias(alias) @@ -461,7 +459,7 @@ func (sg *selectGenerator) createAggregations(tables []tableT) (aggregates []col exprGenerators := slice.Map(tables, func(t tableT) sqlparser.ExprGenerator { return &t }) // add scalar subqueries // TODO: subqueries fail - if sg.r.Intn(10) < 1 && testFailingQueries { + if rand.IntN(10) < 1 && testFailingQueries { exprGenerators = append(exprGenerators, sg) } @@ -481,18 +479,18 @@ func (sg *selectGenerator) createAggregations(tables []tableT) (aggregates []col func (sg *selectGenerator) createOrderBy() { // always order on grouping expressions for _, expr := range sg.sel.GroupBy { - sg.sel.OrderBy = append(sg.sel.OrderBy, sqlparser.NewOrder(expr, getRandomOrderDirection(sg.r))) + sg.sel.OrderBy = append(sg.sel.OrderBy, sqlparser.NewOrder(expr, getRandomOrderDirection())) } // randomly order on SelectExprs for _, selExpr := range sg.sel.SelectExprs { - if aliasedExpr, ok := selExpr.(*sqlparser.AliasedExpr); ok && sg.r.Intn(2) < 1 { + if aliasedExpr, ok := selExpr.(*sqlparser.AliasedExpr); ok && rand.IntN(2) < 1 { literal, ok := aliasedExpr.Expr.(*sqlparser.Literal) isIntLiteral := ok && literal.Type == sqlparser.IntVal if isIntLiteral { continue } - sg.sel.OrderBy = append(sg.sel.OrderBy, sqlparser.NewOrder(aliasedExpr.Expr, getRandomOrderDirection(sg.r))) + sg.sel.OrderBy = append(sg.sel.OrderBy, sqlparser.NewOrder(aliasedExpr.Expr, getRandomOrderDirection())) } } } @@ -502,7 +500,7 @@ func (sg *selectGenerator) createWherePredicates(tables []tableT) { exprGenerators := slice.Map(tables, func(t tableT) sqlparser.ExprGenerator { return &t }) // add scalar subqueries // TODO: subqueries fail - if sg.r.Intn(10) < 1 && testFailingQueries { + if rand.IntN(10) < 1 && testFailingQueries { exprGenerators = append(exprGenerators, sg) } @@ -515,7 +513,7 @@ func (sg *selectGenerator) createHavingPredicates(grouping []column) { exprGenerators := slice.Map(grouping, func(c column) sqlparser.ExprGenerator { return &c }) // add scalar subqueries // TODO: subqueries fail - if sg.r.Intn(10) < 1 && testFailingQueries { + if rand.IntN(10) < 1 && testFailingQueries { exprGenerators = append(exprGenerators, sg) } @@ -533,7 +531,7 @@ func (sg *selectGenerator) createRandomExprs(minExprs, maxExprs int, generators } else if maxExprs <= 0 { return } - numPredicates := sg.r.Intn(maxExprs-minExprs+1) + minExprs + numPredicates := rand.IntN(maxExprs-minExprs+1) + minExprs for i := 0; i < numPredicates; i++ { predicates = append(predicates, sg.getRandomExpr(generators...)) } @@ -545,9 +543,9 @@ func (sg *selectGenerator) createRandomExprs(minExprs, maxExprs int, generators func (sg *selectGenerator) getRandomExpr(generators ...sqlparser.ExprGenerator) sqlparser.Expr { var g *sqlparser.Generator if generators == nil { - g = sqlparser.NewGenerator(sg.r, 2) + g = sqlparser.NewGenerator(2) } else { - g = sqlparser.NewGenerator(sg.r, 2, generators...) + g = sqlparser.NewGenerator(2, generators...) } return g.Expression(sg.genConfig.SingleRowConfig().SetNumCols(1)) @@ -560,9 +558,9 @@ func (sg *selectGenerator) createLimit() { return } - limitNum := sg.r.Intn(10) - if sg.r.Intn(2) < 1 { - offset := sg.r.Intn(10) + limitNum := rand.IntN(10) + if rand.IntN(2) < 1 { + offset := rand.IntN(10) sg.sel.Limit = sqlparser.NewLimit(offset, limitNum) } else { sg.sel.Limit = sqlparser.NewLimitWithoutOffset(limitNum) @@ -572,7 +570,7 @@ func (sg *selectGenerator) createLimit() { // randomlyAlias randomly aliases expr with alias alias, adds it to sel.SelectExprs, and returns the column created func (sg *selectGenerator) randomlyAlias(expr sqlparser.Expr, alias string) column { var col column - if sg.r.Intn(2) < 1 { + if rand.IntN(2) < 1 { alias = "" col.name = sqlparser.String(expr) } else { @@ -588,7 +586,7 @@ func (sg *selectGenerator) matchNumCols(tables []tableT, newTable tableT, canAgg // remove SelectExprs and newTable.cols randomly until there are sg.genConfig.NumCols amount for len(sg.sel.SelectExprs) > sg.genConfig.NumCols && sg.genConfig.NumCols > 0 { // select a random index and remove it from SelectExprs and newTable - idx := sg.r.Intn(len(sg.sel.SelectExprs)) + idx := rand.IntN(len(sg.sel.SelectExprs)) sg.sel.SelectExprs[idx] = sg.sel.SelectExprs[len(sg.sel.SelectExprs)-1] sg.sel.SelectExprs = sg.sel.SelectExprs[:len(sg.sel.SelectExprs)-1] @@ -616,18 +614,18 @@ func (sg *selectGenerator) matchNumCols(tables []tableT, newTable tableT, canAgg return newTable } -func getRandomOrderDirection(r *rand.Rand) sqlparser.OrderDirection { +func getRandomOrderDirection() sqlparser.OrderDirection { // asc, desc - return randomEl(r, []sqlparser.OrderDirection{0, 1}) + return randomEl([]sqlparser.OrderDirection{0, 1}) } -func getRandomJoinType(r *rand.Rand) sqlparser.JoinType { +func getRandomJoinType() sqlparser.JoinType { // normal, straight, left, right, natural, natural left, natural right - return randomEl(r, []sqlparser.JoinType{0, 1, 2, 3, 4, 5, 6}) + return randomEl([]sqlparser.JoinType{0, 1, 2, 3, 4, 5, 6}) } -func randomEl[K any](r *rand.Rand, in []K) K { - return in[r.Intn(len(in))] +func randomEl[K any](in []K) K { + return in[rand.IntN(len(in))] } func newAliasedTable(tbl tableT, alias string) *sqlparser.AliasedTableExpr { diff --git a/go/test/endtoend/vtgate/queries/random/query_gen_test.go b/go/test/endtoend/vtgate/queries/random/query_gen_test.go deleted file mode 100644 index fe8aa6f6492..00000000000 --- a/go/test/endtoend/vtgate/queries/random/query_gen_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2023 The Vitess Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package random - -import ( - "fmt" - "math/rand" - "testing" - - "github.com/stretchr/testify/require" - - "vitess.io/vitess/go/vt/sqlparser" -) - -// TestSeed makes sure that the seed is deterministic -func TestSeed(t *testing.T) { - // specify the schema (that is defined in schema.sql) - schemaTables := []tableT{ - {tableExpr: sqlparser.NewTableName("emp")}, - {tableExpr: sqlparser.NewTableName("dept")}, - } - schemaTables[0].addColumns([]column{ - {name: "empno", typ: "bigint"}, - {name: "ename", typ: "varchar"}, - {name: "job", typ: "varchar"}, - {name: "mgr", typ: "bigint"}, - {name: "hiredate", typ: "date"}, - {name: "sal", typ: "bigint"}, - {name: "comm", typ: "bigint"}, - {name: "deptno", typ: "bigint"}, - }...) - schemaTables[1].addColumns([]column{ - {name: "deptno", typ: "bigint"}, - {name: "dname", typ: "varchar"}, - {name: "loc", typ: "varchar"}, - }...) - - seed := int64(1689757943775102000) - genConfig := sqlparser.NewExprGeneratorConfig(sqlparser.CannotAggregate, "", 0, false) - qg := newQueryGenerator(rand.New(rand.NewSource(seed)), genConfig, 2, 2, 2, schemaTables) - qg.randomQuery() - query1 := sqlparser.String(qg.stmt) - qg = newQueryGenerator(rand.New(rand.NewSource(seed)), genConfig, 2, 2, 2, schemaTables) - qg.randomQuery() - query2 := sqlparser.String(qg.stmt) - fmt.Println(query1) - require.Equal(t, query1, query2) -} diff --git a/go/test/endtoend/vtgate/queries/random/random_expr_test.go b/go/test/endtoend/vtgate/queries/random/random_expr_test.go index 450169a8d9f..8de1896d0e3 100644 --- a/go/test/endtoend/vtgate/queries/random/random_expr_test.go +++ b/go/test/endtoend/vtgate/queries/random/random_expr_test.go @@ -17,9 +17,7 @@ limitations under the License. package random import ( - "math/rand" "testing" - "time" "vitess.io/vitess/go/slice" "vitess.io/vitess/go/vt/sqlparser" @@ -49,11 +47,8 @@ func TestRandomExprWithTables(t *testing.T) { }...) for i := 0; i < 100; i++ { - - seed := time.Now().UnixNano() - r := rand.New(rand.NewSource(seed)) genConfig := sqlparser.NewExprGeneratorConfig(sqlparser.CanAggregate, "", 0, false) - g := sqlparser.NewGenerator(r, 3, slice.Map(schemaTables, func(t tableT) sqlparser.ExprGenerator { return &t })...) + g := sqlparser.NewGenerator(3, slice.Map(schemaTables, func(t tableT) sqlparser.ExprGenerator { return &t })...) g.Expression(genConfig) } } diff --git a/go/test/endtoend/vtgate/queries/random/random_test.go b/go/test/endtoend/vtgate/queries/random/random_test.go index aea43c2f929..b3d6944cb56 100644 --- a/go/test/endtoend/vtgate/queries/random/random_test.go +++ b/go/test/endtoend/vtgate/queries/random/random_test.go @@ -18,7 +18,6 @@ package random import ( "fmt" - "math/rand" "strings" "testing" "time" @@ -258,16 +257,14 @@ func TestRandom(t *testing.T) { var queryCount, queryFailCount int // continue testing after an error if and only if testFailingQueries is true for time.Now().Before(endBy) && (!t.Failed() || !testFailingQueries) { - seed := time.Now().UnixNano() genConfig := sqlparser.NewExprGeneratorConfig(sqlparser.CannotAggregate, "", 0, false) - qg := newQueryGenerator(rand.New(rand.NewSource(seed)), genConfig, 2, 2, 2, schemaTables) + qg := newQueryGenerator(genConfig, 2, 2, 2, schemaTables) qg.randomQuery() query := sqlparser.String(qg.stmt) _, vtErr := mcmp.ExecAllowAndCompareError(query) // this assumes all queries are valid mysql queries if vtErr != nil { - fmt.Printf("seed: %d\n", seed) fmt.Println(query) fmt.Println(vtErr) diff --git a/go/test/stress/stress.go b/go/test/stress/stress.go index 1346e3afa55..2f0ecdc751f 100644 --- a/go/test/stress/stress.go +++ b/go/test/stress/stress.go @@ -18,7 +18,7 @@ package stress import ( "fmt" - "math/rand" + "math/rand/v2" "sync" "sync/atomic" "testing" diff --git a/go/timer/randticker.go b/go/timer/randticker.go index 17ab08526d6..8e921f40fea 100644 --- a/go/timer/randticker.go +++ b/go/timer/randticker.go @@ -17,7 +17,7 @@ limitations under the License. package timer import ( - "math/rand" + "math/rand/v2" "time" ) @@ -35,9 +35,8 @@ func NewRandTicker(d, variance time.Duration) *RandTicker { c := make(chan time.Time, 1) done := make(chan struct{}) go func() { - rnd := rand.New(rand.NewSource(time.Now().UnixNano())) for { - vr := time.Duration(rnd.Int63n(int64(2*variance)) - int64(variance)) + vr := time.Duration(rand.Int64N(int64(2*variance)) - int64(variance)) tmr := time.NewTimer(d + vr) select { case <-tmr.C: diff --git a/go/viperutil/internal/sync/sync_internal_test.go b/go/viperutil/internal/sync/sync_internal_test.go index cc8a163fa18..3c84913c7ce 100644 --- a/go/viperutil/internal/sync/sync_internal_test.go +++ b/go/viperutil/internal/sync/sync_internal_test.go @@ -19,7 +19,7 @@ package sync import ( "context" "encoding/json" - "math/rand" + "math/rand/v2" "testing" "time" @@ -132,5 +132,5 @@ func TestPersistConfig(t *testing.T) { } func jitter(min, max int) int { - return min + rand.Intn(max-min+1) + return min + rand.IntN(max-min+1) } diff --git a/go/viperutil/internal/sync/sync_test.go b/go/viperutil/internal/sync/sync_test.go index 6b8efa1b105..750baa053ea 100644 --- a/go/viperutil/internal/sync/sync_test.go +++ b/go/viperutil/internal/sync/sync_test.go @@ -19,7 +19,7 @@ package sync_test import ( "context" "encoding/json" - "math/rand" + "math/rand/v2" "os" "sync" "testing" @@ -53,7 +53,7 @@ func TestWatchConfig(t *testing.T) { return atomicWrite(tmp.Name(), data) } writeRandomConfig := func(tmp *os.File) error { - a, b := rand.Intn(100), rand.Intn(100) + a, b := rand.IntN(100), rand.IntN(100) return writeConfig(tmp, a, b) } @@ -155,5 +155,5 @@ func TestWatchConfig(t *testing.T) { } func jitter(min, max int) int { - return min + rand.Intn(max-min+1) + return min + rand.IntN(max-min+1) } diff --git a/go/vt/discovery/tablet_picker.go b/go/vt/discovery/tablet_picker.go index d81dcf01354..4cfb6020fe6 100644 --- a/go/vt/discovery/tablet_picker.go +++ b/go/vt/discovery/tablet_picker.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "sort" "strings" "sync" @@ -298,7 +298,7 @@ func (tp *TabletPicker) orderByTabletType(candidates []*topo.TabletInfo) []*topo sort.Slice(candidates, func(i, j int) bool { if orderMap[candidates[i].Type] == orderMap[candidates[j].Type] { // identical tablet types: randomize order of tablets for this type - return rand.Intn(2) == 0 // 50% chance + return rand.IntN(2) == 0 // 50% chance } return orderMap[candidates[i].Type] < orderMap[candidates[j].Type] }) diff --git a/go/vt/discovery/topology_watcher_test.go b/go/vt/discovery/topology_watcher_test.go index bdf2c2dd2da..0a7c96358a2 100644 --- a/go/vt/discovery/topology_watcher_test.go +++ b/go/vt/discovery/topology_watcher_test.go @@ -18,7 +18,7 @@ package discovery import ( "context" - "math/rand" + "math/rand/v2" "testing" "time" @@ -399,7 +399,7 @@ func TestFilterByKeyspace(t *testing.T) { for _, test := range testFilterByKeyspace { // Add a new tablet to the topology. - port := rand.Int31n(1000) + port := rand.Int32N(1000) tablet := &topodatapb.Tablet{ Alias: &topodatapb.TabletAlias{ Cell: testCell, diff --git a/go/vt/key/destination.go b/go/vt/key/destination.go index 6b8f145390b..77287c782e7 100644 --- a/go/vt/key/destination.go +++ b/go/vt/key/destination.go @@ -18,7 +18,7 @@ package key import ( "encoding/hex" - "math/rand" + "math/rand/v2" "sort" "strings" @@ -274,7 +274,7 @@ type DestinationAnyShardPickerRandomShard struct{} // PickShard is DestinationAnyShardPickerRandomShard's implementation. func (dp DestinationAnyShardPickerRandomShard) PickShard(shardCount int) int { - return rand.Intn(shardCount) + return rand.IntN(shardCount) } // diff --git a/go/vt/mysqlctl/xtrabackupengine_test.go b/go/vt/mysqlctl/xtrabackupengine_test.go index 7a829ce4ba0..84230c54520 100644 --- a/go/vt/mysqlctl/xtrabackupengine_test.go +++ b/go/vt/mysqlctl/xtrabackupengine_test.go @@ -18,8 +18,8 @@ package mysqlctl import ( "bytes" + "crypto/rand" "io" - "math/rand" "testing" "github.com/stretchr/testify/assert" @@ -77,11 +77,10 @@ func TestFindReplicationPositionEmptyMatch(t *testing.T) { } func TestStripeRoundTrip(t *testing.T) { - // Generate some deterministic input data. + // Generate some random input data. dataSize := int64(1000000) input := make([]byte, dataSize) - rng := rand.New(rand.NewSource(1)) - rng.Read(input) + rand.Read(input) test := func(blockSize int64, stripes int) { // Write it out striped across some buffers. diff --git a/go/vt/schemadiff/schema_test.go b/go/vt/schemadiff/schema_test.go index 4e3440830f4..7eab685f0d7 100644 --- a/go/vt/schemadiff/schema_test.go +++ b/go/vt/schemadiff/schema_test.go @@ -18,7 +18,7 @@ package schemadiff import ( "fmt" - "math/rand" + "math/rand/v2" "sort" "strings" "testing" diff --git a/go/vt/sqlparser/normalizer_test.go b/go/vt/sqlparser/normalizer_test.go index 18f2ad44a7f..42e26caa39d 100644 --- a/go/vt/sqlparser/normalizer_test.go +++ b/go/vt/sqlparser/normalizer_test.go @@ -18,7 +18,7 @@ package sqlparser import ( "fmt" - "math/rand" + "math/rand/v2" "reflect" "regexp" "strconv" @@ -616,9 +616,9 @@ func randtmpl(template string) string { for i, c := range result { switch c { case '#': - result[i] = numberBytes[rand.Intn(len(numberBytes))] + result[i] = numberBytes[rand.IntN(len(numberBytes))] case '@': - result[i] = letterBytes[rand.Intn(len(letterBytes))] + result[i] = letterBytes[rand.IntN(len(letterBytes))] } } return string(result) @@ -628,7 +628,7 @@ func randString(n int) string { const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" b := make([]byte, n) for i := range b { - b[i] = letterBytes[rand.Intn(len(letterBytes))] + b[i] = letterBytes[rand.IntN(len(letterBytes))] } return string(b) } @@ -648,14 +648,14 @@ func BenchmarkNormalizeTPCCInsert(b *testing.B) { for i := 0; i < rows; i++ { fmt.Fprintf(&query, "(%d, %d, %d, '%s','OE','%s','%s', '%s', '%s', '%s', '%s','%s',NOW(),'%s',50000,%f,-10,10,1,0,'%s' )", rand.Int(), rand.Int(), rand.Int(), - "first-"+randString(rand.Intn(10)), + "first-"+randString(rand.IntN(10)), randtmpl("last-@@@@"), randtmpl("street1-@@@@@@@@@@@@"), randtmpl("street2-@@@@@@@@@@@@"), randtmpl("city-@@@@@@@@@@@@"), randtmpl("@@"), randtmpl("zip-#####"), randtmpl("################"), - "GC", rand.Float64(), randString(300+rand.Intn(200)), + "GC", rand.Float64(), randString(300+rand.IntN(200)), ) if i < rows-1 { query.WriteString(", ") diff --git a/go/vt/sqlparser/parse_test.go b/go/vt/sqlparser/parse_test.go index 91cc3c13029..0ac9dda2c52 100644 --- a/go/vt/sqlparser/parse_test.go +++ b/go/vt/sqlparser/parse_test.go @@ -21,7 +21,7 @@ import ( "compress/gzip" "fmt" "io" - "math/rand" + "math/rand/v2" "os" "path" "strings" @@ -3813,7 +3813,7 @@ func TestParallelValid(t *testing.T) { go func() { defer wg.Done() for j := 0; j < numIters; j++ { - tcase := validSQL[rand.Intn(len(validSQL))] + tcase := validSQL[rand.IntN(len(validSQL))] if tcase.output == "" { tcase.output = tcase.input } diff --git a/go/vt/sqlparser/precedence_test.go b/go/vt/sqlparser/precedence_test.go index 774ada31dbd..0d29d8b87e3 100644 --- a/go/vt/sqlparser/precedence_test.go +++ b/go/vt/sqlparser/precedence_test.go @@ -18,7 +18,6 @@ package sqlparser import ( "fmt" - "math/rand" "testing" "time" @@ -175,10 +174,7 @@ func TestParens(t *testing.T) { func TestRandom(t *testing.T) { // The purpose of this test is to find discrepancies between Format and parsing. If for example our precedence rules are not consistent between the two, this test should find it. // The idea is to generate random queries, and pass them through the parser and then the unparser, and one more time. The result of the first unparse should be the same as the second result. - seed := time.Now().UnixNano() - r := rand.New(rand.NewSource(seed)) - fmt.Printf("seed is %d\n", seed) - g := NewGenerator(r, 5) + g := NewGenerator(5) endBy := time.Now().Add(1 * time.Second) parser := NewTestParser() diff --git a/go/vt/sqlparser/random_expr.go b/go/vt/sqlparser/random_expr.go index 6eed8145ed2..f5b394b36fe 100644 --- a/go/vt/sqlparser/random_expr.go +++ b/go/vt/sqlparser/random_expr.go @@ -18,7 +18,7 @@ package sqlparser import ( "fmt" - "math/rand" + "math/rand/v2" ) // This file is used to generate random expressions to be used for testing @@ -32,7 +32,7 @@ const ( type ( ExprGenerator interface { - Generate(r *rand.Rand, config ExprGeneratorConfig) Expr + Generate(config ExprGeneratorConfig) Expr } QueryGenerator interface { @@ -53,7 +53,6 @@ type ( } Generator struct { - r *rand.Rand depth int maxDepth int isAggregate bool @@ -120,9 +119,8 @@ func (egc ExprGeneratorConfig) IsAggregateConfig() ExprGeneratorConfig { return egc } -func NewGenerator(r *rand.Rand, maxDepth int, exprGenerators ...ExprGenerator) *Generator { +func NewGenerator(maxDepth int, exprGenerators ...ExprGenerator) *Generator { g := Generator{ - r: r, maxDepth: maxDepth, exprGenerators: exprGenerators, } @@ -190,7 +188,7 @@ func (g *Generator) Expression(genConfig ExprGeneratorConfig) Expr { // don't create expressions from the expression exprGenerators if we haven't created an aggregation yet if _, ok := generator.(QueryGenerator); ok || genConfig.AggrRule != IsAggregate { options = append(options, func() Expr { - expr := generator.Generate(g.r, genConfig) + expr := generator.Generate(genConfig) if expr == nil { return g.randomLiteral() } @@ -208,7 +206,7 @@ func (g *Generator) Expression(genConfig ExprGeneratorConfig) Expr { // if an arbitrary number of columns may be generated, randomly choose 1-3 columns if numCols == 0 { - numCols = g.r.Intn(3) + 1 + numCols = rand.IntN(3) + 1 } if numCols == 1 { @@ -244,7 +242,7 @@ func (g *Generator) makeAggregateIfNecessary(genConfig ExprGeneratorConfig, expr } func (g *Generator) randomAggregate(genConfig ExprGeneratorConfig) Expr { - isDistinct := g.r.Intn(10) < 1 + isDistinct := rand.IntN(10) < 1 options := []exprF{ func() Expr { return &CountStar{} }, @@ -324,7 +322,7 @@ func (g *Generator) subqueryExpr(genConfig ExprGeneratorConfig) Expr { for _, generator := range g.exprGenerators { if qg, ok := generator.(QueryGenerator); ok { options = append(options, func() Expr { - expr := qg.Generate(g.r, genConfig) + expr := qg.Generate(genConfig) if expr == nil { return g.randomTupleLiteral(genConfig) } @@ -342,7 +340,7 @@ func (g *Generator) subqueryExpr(genConfig ExprGeneratorConfig) Expr { func (g *Generator) randomTupleLiteral(genConfig ExprGeneratorConfig) Expr { if genConfig.NumCols == 0 { - genConfig.NumCols = g.r.Intn(3) + 1 + genConfig.NumCols = rand.IntN(3) + 1 } tuple := ValTuple{} @@ -372,11 +370,11 @@ func (g *Generator) randomBool(prob float32) bool { if prob < 0 || prob > 1 { prob = 0.5 } - return g.r.Float32() < prob + return rand.Float32() < prob } func (g *Generator) intLiteral() Expr { - t := fmt.Sprintf("%d", g.r.Intn(100)-g.r.Intn(100)) + t := fmt.Sprintf("%d", rand.IntN(100)-rand.IntN(100)) //nolint SA4000 return NewIntLiteral(t) } @@ -404,10 +402,10 @@ func (g *Generator) comparison(genConfig ExprGeneratorConfig) Expr { defer g.exit() // specifc 1-3 columns - numCols := g.r.Intn(3) + 1 + numCols := rand.IntN(3) + 1 cmp := &ComparisonExpr{ - Operator: comparisonOps[g.r.Intn(len(comparisonOps))], + Operator: comparisonOps[rand.IntN(len(comparisonOps))], Left: g.Expression(genConfig.SetNumCols(numCols)), Right: g.Expression(genConfig.SetNumCols(numCols)), } @@ -427,7 +425,7 @@ func (g *Generator) caseExpr(genConfig ExprGeneratorConfig) Expr { elseExpr = g.Expression(genConfig) } - size := g.r.Intn(2) + 1 + size := rand.IntN(2) + 1 var whens []*When for i := 0; i < size; i++ { var cond Expr @@ -457,7 +455,7 @@ func (g *Generator) arithmetic(genConfig ExprGeneratorConfig) Expr { g.enter() defer g.exit() - op := arithmeticOps[g.r.Intn(len(arithmeticOps))] + op := arithmeticOps[rand.IntN(len(arithmeticOps))] return &BinaryExpr{ Operator: op, @@ -469,11 +467,11 @@ func (g *Generator) arithmetic(genConfig ExprGeneratorConfig) Expr { type exprF func() Expr func (g *Generator) randomOf(options []exprF) Expr { - return options[g.r.Intn(len(options))]() + return options[rand.IntN(len(options))]() } func (g *Generator) randomOfS(options []string) string { - return options[g.r.Intn(len(options))] + return options[rand.IntN(len(options))] } func (g *Generator) andExpr(genConfig ExprGeneratorConfig) Expr { @@ -513,7 +511,7 @@ func (g *Generator) inExpr(genConfig ExprGeneratorConfig) Expr { g.enter() defer g.exit() - size := g.r.Intn(3) + 2 + size := rand.IntN(3) + 2 inExprGenConfig := NewExprGeneratorConfig(genConfig.AggrRule, "", size, true) tuple1 := g.Expression(inExprGenConfig) tuple2 := ValTuple{g.Expression(inExprGenConfig)} @@ -556,7 +554,7 @@ func (g *Generator) isExpr(genConfig ExprGeneratorConfig) Expr { ops := []IsExprOperator{IsNullOp, IsNotNullOp, IsTrueOp, IsNotTrueOp, IsFalseOp, IsNotFalseOp} return &IsExpr{ - Right: ops[g.r.Intn(len(ops))], + Right: ops[rand.IntN(len(ops))], Left: g.Expression(genConfig), } } diff --git a/go/vt/sqlparser/rewriter_test.go b/go/vt/sqlparser/rewriter_test.go index 91c925d672f..628d6fbd0a4 100644 --- a/go/vt/sqlparser/rewriter_test.go +++ b/go/vt/sqlparser/rewriter_test.go @@ -17,7 +17,6 @@ limitations under the License. package sqlparser import ( - "math/rand" "testing" "github.com/stretchr/testify/assert" @@ -26,7 +25,7 @@ import ( ) func BenchmarkVisitLargeExpression(b *testing.B) { - gen := NewGenerator(rand.New(rand.NewSource(1)), 5) + gen := NewGenerator(5) exp := gen.Expression(ExprGeneratorConfig{}) depth := 0 diff --git a/go/vt/sqlparser/walker_test.go b/go/vt/sqlparser/walker_test.go index 560ed2ff470..80c8a4683ce 100644 --- a/go/vt/sqlparser/walker_test.go +++ b/go/vt/sqlparser/walker_test.go @@ -18,7 +18,6 @@ package sqlparser import ( "fmt" - "math/rand" "testing" "github.com/stretchr/testify/require" @@ -27,7 +26,7 @@ import ( func BenchmarkWalkLargeExpression(b *testing.B) { for i := 0; i < 10; i++ { b.Run(fmt.Sprintf("%d", i), func(b *testing.B) { - exp := NewGenerator(rand.New(rand.NewSource(int64(i*100))), 5).Expression(ExprGeneratorConfig{}) + exp := NewGenerator(5).Expression(ExprGeneratorConfig{}) count := 0 for i := 0; i < b.N; i++ { err := Walk(func(node SQLNode) (kontinue bool, err error) { @@ -43,7 +42,7 @@ func BenchmarkWalkLargeExpression(b *testing.B) { func BenchmarkRewriteLargeExpression(b *testing.B) { for i := 1; i < 7; i++ { b.Run(fmt.Sprintf("%d", i), func(b *testing.B) { - exp := NewGenerator(rand.New(rand.NewSource(int64(i*100))), i).Expression(ExprGeneratorConfig{}) + exp := NewGenerator(i).Expression(ExprGeneratorConfig{}) count := 0 for i := 0; i < b.N; i++ { _ = Rewrite(exp, func(_ *Cursor) bool { diff --git a/go/vt/tableacl/testlib/testlib.go b/go/vt/tableacl/testlib/testlib.go index bdde9ae800f..1ebe8b7d564 100644 --- a/go/vt/tableacl/testlib/testlib.go +++ b/go/vt/tableacl/testlib/testlib.go @@ -19,7 +19,7 @@ package testlib import ( "errors" "fmt" - "math/rand" + "math/rand/v2" "testing" querypb "vitess.io/vitess/go/vt/proto/query" @@ -30,7 +30,7 @@ import ( // TestSuite tests a concrete acl.Factory implementation. func TestSuite(t *testing.T, factory acl.Factory) { - name := fmt.Sprintf("tableacl-test-%d", rand.Int63()) + name := fmt.Sprintf("tableacl-test-%d", rand.Int64()) tableacl.Register(name, factory) tableacl.SetDefaultACL(name) diff --git a/go/vt/throttler/demo/throttler_demo.go b/go/vt/throttler/demo/throttler_demo.go index 15228475bfb..cd2a4e11307 100644 --- a/go/vt/throttler/demo/throttler_demo.go +++ b/go/vt/throttler/demo/throttler_demo.go @@ -18,7 +18,7 @@ package main import ( "context" - "math/rand" + "math/rand/v2" "net/http" "sync" "testing" @@ -189,7 +189,7 @@ func (r *replica) processReplicationStream() { actualRate = 0 } if !r.nextDegration.IsZero() && time.Now().After(r.nextDegration) && r.currentDegrationEnd.IsZero() { - degradedRate := rand.Int63n(rate) + degradedRate := rand.Int64N(rate) log.Infof("degrading the replica for %.f seconds from %v TPS to %v", r.degrationDuration.Seconds(), rate, degradedRate) r.throttler.SetMaxRate(degradedRate) r.currentDegrationEnd = time.Now().Add(r.degrationDuration) diff --git a/go/vt/topo/memorytopo/memorytopo.go b/go/vt/topo/memorytopo/memorytopo.go index abf99e760c3..2b5385d8e28 100644 --- a/go/vt/topo/memorytopo/memorytopo.go +++ b/go/vt/topo/memorytopo/memorytopo.go @@ -22,7 +22,7 @@ package memorytopo import ( "context" "errors" - "math/rand" + "math/rand/v2" "strings" "sync" "sync/atomic" @@ -249,7 +249,7 @@ func (n *node) PropagateWatchError(err error) { func NewServerAndFactory(ctx context.Context, cells ...string) (*topo.Server, *Factory) { f := &Factory{ cells: make(map[string]*node), - generation: uint64(rand.Int63n(1 << 60)), + generation: uint64(rand.Int64N(1 << 60)), callstats: stats.NewCountersWithMultiLabels("", "", []string{"Call"}), } f.cells[topo.GlobalCell] = f.newDirectory(topo.GlobalCell, nil) diff --git a/go/vt/topo/zk2topo/zk_conn.go b/go/vt/topo/zk2topo/zk_conn.go index a0eec8b4340..432fc472db0 100644 --- a/go/vt/topo/zk2topo/zk_conn.go +++ b/go/vt/topo/zk2topo/zk_conn.go @@ -21,7 +21,7 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "math/rand" + "math/rand/v2" "net" "os" "strings" @@ -251,7 +251,7 @@ func (c *ZkConn) withRetry(ctx context.Context, action func(conn *zk.Conn) error if i > 0 { // Add a bit of backoff time before retrying: // 1 second base + up to 5 seconds. - time.Sleep(1*time.Second + time.Duration(rand.Int63n(5e9))) + time.Sleep(1*time.Second + time.Duration(rand.Int64N(5e9))) } // Get the current connection, or connect. diff --git a/go/vt/topotools/shard_test.go b/go/vt/topotools/shard_test.go index f2fb5f50340..9fa9cd057b2 100644 --- a/go/vt/topotools/shard_test.go +++ b/go/vt/topotools/shard_test.go @@ -19,7 +19,7 @@ package topotools import ( "context" "fmt" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -114,7 +114,7 @@ func TestGetOrCreateShard(t *testing.T) { defer wg.Done() for j := 0; j < 100; j++ { - index := rand.Intn(10) + index := rand.IntN(10) shard := fmt.Sprintf("%v", index) si, err := ts.GetOrCreateShard(ctx, keyspace, shard) if err != nil { diff --git a/go/vt/vtadmin/cluster/cluster.go b/go/vt/vtadmin/cluster/cluster.go index 966f43bc67c..0afed99c24d 100644 --- a/go/vt/vtadmin/cluster/cluster.go +++ b/go/vt/vtadmin/cluster/cluster.go @@ -23,7 +23,7 @@ import ( stderrors "errors" "fmt" "io" - "math/rand" + "math/rand/v2" "sort" "strings" "sync" @@ -1795,7 +1795,7 @@ func (c *Cluster) getTabletsToQueryForSchemas(ctx context.Context, keyspace stri return nil, fmt.Errorf("%w for shard %s/%s", errors.ErrNoServingTablet, shard.Keyspace, shard.Name) } - randomServingTablet := shardTablets[rand.Intn(len(shardTablets))] + randomServingTablet := shardTablets[rand.IntN(len(shardTablets))] tabletsToQuery = append(tabletsToQuery, randomServingTablet) } @@ -1812,7 +1812,7 @@ func (c *Cluster) getTabletsToQueryForSchemas(ctx context.Context, keyspace stri return nil, err } - randomServingTablet := keyspaceTablets[rand.Intn(len(keyspaceTablets))] + randomServingTablet := keyspaceTablets[rand.IntN(len(keyspaceTablets))] return []*vtadminpb.Tablet{randomServingTablet}, nil } diff --git a/go/vt/vtadmin/cluster/discovery/discovery_consul.go b/go/vt/vtadmin/cluster/discovery/discovery_consul.go index 3f405c6aa40..76ee229edd5 100644 --- a/go/vt/vtadmin/cluster/discovery/discovery_consul.go +++ b/go/vt/vtadmin/cluster/discovery/discovery_consul.go @@ -19,7 +19,7 @@ package discovery import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strings" "text/template" "time" @@ -205,7 +205,7 @@ func (c *ConsulDiscovery) discoverVTGate(ctx context.Context, tags []string, exe return nil, ErrNoVTGates } - return vtgates[rand.Intn(len(vtgates))], nil + return vtgates[rand.IntN(len(vtgates))], nil } // DiscoverVTGateAddr is part of the Discovery interface. @@ -350,7 +350,7 @@ func (c *ConsulDiscovery) discoverVtctld(ctx context.Context, tags []string, exe return nil, ErrNoVtctlds } - return vtctlds[rand.Intn(len(vtctlds))], nil + return vtctlds[rand.IntN(len(vtctlds))], nil } // DiscoverVtctldAddr is part of the Discovery interface. diff --git a/go/vt/vtadmin/cluster/discovery/discovery_json.go b/go/vt/vtadmin/cluster/discovery/discovery_json.go index 3433fb4aece..981937e3e3e 100644 --- a/go/vt/vtadmin/cluster/discovery/discovery_json.go +++ b/go/vt/vtadmin/cluster/discovery/discovery_json.go @@ -20,7 +20,7 @@ import ( "context" "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "vitess.io/vitess/go/trace" @@ -130,7 +130,7 @@ func (d *JSONDiscovery) discoverVTGate(ctx context.Context, tags []string) (*vta return nil, ErrNoVTGates } - gate := gates[rand.Intn(len(gates))] + gate := gates[rand.IntN(len(gates))] return gate, nil } @@ -230,7 +230,7 @@ func (d *JSONDiscovery) discoverVtctld(ctx context.Context, tags []string) (*vta return nil, ErrNoVtctlds } - vtctld := vtctlds[rand.Intn(len(vtctlds))] + vtctld := vtctlds[rand.IntN(len(vtctlds))] return vtctld, nil } diff --git a/go/vt/vtadmin/cluster/discovery/fakediscovery/discovery.go b/go/vt/vtadmin/cluster/discovery/fakediscovery/discovery.go index cf1f7ec7702..f711692d6fd 100644 --- a/go/vt/vtadmin/cluster/discovery/fakediscovery/discovery.go +++ b/go/vt/vtadmin/cluster/discovery/fakediscovery/discovery.go @@ -19,7 +19,7 @@ package fakediscovery import ( "context" - "math/rand" + "math/rand/v2" "sync" "github.com/stretchr/testify/assert" @@ -189,7 +189,7 @@ func (d *Fake) DiscoverVTGate(ctx context.Context, tags []string) (*vtadminpb.VT return nil, assert.AnError } - return gates[rand.Intn(len(gates))], nil + return gates[rand.IntN(len(gates))], nil } // DiscoverVTGateAddr is part of the discovery.Discovery interface. @@ -299,5 +299,5 @@ func (d *Fake) DiscoverVtctld(ctx context.Context, tags []string) (*vtadminpb.Vt return nil, assert.AnError } - return vtctlds[rand.Intn(len(vtctlds))], nil + return vtctlds[rand.IntN(len(vtctlds))], nil } diff --git a/go/vt/vtadmin/debug/debug_test.go b/go/vt/vtadmin/debug/debug_test.go index 4f87dbcc33c..dd1c42bdbd8 100644 --- a/go/vt/vtadmin/debug/debug_test.go +++ b/go/vt/vtadmin/debug/debug_test.go @@ -17,7 +17,7 @@ limitations under the License. package debug import ( - "math/rand" + "math/rand/v2" "testing" "time" @@ -44,10 +44,10 @@ func TestSanitizeString(t *testing.T) { t.Run("", func(t *testing.T) { t.Parallel() - length := rand.Intn(20) + 1 // [1, 21) + length := rand.IntN(20) + 1 // [1, 21) word := "" for j := 0; j < length; j++ { - k := rand.Intn(len(letters)) + k := rand.IntN(len(letters)) word += letters[k : k+1] } @@ -66,8 +66,8 @@ func TestTimeToString(t *testing.T) { t.Parallel() start := time.Now() - secondsoff := rand.Intn(60) - minutesoff := rand.Intn(60) + secondsoff := rand.IntN(60) + minutesoff := rand.IntN(60) in := start.Add(time.Second*time.Duration(secondsoff) + time.Minute*time.Duration(minutesoff)) out, err := time.Parse(time.RFC3339, TimeToString(in)) diff --git a/go/vt/vtadmin/internal/backoff/backoff.go b/go/vt/vtadmin/internal/backoff/backoff.go index 025991d28d6..c3c4ec4ae86 100644 --- a/go/vt/vtadmin/internal/backoff/backoff.go +++ b/go/vt/vtadmin/internal/backoff/backoff.go @@ -27,13 +27,13 @@ package backoff import ( "fmt" + "math/rand/v2" "strings" "time" grpcbackoff "google.golang.org/grpc/backoff" "vitess.io/vitess/go/vt/log" - vtrand "vitess.io/vitess/go/vt/vtadmin/internal/rand" ) // Strategy defines the interface for different backoff strategies. @@ -83,7 +83,7 @@ func backoffCommon(retries int, cfg grpcbackoff.Config, adjust func(cur float64) } // Randomize backoff delays so that if a cluster of requests start at // the same time, they won't operate in lockstep. - backoff *= 1 + cfg.Jitter*(vtrand.Float64()*2-1) + backoff *= 1 + cfg.Jitter*(rand.Float64()*2-1) if backoff < 0 { return 0 } diff --git a/go/vt/vtadmin/internal/rand/rand.go b/go/vt/vtadmin/internal/rand/rand.go deleted file mode 100644 index aa48f10da7e..00000000000 --- a/go/vt/vtadmin/internal/rand/rand.go +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright 2022 The Vitess Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// Package rand provides functions mirroring math/rand that are safe for -// concurrent use, seeded independently of math/rand's global source. -package rand - -/* -- TODO: (ajm188) implement the rest of the global functions vtadmin uses. -- TODO: (ajm188) consider moving to go/internal at the top-level for use in - more places. -*/ - -import ( - "math/rand" - "sync" - "time" -) - -var ( - r = rand.New(rand.NewSource(time.Now().UnixNano())) - m sync.Mutex -) - -// Float64 implements rand.Float64 on the vtrand global source. -func Float64() float64 { - m.Lock() - defer m.Unlock() - - return r.Float64() -} diff --git a/go/vt/vtctl/vdiff_env_test.go b/go/vt/vtctl/vdiff_env_test.go index b5324e7bd6e..d09448c2866 100644 --- a/go/vt/vtctl/vdiff_env_test.go +++ b/go/vt/vtctl/vdiff_env_test.go @@ -19,7 +19,7 @@ package vtctl import ( "context" "fmt" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -82,7 +82,7 @@ func newTestVDiffEnv(t testing.TB, ctx context.Context, sourceShards, targetShar env.wr = wrangler.NewTestWrangler(env.cmdlog, env.topoServ, env.tmc) // Generate a unique dialer name. - dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { env.mu.Lock() defer env.mu.Unlock() diff --git a/go/vt/vterrors/errors_test.go b/go/vt/vterrors/errors_test.go index 8c039e5874f..49b77ee0385 100644 --- a/go/vt/vterrors/errors_test.go +++ b/go/vt/vterrors/errors_test.go @@ -21,7 +21,7 @@ import ( "errors" "fmt" "io" - "math/rand" + "math/rand/v2" "reflect" "strings" "testing" diff --git a/go/vt/vtgate/endtoend/oltp_test.go b/go/vt/vtgate/endtoend/oltp_test.go index f8ca646f8c7..02e9e2c92a7 100644 --- a/go/vt/vtgate/endtoend/oltp_test.go +++ b/go/vt/vtgate/endtoend/oltp_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -21,12 +21,12 @@ const cValueTemplate = "###########-###########-###########-" + const padValueTemplate = "###########-###########-###########-" + "###########-###########" -func sysbenchRandom(rng *rand.Rand, template string) []byte { +func sysbenchRandom(template string) []byte { out := make([]byte, 0, len(template)) for i := range template { switch template[i] { case '#': - out = append(out, '0'+byte(rng.Intn(10))) + out = append(out, '0'+byte(rand.IntN(10))) default: out = append(out, template[i]) } @@ -40,8 +40,6 @@ func BenchmarkOLTP(b *testing.B) { const MaxRows = 10000 const RangeSize = 100 - rng := rand.New(rand.NewSource(1234)) - ctx := context.Background() conn, err := mysql.Connect(ctx, &vtParams) if err != nil { @@ -62,7 +60,7 @@ func BenchmarkOLTP(b *testing.B) { if j > 0 { query.WriteString(", ") } - _, _ = fmt.Fprintf(&query, "(%d, %d, '%s', '%s')", rows, rng.Int31n(0xFFFF), sysbenchRandom(rng, cValueTemplate), sysbenchRandom(rng, padValueTemplate)) + _, _ = fmt.Fprintf(&query, "(%d, %d, '%s', '%s')", rows, rand.Int32N(0xFFFF), sysbenchRandom(cValueTemplate), sysbenchRandom(padValueTemplate)) rows++ } @@ -77,10 +75,10 @@ func BenchmarkOLTP(b *testing.B) { b.Run("SimpleRanges", func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - id := rng.Intn(MaxRows) + id := rand.IntN(MaxRows) query.Reset() - _, _ = fmt.Fprintf(&query, "SELECT c FROM oltp_test WHERE id BETWEEN %d AND %d", id, id+rng.Intn(RangeSize)-1) + _, _ = fmt.Fprintf(&query, "SELECT c FROM oltp_test WHERE id BETWEEN %d AND %d", id, id+rand.IntN(RangeSize)-1) _, err := conn.ExecuteFetch(query.String(), 1000, false) if err != nil { b.Error(err) @@ -91,10 +89,10 @@ func BenchmarkOLTP(b *testing.B) { b.Run("SumRanges", func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - id := rng.Intn(MaxRows) + id := rand.IntN(MaxRows) query.Reset() - _, _ = fmt.Fprintf(&query, "SELECT SUM(k) FROM oltp_test WHERE id BETWEEN %d AND %d", id, id+rng.Intn(RangeSize)-1) + _, _ = fmt.Fprintf(&query, "SELECT SUM(k) FROM oltp_test WHERE id BETWEEN %d AND %d", id, id+rand.IntN(RangeSize)-1) _, err := conn.ExecuteFetch(query.String(), 1000, false) if err != nil { b.Error(err) @@ -105,10 +103,10 @@ func BenchmarkOLTP(b *testing.B) { b.Run("OrderRanges", func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - id := rng.Intn(MaxRows) + id := rand.IntN(MaxRows) query.Reset() - _, _ = fmt.Fprintf(&query, "SELECT c FROM oltp_test WHERE id BETWEEN %d AND %d ORDER BY c", id, id+rng.Intn(RangeSize)-1) + _, _ = fmt.Fprintf(&query, "SELECT c FROM oltp_test WHERE id BETWEEN %d AND %d ORDER BY c", id, id+rand.IntN(RangeSize)-1) _, err := conn.ExecuteFetch(query.String(), 1000, false) if err != nil { b.Error(err) @@ -119,10 +117,10 @@ func BenchmarkOLTP(b *testing.B) { b.Run("DistinctRanges", func(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - id := rng.Intn(MaxRows) + id := rand.IntN(MaxRows) query.Reset() - _, _ = fmt.Fprintf(&query, "SELECT DISTINCT c FROM oltp_test WHERE id BETWEEN %d AND %d ORDER BY c", id, id+rng.Intn(RangeSize)-1) + _, _ = fmt.Fprintf(&query, "SELECT DISTINCT c FROM oltp_test WHERE id BETWEEN %d AND %d ORDER BY c", id, id+rand.IntN(RangeSize)-1) _, err := conn.ExecuteFetch(query.String(), 1000, false) if err != nil { b.Error(err) diff --git a/go/vt/vtgate/engine/aggregations_test.go b/go/vt/vtgate/engine/aggregations_test.go index 55ec59f73e1..9facf3d4f6f 100644 --- a/go/vt/vtgate/engine/aggregations_test.go +++ b/go/vt/vtgate/engine/aggregations_test.go @@ -19,7 +19,7 @@ package engine import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strings" "testing" @@ -58,7 +58,7 @@ func benchmarkName(fields []*querypb.Field) string { func BenchmarkScalarAggregate(b *testing.B) { var rand_i64 = sqltypes.RandomGenerators[sqltypes.Int64] var rand_i64small = func() sqltypes.Value { - return sqltypes.NewInt64(rand.Int63n(1024)) + return sqltypes.NewInt64(rand.Int64N(1024)) } var rand_f64 = sqltypes.RandomGenerators[sqltypes.Float64] var rand_dec = sqltypes.RandomGenerators[sqltypes.Decimal] @@ -142,7 +142,7 @@ func BenchmarkScalarAggregate(b *testing.B) { return sqltypes.NewVarChar(uuid.New().String()) }, func() sqltypes.Value { - return sqltypes.NewVarChar(fmt.Sprintf("%x-%x", rand.Intn(256), rand.Intn(256))) + return sqltypes.NewVarChar(fmt.Sprintf("%x-%x", rand.IntN(256), rand.IntN(256))) }, }, params: []*AggregateParams{ diff --git a/go/vt/vtgate/engine/route.go b/go/vt/vtgate/engine/route.go index 1a0c17d6be5..a45329c8e84 100644 --- a/go/vt/vtgate/engine/route.go +++ b/go/vt/vtgate/engine/route.go @@ -19,7 +19,7 @@ package engine import ( "context" "fmt" - "math/rand" + "math/rand/v2" "sort" "strings" "time" @@ -542,7 +542,7 @@ func (route *Route) executeWarmingReplicaRead(ctx context.Context, vcursor VCurs return } - if vcursor.GetWarmingReadsPercent() == 0 || rand.Intn(100) > vcursor.GetWarmingReadsPercent() { + if vcursor.GetWarmingReadsPercent() == 0 || rand.IntN(100) > vcursor.GetWarmingReadsPercent() { return } diff --git a/go/vt/vtgate/evalengine/api_compare_test.go b/go/vt/vtgate/evalengine/api_compare_test.go index b483f8e52c0..aa039537240 100644 --- a/go/vt/vtgate/evalengine/api_compare_test.go +++ b/go/vt/vtgate/evalengine/api_compare_test.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "math" - "math/rand" + "math/rand/v2" "slices" "strings" "testing" diff --git a/go/vt/vtgate/evalengine/integration/fuzz_test.go b/go/vt/vtgate/evalengine/integration/fuzz_test.go index cb29b9c9c32..17a721edde9 100644 --- a/go/vt/vtgate/evalengine/integration/fuzz_test.go +++ b/go/vt/vtgate/evalengine/integration/fuzz_test.go @@ -21,7 +21,7 @@ package integration import ( "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "os" "regexp" "strings" @@ -42,7 +42,6 @@ import ( type ( gencase struct { - rand *rand.Rand ratioTuple int ratioSubexpr int tupleLen int @@ -62,24 +61,24 @@ var rhsOfIs = []string{ } func (g *gencase) arg(tuple bool) string { - if tuple || g.rand.Intn(g.ratioTuple) == 0 { + if tuple || rand.IntN(g.ratioTuple) == 0 { var exprs []string for i := 0; i < g.tupleLen; i++ { exprs = append(exprs, g.arg(false)) } return fmt.Sprintf("(%s)", strings.Join(exprs, ", ")) } - if g.rand.Intn(g.ratioSubexpr) == 0 { + if rand.IntN(g.ratioSubexpr) == 0 { return fmt.Sprintf("(%s)", g.expr()) } - return g.primitives[g.rand.Intn(len(g.primitives))] + return g.primitives[rand.IntN(len(g.primitives))] } func (g *gencase) expr() string { - op := g.operators[g.rand.Intn(len(g.operators))] + op := g.operators[rand.IntN(len(g.operators))] rhs := g.arg(op == "IN" || op == "NOT IN") if op == "IS" { - rhs = rhsOfIs[g.rand.Intn(len(rhsOfIs))] + rhs = rhsOfIs[rand.IntN(len(rhsOfIs))] } return fmt.Sprintf("%s %s %s", g.arg(false), op, rhs) } @@ -183,7 +182,6 @@ func TestGenerateFuzzCases(t *testing.T) { t.Skipf("skipping fuzz test generation") } var gen = gencase{ - rand: rand.New(rand.NewSource(fuzzSeed)), ratioTuple: 8, ratioSubexpr: 8, tupleLen: 4, diff --git a/go/vt/vtgate/fakerpcvtgateconn/conn.go b/go/vt/vtgate/fakerpcvtgateconn/conn.go index 442c8997979..3f6236ea9ec 100644 --- a/go/vt/vtgate/fakerpcvtgateconn/conn.go +++ b/go/vt/vtgate/fakerpcvtgateconn/conn.go @@ -23,7 +23,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "reflect" "vitess.io/vitess/go/sqltypes" @@ -211,7 +211,7 @@ func newSession( Shard: shard, TabletType: tabletType, }, - TransactionId: rand.Int63(), + TransactionId: rand.Int64(), }) } return &vtgatepb.Session{ diff --git a/go/vt/vtgate/planbuilder/plan_test.go b/go/vt/vtgate/planbuilder/plan_test.go index 2ce1d04b4c5..6a2d0fe8b3f 100644 --- a/go/vt/vtgate/planbuilder/plan_test.go +++ b/go/vt/vtgate/planbuilder/plan_test.go @@ -21,7 +21,7 @@ import ( "context" "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "os" "path/filepath" "runtime/debug" diff --git a/go/vt/vtgate/planbuilder/predicate_rewrite_test.go b/go/vt/vtgate/planbuilder/predicate_rewrite_test.go index ba1d60ff234..f103709d9e3 100644 --- a/go/vt/vtgate/planbuilder/predicate_rewrite_test.go +++ b/go/vt/vtgate/planbuilder/predicate_rewrite_test.go @@ -18,7 +18,7 @@ package planbuilder import ( "fmt" - "math/rand" + "math/rand/v2" "strconv" "testing" "time" @@ -53,12 +53,12 @@ const ( func (tc testCase) createPredicate(lvl int) sqlparser.Expr { if lvl >= tc.depth { // we're at max depth, so we just return one of the nodes - n := rand.Intn(tc.nodes) + n := rand.IntN(tc.nodes) return sqlparser.NewColName(fmt.Sprintf("n%d", n)) } - switch nodeType(rand.Intn(int(SIZE))) { + switch nodeType(rand.IntN(int(SIZE))) { case NODE: - n := rand.Intn(tc.nodes) + n := rand.IntN(tc.nodes) return sqlparser.NewColName(fmt.Sprintf("n%d", n)) case NOT: return &sqlparser.NotExpr{ @@ -95,8 +95,8 @@ func TestFuzzRewriting(t *testing.T) { start := time.Now() for time.Since(start) < 1*time.Second { tc := testCase{ - nodes: rand.Intn(4) + 1, - depth: rand.Intn(4) + 1, + nodes: rand.IntN(4) + 1, + depth: rand.IntN(4) + 1, } predicate := tc.createPredicate(0) diff --git a/go/vt/vtgate/semantics/table_set_test.go b/go/vt/vtgate/semantics/table_set_test.go index 03d0d91cc9e..3730f91c533 100644 --- a/go/vt/vtgate/semantics/table_set_test.go +++ b/go/vt/vtgate/semantics/table_set_test.go @@ -17,7 +17,7 @@ limitations under the License. package semantics import ( - "math/rand" + "math/rand/v2" "testing" "github.com/stretchr/testify/assert" @@ -69,7 +69,7 @@ func TestTableSet_LargeTablesConstituents(t *testing.T) { var table int for t := 0; t < 256; t++ { - table += rand.Intn(GapSize) + 1 + table += rand.IntN(GapSize) + 1 expected = append(expected, SingleTableSet(table)) ts = ts.WithTable(table) } diff --git a/go/vt/vtgate/tabletgateway.go b/go/vt/vtgate/tabletgateway.go index 49b9dac1128..496224c207f 100644 --- a/go/vt/vtgate/tabletgateway.go +++ b/go/vt/vtgate/tabletgateway.go @@ -19,7 +19,7 @@ package vtgate import ( "context" "fmt" - "math/rand" + "math/rand/v2" "runtime/debug" "sort" "sync" @@ -403,13 +403,13 @@ func (gw *TabletGateway) shuffleTablets(cell string, tablets []*discovery.Tablet // shuffle in same cell tablets for i := sameCellMax; i > 0; i-- { - swap := rand.Intn(i + 1) + swap := rand.IntN(i + 1) tablets[i], tablets[swap] = tablets[swap], tablets[i] } // shuffle in diff cell tablets for i, diffCellMin := length-1, sameCellMax+1; i > diffCellMin; i-- { - swap := rand.Intn(i-sameCellMax) + diffCellMin + swap := rand.IntN(i-sameCellMax) + diffCellMin tablets[i], tablets[swap] = tablets[swap], tablets[i] } } diff --git a/go/vt/vthash/highway/highwayhash_test.go b/go/vt/vthash/highway/highwayhash_test.go index 896b6d13763..360b0bfce08 100644 --- a/go/vt/vthash/highway/highwayhash_test.go +++ b/go/vt/vthash/highway/highwayhash_test.go @@ -21,8 +21,8 @@ package highway import ( "bytes" + "crypto/rand" "encoding/hex" - "math/rand" "runtime" "sync/atomic" "testing" @@ -203,11 +203,10 @@ func benchmarkParallel(b *testing.B, size int) { var key [32]byte - rng := rand.New(rand.NewSource(0xabadc0cac01a)) data := make([][]byte, c) for i := range data { data[i] = make([]byte, size) - rng.Read(data[i]) + _, _ = rand.Read(data[i]) } b.SetBytes(int64(size)) diff --git a/go/vt/vtorc/logic/topology_recovery.go b/go/vt/vtorc/logic/topology_recovery.go index c1fc2c8f9fb..1ee82bb3560 100644 --- a/go/vt/vtorc/logic/topology_recovery.go +++ b/go/vt/vtorc/logic/topology_recovery.go @@ -20,7 +20,7 @@ import ( "context" "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "time" "github.com/patrickmn/go-cache" diff --git a/go/vt/vttablet/endtoend/queries_test.go b/go/vt/vttablet/endtoend/queries_test.go index 3dad415c1c1..5a57f681a10 100644 --- a/go/vt/vttablet/endtoend/queries_test.go +++ b/go/vt/vttablet/endtoend/queries_test.go @@ -18,7 +18,7 @@ package endtoend import ( "fmt" - "math/rand" + "math/rand/v2" "testing" "github.com/stretchr/testify/require" @@ -1775,7 +1775,7 @@ func BenchmarkTabletQueries(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - tcase := TestQueryCases[rand.Intn(len(TestQueryCases))] + tcase := TestQueryCases[rand.IntN(len(TestQueryCases))] if err := tcase.Benchmark(client); err != nil { b.Error(err) } diff --git a/go/vt/vttablet/grpctmclient/cached_client_flaky_test.go b/go/vt/vttablet/grpctmclient/cached_client_flaky_test.go index c5346a99aa4..cf002cb7d18 100644 --- a/go/vt/vttablet/grpctmclient/cached_client_flaky_test.go +++ b/go/vt/vttablet/grpctmclient/cached_client_flaky_test.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "net" "runtime" "sync" @@ -117,7 +117,7 @@ func BenchmarkCachedConnClientSteadyState(b *testing.B) { ctx, cancel := context.WithTimeout(ctx, time.Second*5) defer cancel() - x := rand.Intn(len(tablets)) + x := rand.IntN(len(tablets)) err := client.Ping(ctx, tablets[x]) assert.NoError(b, err) }() @@ -185,7 +185,7 @@ func BenchmarkCachedConnClientSteadyStateRedials(b *testing.B) { ctx, cancel := context.WithTimeout(ctx, time.Second*5) defer cancel() - x := rand.Intn(len(tablets)) + x := rand.IntN(len(tablets)) err := client.Ping(ctx, tablets[x]) assert.NoError(b, err) }() @@ -340,10 +340,10 @@ func TestCachedConnClient(t *testing.T) { longestDials <- longestDial return case <-time.After(jitter): - jitter = time.Millisecond * (time.Duration(rand.Intn(11) + 50)) + jitter = time.Millisecond * (time.Duration(rand.IntN(11) + 50)) attempts++ - tablet := tablets[rand.Intn(len(tablets))] + tablet := tablets[rand.IntN(len(tablets))] start := time.Now() _, closer, err := client.dialer.dial(context.Background(), tablet) if err != nil { diff --git a/go/vt/vttablet/tabletmanager/tm_init.go b/go/vt/vttablet/tabletmanager/tm_init.go index c4ad332a470..f8931691ed5 100644 --- a/go/vt/vttablet/tabletmanager/tm_init.go +++ b/go/vt/vttablet/tabletmanager/tm_init.go @@ -38,7 +38,7 @@ import ( "encoding/hex" "errors" "fmt" - "math/rand" + "math/rand/v2" "regexp" "strings" "sync" @@ -912,8 +912,7 @@ func (tm *TabletManager) withRetry(ctx context.Context, description string, work // Exponential backoff with 1.3 as a factor, // and randomized down by at most 20 // percent. The generated time series looks - // good. Also note rand.Seed is called at - // init() time in binlog_players.go. + // good. f := float64(backoff) * 1.3 f -= f * 0.2 * rand.Float64() backoff = time.Duration(f) diff --git a/go/vt/vttablet/tabletserver/messager/message_manager.go b/go/vt/vttablet/tabletserver/messager/message_manager.go index 845eaf8df40..029622bf938 100644 --- a/go/vt/vttablet/tabletserver/messager/message_manager.go +++ b/go/vt/vttablet/tabletserver/messager/message_manager.go @@ -21,7 +21,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "sync" "time" diff --git a/go/vt/vttablet/tabletserver/query_engine_test.go b/go/vt/vttablet/tabletserver/query_engine_test.go index 604f65f3311..146414e819b 100644 --- a/go/vt/vttablet/tabletserver/query_engine_test.go +++ b/go/vt/vttablet/tabletserver/query_engine_test.go @@ -19,7 +19,7 @@ package tabletserver import ( "context" "fmt" - "math/rand" + "math/rand/v2" "net/http" "net/http/httptest" "os" @@ -457,7 +457,7 @@ func BenchmarkPlanCacheThroughput(b *testing.B) { logStats := tabletenv.NewLogStats(ctx, "GetPlanStats") for i := 0; i < b.N; i++ { - query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(500)) + query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.IntN(500)) _, err := qe.GetPlan(ctx, logStats, query, false) if err != nil { b.Fatal(err) @@ -487,7 +487,7 @@ func benchmarkPlanCache(b *testing.B, db *fakesqldb.DB, par int) { logStats := tabletenv.NewLogStats(ctx, "GetPlanStats") for pb.Next() { - query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(500)) + query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.IntN(500)) _, err := qe.GetPlan(ctx, logStats, query, false) require.NoErrorf(b, err, "bad query: %s", query) } @@ -619,7 +619,7 @@ func TestPlanCachePollution(t *testing.T) { go func() { defer wg.Done() runner(NormalQueries, &stats1, func() string { - return fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(5000)) + return fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.IntN(5000)) }) }() diff --git a/go/vt/vttablet/tabletserver/query_executor_test.go b/go/vt/vttablet/tabletserver/query_executor_test.go index afc42113522..0c845d7c2ae 100644 --- a/go/vt/vttablet/tabletserver/query_executor_test.go +++ b/go/vt/vttablet/tabletserver/query_executor_test.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "io" - "math/rand" + "math/rand/v2" "strings" "testing" "time" @@ -795,7 +795,7 @@ func TestQueryExecutorPlanNextval(t *testing.T) { func TestQueryExecutorMessageStreamACL(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) config := &tableaclpb.Config{ @@ -858,7 +858,7 @@ func TestQueryExecutorMessageStreamACL(t *testing.T) { } func TestQueryExecutorTableAcl(t *testing.T) { - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) db := setUpQueryExecutorTest(t) @@ -902,7 +902,7 @@ func TestQueryExecutorTableAcl(t *testing.T) { } func TestQueryExecutorTableAclNoPermission(t *testing.T) { - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) db := setUpQueryExecutorTest(t) @@ -961,7 +961,7 @@ func TestQueryExecutorTableAclNoPermission(t *testing.T) { } func TestQueryExecutorTableAclDualTableExempt(t *testing.T) { - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) db := setUpQueryExecutorTest(t) @@ -1013,7 +1013,7 @@ func TestQueryExecutorTableAclDualTableExempt(t *testing.T) { } func TestQueryExecutorTableAclExemptACL(t *testing.T) { - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) db := setUpQueryExecutorTest(t) @@ -1078,7 +1078,7 @@ func TestQueryExecutorTableAclExemptACL(t *testing.T) { } func TestQueryExecutorTableAclDryRun(t *testing.T) { - aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int63()) + aclName := fmt.Sprintf("simpleacl-test-%d", rand.Int64()) tableacl.Register(aclName, &simpleacl.Factory{}) tableacl.SetDefaultACL(aclName) db := setUpQueryExecutorTest(t) diff --git a/go/vt/vttablet/tabletserver/throttle/throttler.go b/go/vt/vttablet/tabletserver/throttle/throttler.go index 8f6db91936d..e388df724ed 100644 --- a/go/vt/vttablet/tabletserver/throttle/throttler.go +++ b/go/vt/vttablet/tabletserver/throttle/throttler.go @@ -46,7 +46,7 @@ import ( "errors" "fmt" "math" - "math/rand" + "math/rand/v2" "net/http" "strconv" "strings" diff --git a/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go b/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go index 4a682ffd298..7cb774663a4 100644 --- a/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go +++ b/go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go @@ -18,7 +18,7 @@ package txthrottler import ( "context" - "math/rand" + "math/rand/v2" "reflect" "strings" "sync" @@ -251,7 +251,7 @@ func (t *txThrottler) Throttle(priority int, workload string) (result bool) { // Throttle according to both what the throttler state says and the priority. Workloads with lower priority value // are less likely to be throttled. - result = rand.Intn(sqlparser.MaxPriorityValue) < priority && t.state.throttle() + result = rand.IntN(sqlparser.MaxPriorityValue) < priority && t.state.throttle() t.requestsTotal.Add(workload, 1) if result { diff --git a/go/vt/vttablet/tabletserver/vstreamer/packet_size_test.go b/go/vt/vttablet/tabletserver/vstreamer/packet_size_test.go index 35542e0a879..fc430543a36 100644 --- a/go/vt/vttablet/tabletserver/vstreamer/packet_size_test.go +++ b/go/vt/vttablet/tabletserver/vstreamer/packet_size_test.go @@ -18,7 +18,7 @@ package vstreamer import ( "math" - "math/rand" + "math/rand/v2" "testing" "time" @@ -35,7 +35,7 @@ func (p polynomial) fit(x float64) float64 { return y } -func simulate(t *testing.T, rand *rand.Rand, ps PacketSizer, base, mustSend int, interpolate func(float64) float64) (time.Duration, int) { +func simulate(t *testing.T, ps PacketSizer, base, mustSend int, interpolate func(float64) float64) (time.Duration, int) { t.Helper() var elapsed time.Duration @@ -45,7 +45,7 @@ func simulate(t *testing.T, rand *rand.Rand, ps PacketSizer, base, mustSend int, packetSize := 0 for sent < mustSend { - packetSize += rand.Intn(base / 100) + packetSize += rand.IntN(base / 100) if ps.ShouldSend(packetSize) { x := float64(packetSize) / packetRange @@ -91,16 +91,13 @@ func TestPacketSizeSimulation(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - seed := time.Now().UnixNano() - rand := rand.New(rand.NewSource(seed)) - // Simulate a replication using the given polynomial and the dynamic packet sizer ps1 := newDynamicPacketSizer(tc.baseSize) - elapsed1, sent1 := simulate(t, rand, ps1, tc.baseSize, tc.baseSize*1000, tc.p.fit) + elapsed1, sent1 := simulate(t, ps1, tc.baseSize, tc.baseSize*1000, tc.p.fit) // Simulate the same polynomial using a fixed packet size ps2 := newFixedPacketSize(tc.baseSize) - elapsed2, sent2 := simulate(t, rand, ps2, tc.baseSize, tc.baseSize*1000, tc.p.fit) + elapsed2, sent2 := simulate(t, ps2, tc.baseSize, tc.baseSize*1000, tc.p.fit) // the simulation for dynamic packet sizing should always be faster then the fixed packet, // and should also send fewer packets in total diff --git a/go/vt/vttest/environment.go b/go/vt/vttest/environment.go index 91b38674113..3487a9fc1c7 100644 --- a/go/vt/vttest/environment.go +++ b/go/vt/vttest/environment.go @@ -18,7 +18,7 @@ package vttest import ( "fmt" - "math/rand" + "math/rand/v2" "os" "path" "strings" @@ -232,7 +232,7 @@ func tmpdir(dataroot string) (dir string, err error) { } func randomPort() int { - v := rand.Int31n(20000) + v := rand.Int32N(20000) return int(v + 10000) } diff --git a/go/vt/vttest/randomdata.go b/go/vt/vttest/randomdata.go index 0848f8cb709..6efcecfce04 100644 --- a/go/vt/vttest/randomdata.go +++ b/go/vt/vttest/randomdata.go @@ -18,7 +18,7 @@ package vttest import ( "fmt" - "math/rand" + "math/rand/v2" "strings" ) @@ -28,7 +28,7 @@ import ( // being used, as to ensure reproducible generation between runs. // A FieldGenerator must return the raw SQL data for the field, ready to be // placed into a SQL statement. The returned value will _NOT_ be escaped. -type FieldGenerator func(name, t string, rng *rand.Rand) (string, error) +type FieldGenerator func(name, t string) (string, error) // SeedConfig are the settings to enable the initialization of the // local cluster with random data. This struct must be set in Config @@ -54,16 +54,6 @@ type SeedConfig struct { RandomField FieldGenerator } -// SeedConfigDefaults returns the default values for SeedConfig -func SeedConfigDefaults() *SeedConfig { - return &SeedConfig{ - RngSeed: rand.Int(), - MinSize: 1000, - MaxSize: 10000, - NullProbability: 0.1, - } -} - const batchInsertSize = 1000 func (db *LocalCluster) batchInsert(dbname, table string, fields []string, rows [][]string) error { @@ -84,14 +74,14 @@ func (db *LocalCluster) batchInsert(dbname, table string, fields []string, rows return db.Execute([]string{sql}, dbname) } -func (db *LocalCluster) randomField(name, t string, allowNull bool, rng *rand.Rand) (string, error) { - if allowNull && rng.Float64() < db.Seed.NullProbability { +func (db *LocalCluster) randomField(name, t string, allowNull bool) (string, error) { + if allowNull && rand.Float64() < db.Seed.NullProbability { return "NULL", nil } - return db.Seed.RandomField(name, t, rng) + return db.Seed.RandomField(name, t) } -func (db *LocalCluster) populateTable(dbname, table string, rng *rand.Rand) error { +func (db *LocalCluster) populateTable(dbname, table string) error { fieldInfo, err := db.Query(fmt.Sprintf("DESCRIBE %s", table), dbname, 1024) if err != nil { return err @@ -100,7 +90,7 @@ func (db *LocalCluster) populateTable(dbname, table string, rng *rand.Rand) erro var ( minRows = db.Seed.MinSize maxRows = db.Seed.MaxSize - numRows = rng.Intn(maxRows-minRows) + minRows + numRows = rand.IntN(maxRows-minRows) + minRows rows [][]string fieldNames []string ) @@ -112,7 +102,7 @@ func (db *LocalCluster) populateTable(dbname, table string, rng *rand.Rand) erro fieldType := row[1].ToString() allowNull := row[2].ToString() == "YES" - f, err := db.randomField(fieldName, fieldType, allowNull, rng) + f, err := db.randomField(fieldName, fieldType, allowNull) if err != nil { return err } @@ -134,14 +124,14 @@ func (db *LocalCluster) populateTable(dbname, table string, rng *rand.Rand) erro return nil } -func (db *LocalCluster) populateShard(dbname string, rng *rand.Rand) error { +func (db *LocalCluster) populateShard(dbname string) error { q, err := db.Query("SHOW TABLES", dbname, 1024) if err != nil { return err } for _, row := range q.Rows { - if err := db.populateTable(dbname, row[0].ToString(), rng); err != nil { + if err := db.populateTable(dbname, row[0].ToString()); err != nil { return err } } @@ -149,10 +139,9 @@ func (db *LocalCluster) populateShard(dbname string, rng *rand.Rand) error { } func (db *LocalCluster) populateWithRandomData() error { - rng := rand.New(rand.NewSource(int64(db.Seed.RngSeed))) for _, kpb := range db.Topology.Keyspaces { for _, dbname := range db.shardNames(kpb) { - if err := db.populateShard(dbname, rng); err != nil { + if err := db.populateShard(dbname); err != nil { return err } } diff --git a/go/vt/wrangler/traffic_switcher_env_test.go b/go/vt/wrangler/traffic_switcher_env_test.go index 3838ded0669..7705ee49f45 100644 --- a/go/vt/wrangler/traffic_switcher_env_test.go +++ b/go/vt/wrangler/traffic_switcher_env_test.go @@ -19,7 +19,7 @@ package wrangler import ( "context" "fmt" - "math/rand" + "math/rand/v2" "strconv" "strings" "sync" @@ -158,7 +158,7 @@ func newTestTableMigraterCustom(ctx context.Context, t *testing.T, sourceShards, tme.targetKeyRanges = append(tme.targetKeyRanges, targetKeyRange) } - dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { tme.mu.Lock() defer tme.mu.Unlock() @@ -424,7 +424,7 @@ func newTestTablePartialMigrater(ctx context.Context, t *testing.T, shards, shar tme.targetKeyRanges = append(tme.targetKeyRanges, targetKeyRange) } - dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { tme.mu.Lock() defer tme.mu.Unlock() @@ -589,7 +589,7 @@ func newTestShardMigrater(ctx context.Context, t *testing.T, sourceShards, targe tme.targetKeyRanges = append(tme.targetKeyRanges, targetKeyRange) } - dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("TrafficSwitcherTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { tme.mu.Lock() defer tme.mu.Unlock() diff --git a/go/vt/wrangler/vdiff_env_test.go b/go/vt/wrangler/vdiff_env_test.go index ff0f97db769..ac30736c999 100644 --- a/go/vt/wrangler/vdiff_env_test.go +++ b/go/vt/wrangler/vdiff_env_test.go @@ -19,7 +19,7 @@ package wrangler import ( "context" "fmt" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -81,7 +81,7 @@ func newTestVDiffEnv(t testing.TB, ctx context.Context, sourceShards, targetShar env.wr = New(vtenv.NewTestEnv(), logutil.NewConsoleLogger(), env.topoServ, env.tmc) // Generate a unique dialer name. - dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("VDiffTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { env.mu.Lock() defer env.mu.Unlock() diff --git a/go/vt/wrangler/wrangler_env_test.go b/go/vt/wrangler/wrangler_env_test.go index 4bc20c0aad0..04231fb7bf3 100644 --- a/go/vt/wrangler/wrangler_env_test.go +++ b/go/vt/wrangler/wrangler_env_test.go @@ -19,7 +19,7 @@ package wrangler import ( "context" "fmt" - "math/rand" + "math/rand/v2" "sync" "testing" @@ -73,7 +73,7 @@ func newWranglerTestEnv(t testing.TB, ctx context.Context, sourceShards, targetS env.tmc.tablets = make(map[int]*testWranglerTablet) // Generate a unique dialer name. - dialerName := fmt.Sprintf("WranglerTest-%s-%d", t.Name(), rand.Intn(1000000000)) + dialerName := fmt.Sprintf("WranglerTest-%s-%d", t.Name(), rand.IntN(1000000000)) tabletconn.RegisterDialer(dialerName, func(tablet *topodatapb.Tablet, failFast grpcclient.FailFast) (queryservice.QueryService, error) { env.mu.Lock() defer env.mu.Unlock() diff --git a/test/client/client.go b/test/client/client.go index d1a174d8d04..bd6c6ad2af4 100644 --- a/test/client/client.go +++ b/test/client/client.go @@ -27,7 +27,7 @@ package main import ( "fmt" - "math/rand" + "math/rand/v2" "os" "time" @@ -59,7 +59,7 @@ func main() { fmt.Printf("begin failed: %v\n", err) os.Exit(1) } - page := rand.Intn(100) + 1 + page := rand.IntN(100) + 1 timeCreated := time.Now().UnixNano() if _, err := tx.Exec("INSERT INTO messages (page,time_created_ns,message) VALUES (?,?,?)", page, timeCreated, "V is for speed"); err != nil {