Debian Codegraph @

unittest/gunit/innodb/ut0rnd-t.cc

raw symbols SCIP
1 /* Copyright (c) 2013, 2026, Oracle and/or its affiliates.
2
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License, version 2.0,
5 as published by the Free Software Foundation.
6
7 This program is designed to work with certain software (including
8 but not limited to OpenSSL) that is licensed under separate terms,
9 as designated in a particular file or component or in included license
10 documentation. The authors of MySQL hereby grant you an additional
11 permission to link the program and your derivative works with the
12 separately licensed software that they have either included with
13 the program or referenced in the documentation.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License, version 2.0, for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24 /* See http://code.google.com/p/googletest/wiki/Primer */
25
26 #include <gtest/gtest.h>
27 #include <array>
28 #include <cstdint>
29 #include <random>
30 #include "unittest/gunit/benchmark.h"
31
32 #include "storage/innobase/include/mach0data.h"
33 #include "storage/innobase/include/univ.i"
34 #include "storage/innobase/include/ut0crc32.h"
35 #include "storage/innobase/include/ut0rnd.h"
36
37 #include "extra/xxhash/my_xxhash.h"
38
39 namespace innodb_ut0rnd_unittest {
40
41 namespace old_impl {
42
43 /* Old implementations to compare against. */
44
45 #define UT_RND1 151117737
46 #define UT_RND2 119785373
47 #define UT_RND3 85689495
48 #define UT_RND4 76595339
49 #define UT_SUM_RND2 98781234
50 #define UT_SUM_RND3 126792457
51 #define UT_SUM_RND4 63498502
52 #define UT_XOR_RND1 187678878
53 #define UT_XOR_RND2 143537923
54
55 static inline ulint ut_rnd_gen_next_ulint(ulint rnd) {
56 ulint n_bits;
57 n_bits = 8 * sizeof(ulint);
58 rnd = UT_RND2 * rnd + UT_SUM_RND3;
59 rnd = UT_XOR_RND1 ^ rnd;
60 rnd = (rnd << 20) + (rnd >> (n_bits - 20));
61 rnd = UT_RND3 * rnd + UT_SUM_RND4;
62 rnd = UT_XOR_RND2 ^ rnd;
63 rnd = (rnd << 20) + (rnd >> (n_bits - 20));
64 rnd = UT_RND1 * rnd + UT_SUM_RND2;
65 return (rnd);
66 }
67
68 thread_local ulint ut_rnd_ulint_counter;
69
70 static inline ulint ut_rnd_gen_ulint() {
71 ulint rnd = ut_rnd_ulint_counter;
72 if (rnd == 0) {
73 rnd = 65654363;
74 }
75
76 rnd = UT_RND1 * rnd + UT_RND2;
77
78 ut_rnd_ulint_counter = rnd;
79
80 return (ut_rnd_gen_next_ulint(rnd));
81 }
82
83 constexpr uint32_t UT_HASH_RANDOM_MASK = 1463735687;
84 constexpr uint32_t UT_HASH_RANDOM_MASK2 = 1653893711;
85
86 static inline ulint ut_hash_ulint(ulint key, ulint table_size) {
87 ut_ad(table_size);
88 key = key ^ UT_HASH_RANDOM_MASK2;
89
90 return (key % table_size);
91 }
92 static inline ulint ut_fold_ulint_pair(ulint n1, ulint n2) {
93 return (
94 ((((n1 ^ n2 ^ UT_HASH_RANDOM_MASK2) << 8) + n1) ^ UT_HASH_RANDOM_MASK) +
95 n2);
96 }
97
98 static inline ulint ut_fold_ull(uint64_t d) {
99 return (ut_fold_ulint_pair((ulint)d & std::numeric_limits<uint32_t>::max(),
100 (ulint)(d >> 32)));
101 }
102
103 } // namespace old_impl
104
105 static void init() {
106 ut::detail::random_seed = 0;
107 old_impl::ut_rnd_ulint_counter = 0;
108 }
109
110 struct random_data_t {
111 std::array<byte, 100000> data;
112 random_data_t() {
113 for (byte &b : data) {
114 b = rand();
115 }
116 }
117 };
118 random_data_t random_data{};
119
120 /* Correctness tests for hashing methods. */
121
122 TEST(ut0rnd, hash_binary_ib_basic) {
123 init();
124 /* This value is used in page checksum for innodb algorithm, if chosen. This
125 can't ever change to not make existing databases invalid. */
126 EXPECT_EQ(58956420, ut::hash_binary_ib((const byte *)"innodb", 6));
127 }
128
129 static double calculate_limit_variance_from_expected(uint32_t n) {
130 /* We set the limit arbitrarily. The higher N the lower the distance from
131 expected variation should be. The below formula has points at around:
132 3.00 for N=8,
133 0.65 for N=64,
134 0.25 for N=1024,
135 0.11 for N=10000 */
136 return 4.5 / log2(n / 2.0) + 0.75;
137 }
138
139 /** Tests if a given hasher produces a nice distribution. The buckets can't
140 differ in sizes more than 10% from the expected average. */
141 template <typename T, uint32_t N>
142 double test_distribution(const std::string &test_name, T hasher,
143 uint64_t multiplier) {
144 std::array<uint64_t, N> buckets{0};
145 std::array<uint64_t, N> max_res_buckets{0};
146 constexpr auto maxM = std::max(uint32_t{10000}, N * 5);
147 constexpr auto stepM = 3 * N;
148 const ut::fast_modulo_t N_mod{N};
149 int max_res_M = 0;
150 double max_res = 0;
151 const auto variance_limit = calculate_limit_variance_from_expected(N);
152 for (uint32_t M = stepM, i = 0; M <= maxM; M += stepM) {
153 for (; i < M; i++) {
154 uint32_t hash = hasher(i * multiplier, N_mod);
155 assert(hash < N);
156 buckets[hash]++;
157 }
158 /* Suppose I choose two of the M elements at random (with replacement) and
159 ask if they "collide" by being in the same bucket.
160 A bucket with k elements contributes k*k such collisions. */
161 uint64_t collisions = 0;
162 for (uint32_t j = 0; j < N; j++) {
163 collisions += buckets[j] * buckets[j];
164 }
165 /* Average number of elements in each bucket. */
166 const auto avg = 1.0 * M / N;
167 const auto minimum_possible_collisions = avg * avg * N;
168 const auto excess_collisions = collisions - minimum_possible_collisions;
169 /* If we just tossed M balls into N bins randomly, so that a ball landing in
170 a particular bin has a chance p=1/N, the variance would be M*(1/N)*(1-1/N).
171 Note that variance*N = sum {(buckets[j]-avg)^2} = excess_collisions.
172 */
173 const auto good_excess_collisions = 1.0 * M * (1 - 1.0 / N);
174 /* We calculate "score" as ratio of actual number of excess collisions to
175 the above good excess collisions. The lower the better. Also, we adjust
176 score based on value of M, so that small values of M are required to be
177 closer to the good variance and higher can have up to 50% more collisions
178 for the same score. */
179 const auto score = excess_collisions / good_excess_collisions /
180 (1 + std::min(0.5, 1.0 * (M - stepM) / 200));
181 if (score > max_res) {
182 max_res = score;
183 max_res_M = M;
184 max_res_buckets = buckets;
185 }
186 }
187 /* Print all distributions that get close to the limit (70% of it) */
188 if (max_res > 1 + (variance_limit - 1) * 0.7) {
189 std::cout << "Bad distribution found for test \"" << test_name
190 << "\", N=" << N << ", mult=" << multiplier
191 << ", max_res=" << max_res << " @ M=" << max_res_M
192 << ", limit=" << variance_limit << std::endl;
193 if (N < 100) {
194 for (auto a : max_res_buckets) {
195 std::cout << a << " ";
196 }
197 std::cout << std::endl;
198 }
199 }
200 return max_res;
201 }
202
203 template <typename T, uint32_t N>
204 void test_distribution(bool assert_distribution, const std::string &test_name,
205 T hasher) {
206 double score = 0;
207 constexpr auto P = 10;
208 for (int i = 0; i <= P; i++) {
209 score =
210 std::max(score, test_distribution<T, N>(test_name, hasher, 1ULL << i));
211 }
212 score = std::max(score, test_distribution<T, N>(test_name, hasher, 7));
213 score = std::max(score, test_distribution<T, N>(test_name, hasher, 11));
214 score =
215 std::max(score, test_distribution<T, N>(test_name, hasher, 2 * 3 * 5));
216
217 const auto variance_limit = calculate_limit_variance_from_expected(N);
218 std::cout << "Overall score for N=" << N << " is: " << score
219 << ", while the limit for good enough result is " << variance_limit
220 << std::endl;
221
222 if (assert_distribution) {
223 EXPECT_LE(score, variance_limit);
224 }
225 }
226
227 template <typename THash>
228 void test_distribution(bool assert_distribution, const std::string &test_name,
229 THash hasher) {
230 test_distribution<THash, 8>(assert_distribution, test_name,
231 hasher); // For 2^n distributions
232 test_distribution<THash, 10>(assert_distribution, test_name,
233 hasher); // For 10^n distributions
234 test_distribution<THash, 11>(assert_distribution, test_name,
235 hasher); // For small prime distribution
236 test_distribution<THash, 64>(assert_distribution, test_name,
237 hasher); // For 2^n distributions
238 test_distribution<THash, 1 << 10>(assert_distribution, test_name,
239 hasher); // For big 2^n distribution
240 test_distribution<THash, 1000>(assert_distribution, test_name,
241 hasher); // For big 10^n distribution
242 test_distribution<THash, 1 << 13>(assert_distribution, test_name,
243 hasher); // For big 2^n distribution
244 test_distribution<THash, 10 * 1000>(assert_distribution, test_name,
245 hasher); // For big 10^n distribution
246 }
247
248 /* Test distributions for algorithms that hash uint64_t. */
249
250 TEST(ut0rnd, hash_uint64_distribution) {
251 init();
252 ut_crc32_init();
253 test_distribution(true, "ut::hash_uint64(i)",
254 [](size_t i, const ut::fast_modulo_t &n) {
255 return ut::hash_uint64(i) % n;
256 });
257 }
258
259 TEST(ut0rnd, hash_std_hash_distribution) {
260 init();
261 test_distribution(false, "std::hash<uint64_t>{}(i)",
262 [](size_t i, const ut::fast_modulo_t &n) {
263 return std::hash<uint64_t>{}(i) % n;
264 });
265 }
266 TEST(ut0rnd, hash_uint32_old_distribution) {
267 init();
268 test_distribution(false, "old_impl::ut_hash_ulint(i, N)",
269 [](size_t i, const ut::fast_modulo_t &n) {
270 return old_impl::ut_hash_ulint(i, n.get_mod());
271 });
272 }
273
274 TEST(ut0rnd, hash_uint64_pair_sysbench_ahi_distribution) {
275 ut_crc32_init();
276 std::array<size_t, 8> buckets{};
277 for (int i = 0; i < 8; i++) {
278 uint32_t hash = ut::hash_uint64_pair(149 + 2 * i, i) % 8;
279 buckets[hash]++;
280 }
281
282 int res = 0;
283 for (int i = 0; i < 8; i++) {
284 if (buckets[i] != 0) {
285 res++;
286 }
287 }
288
289 EXPECT_GE(res, 6);
290
291 if (res < 6) {
292 for (auto a : buckets) {
293 std::cout << a << " ";
294 }
295 std::cout << std::endl;
296 }
297 }
298
299 /* Test uint64_pair distribution of a sequential BIGINT record as hashed by
300 ut::hash_binary(). This method will read it as little-endian, while the InnoDB
301 storage format for BIGINT is big-endian. */
302 TEST(ut0rnd, hash_uint64_pair_highest_byte_distribution) {
303 ut_crc32_init();
304 /* This test checks if hash_uint64_pair causes collisions when one of the
305 arguments is kept constant, and the other takes consecutive values.
306 Historically, the number of collisions depended mostly on the pattern of
307 lowest bits in the constant, so we try all possible lowest bytes. */
308 for (uint64_t seed = 0; seed < 256; ++seed) {
309 std::set<uint64_t> hashes_left, hashes_right;
310 for (uint64_t highest = 0; highest < 256; highest++) {
311 /* As mentioned in the test, we want to test a real-world example of a
312 BIGINT field as seen by `tuple->fields[0].data`. It has 7 bytes set, with
313 main non-zero part of the value in the highest bytes. The value of
314 `highest` byte will be inserted to the 8th, the highest byte of this
315 value and it represents the lowest byte of the BIGINT field's value. */
316 uint64_t rec = 0x9a533400000080ULL | (highest << (64 - 8));
317 EXPECT_TRUE(hashes_left.insert(ut::hash_uint64_pair(rec, seed)).second);
318 EXPECT_TRUE(hashes_right.insert(ut::hash_uint64_pair(seed, rec)).second);
319 }
320 }
321 }
322
323 /* Test distributions for algorithms that hash pair of uint32_t that are:
324 increasing together or with either one being constant. */
325
326 template <typename THash>
327 static void hash_pair_distribution_test(bool assert_distribution,
328 const std::string &test_name,
329 THash hasher) {
330 init();
331 ut_crc32_init();
332 test_distribution(assert_distribution, test_name + "(i, i)",
333 [&hasher](size_t i, const ut::fast_modulo_t &n) {
334 return hasher(i, i) % n;
335 });
336 test_distribution(assert_distribution, test_name + "(1, i)",
337 [&hasher](size_t i, const ut::fast_modulo_t &n) {
338 return hasher(1, i) % n;
339 });
340 test_distribution(assert_distribution, test_name + "(i, 1)",
341 [&hasher](size_t i, const ut::fast_modulo_t &n) {
342 return hasher(i, 1) % n;
343 });
344 /* Distribution basing on <index_id, space_id> generated for tables by
345 sysbench. */
346 test_distribution(assert_distribution, test_name + "(149+2*i, i)",
347 [&hasher](size_t i, const ut::fast_modulo_t &n) {
348 return hasher(149 + 2 * i, i) % n;
349 });
350 }
351
352 TEST(ut0rnd, hash_uint64_pair_distribution) {
353 hash_pair_distribution_test(true, "ut::hash_uint64_pair",
354 ut::hash_uint64_pair);
355 }
356
357 TEST(ut0rnd, hash_uint32_pair_old_distribution) {
358 hash_pair_distribution_test(false, "ut::detail::hash_uint32_pair_ib",
359 ut::detail::hash_uint32_pair_ib);
360 }
361
362 static void test_interval_fast_distribution(uint64_t n) {
363 const uint64_t max_count = n * 10000;
364 // min, mid, max are usecases
365 uint64_t target_score[][2] = {{0, 0}, {n / 2, 0}, {n - 1, 0}};
366
367 // variation is needed. not needed to be so accurate always.
368 const uint64_t min_score = 5000;
369 const uint64_t max_score = 17000;
370
371 for (uint64_t i = 0; i < max_count; i++) {
372 const auto value = ut::random_from_interval_fast(0, n);
373 for (auto target : target_score) {
374 if (value == target[0]) {
375 target[1]++;
376 }
377 }
378 ut_delay(ut::random_from_interval_fast(0, 6));
379 }
380
381 for (auto target : target_score) {
382 // EXPECT_GE(target[1], min_score);
383 // EXPECT_LE(target[1], max_score);
384
385 if (target[1] < min_score || target[1] > max_score) {
386 std::cout << "test_interval_fast_distribution " << target[0] << " for 0-"
387 << n - 1 << " : " << target[1] << " / " << max_count
388 << std::endl;
389 }
390 }
391 }
392
393 TEST(ut0rnd, random_from_interval_fast) {
394 init();
395 test_interval_fast_distribution(2); // 1/2
396 test_interval_fast_distribution(10); // 1/10
397 test_interval_fast_distribution(100); // 1/100
398 }
399
400 /* Micro-benchmark raw random generator performance. */
401
402 template <typename THash>
403 static void benchmark_hasher(const size_t num_iterations, THash hasher) {
404 init();
405 ut_crc32_init();
406
407 uint32_t fold = 1; // Non-zero value. Some hasher might return 0 for fold==0.
408 for (size_t n = 0; n < num_iterations * 1000; n++) {
409 fold += hasher(fold, n);
410 }
411 EXPECT_NE(0U, fold); // To keep the compiler from optimizing it away.
412 SetBytesProcessed(num_iterations * 1000);
413 }
414
415 static void BM_RND_GEN_OLD(const size_t num_iterations) {
416 benchmark_hasher(num_iterations, [](uint64_t, uint64_t) {
417 return old_impl::ut_rnd_gen_ulint();
418 });
419 }
420 BENCHMARK(BM_RND_GEN_OLD)
421
422 static void BM_RND_GEN_STD_HASH(const size_t num_iterations) {
423 benchmark_hasher(num_iterations, [](uint64_t, uint64_t n) {
424 return std::hash<uint64_t>{}(n);
425 });
426 }
427 BENCHMARK(BM_RND_GEN_STD_HASH)
428
429 #if SIZEOF_VOIDP >= 8
430 static void BM_RND_GEN_STD_LINEAR(const size_t num_iterations) {
431 std::linear_congruential_engine<uint64_t, 0xacb1f3526e25dd39,
432 0xf72a876a516b4b56,
433 std::numeric_limits<uint64_t>::max()>
434 eng;
435 benchmark_hasher(num_iterations,
436 [&eng](uint64_t, uint64_t n) { return eng(); });
437 }
438 BENCHMARK(BM_RND_GEN_STD_LINEAR)
439 #endif
440
441 static void BM_RND_GEN(const size_t num_iterations) {
442 benchmark_hasher(num_iterations,
443 [](uint64_t, uint64_t n) { return ut::random_64(); });
444 }
445 BENCHMARK(BM_RND_GEN)
446
447 static void BM_RND_GEN_FAST(const size_t num_iterations) {
448 benchmark_hasher(num_iterations,
449 [](uint64_t, uint64_t) { return ut::random_64_fast(); });
450 }
451 BENCHMARK(BM_RND_GEN_FAST)
452
453 /* Micro-benchmark raw uint64_t hash performance. */
454
455 static void BM_HASH_UINT64(const size_t num_iterations) {
456 benchmark_hasher(num_iterations, [](uint64_t fold, uint64_t) {
457 return ut::hash_uint64(fold);
458 });
459 }
460 BENCHMARK(BM_HASH_UINT64)
461
462 static void BM_HASH_UINT64_OLD(const size_t num_iterations) {
463 benchmark_hasher(num_iterations, [](uint64_t fold, uint64_t) {
464 return old_impl::ut_fold_ull(fold);
465 });
466 }
467 BENCHMARK(BM_HASH_UINT64_OLD)
468
469 /* Micro-benchmark raw pair of uint32_t hash performance. */
470
471 static void BM_HASH_UINT64_PAIR(const size_t num_iterations) {
472 benchmark_hasher(num_iterations, [](uint64_t fold, uint64_t n) {
473 return ut::hash_uint64_pair(fold, ut::random_64());
474 });
475 }
476 BENCHMARK(BM_HASH_UINT64_PAIR)
477
478 static void BM_HASH_UINT32_PAIR_OLD(const size_t num_iterations) {
479 benchmark_hasher(num_iterations, [](uint64_t fold, uint64_t n) {
480 return ut::detail::hash_uint32_pair_ib(fold, ut::random_64());
481 });
482 }
483 BENCHMARK(BM_HASH_UINT32_PAIR_OLD)
484
485 /* Micro-benchmark raw performance of several hashing algorithms of arbitrary
486 * string. */
487
488 #define BENCHMARK_HASH(NAME, N) \
489 static void BM_HASH_##NAME##_##N(size_t num_iterations) { \
490 BM_HASH_##NAME<N>(num_iterations); \
491 } \
492 BENCHMARK(BM_HASH_##NAME##_##N)
493 #define BENCHMARK_HASHES(NAME) \
494 BENCHMARK_HASH(NAME, 5) \
495 BENCHMARK_HASH(NAME, 16) \
496 BENCHMARK_HASH(NAME, 31) \
497 BENCHMARK_HASH(NAME, 63) \
498 BENCHMARK_HASH(NAME, 127) \
499 BENCHMARK_HASH(NAME, 255) \
500 BENCHMARK_HASH(NAME, 511) \
501 BENCHMARK_HASH(NAME, 1023) \
502 BENCHMARK_HASH(NAME, 2047) \
503 BENCHMARK_HASH(NAME, 4095) \
504 BENCHMARK_HASH(NAME, 8191) \
505 BENCHMARK_HASH(NAME, 16383) \
506 BENCHMARK_HASH(NAME, 32767) \
507 BENCHMARK_HASH(NAME, 65535)
508
509 template <uint32_t N, typename THash>
510 static void benchmark_binary_hasher(const size_t num_iterations, THash hasher) {
511 init();
512 ut_crc32_init();
513 uint64_t fold = 0;
514 size_t i = 0;
515 for (size_t n = 0; n < num_iterations * 1000; n++) {
516 i = i > 20000 - N ? i + 1 : 0;
517 fold = hasher(&random_data.data[i], fold);
518 }
519 EXPECT_NE(0U, fold); // To keep the compiler from optimizing it away.
520 SetBytesProcessed(num_iterations * N * 1000);
521 }
522
523 template <uint32_t N>
524 static void BM_HASH_BINARY_XXHASH(const size_t num_iterations) {
525 benchmark_binary_hasher<N>(num_iterations, [](byte *buf, uint64_t fold) {
526 return XXH64(buf, N, fold);
527 });
528 }
529 BENCHMARK_HASHES(BINARY_XXHASH)
530
531 template <uint32_t N>
532 static void BM_HASH_BINARY_STD(const size_t num_iterations) {
533 benchmark_binary_hasher<N>(num_iterations, [](byte *buf, uint64_t fold) {
534 return ut::hash_uint64_pair(
535 fold,
536 std::hash<std::string_view>{}(std::string_view((const char *)buf, N)));
537 });
538 }
539 BENCHMARK_HASHES(BINARY_STD)
540
541 template <uint32_t N>
542 static void BM_HASH_BINARY_OLD(const size_t num_iterations) {
543 benchmark_binary_hasher<N>(num_iterations, [](byte *buf, uint64_t fold) {
544 return ut::hash_uint64_pair(fold, ut::hash_binary_ib(buf, N));
545 });
546 }
547 BENCHMARK_HASHES(BINARY_OLD)
548
549 template <uint32_t N>
550 static void BM_HASH_BINARY_UT(const size_t num_iterations) {
551 benchmark_binary_hasher<N>(num_iterations, [](byte *buf, uint64_t fold) {
552 return ut::hash_uint64_pair(fold, ut::hash_binary(buf, N));
553 });
554 }
555 BENCHMARK_HASHES(BINARY_UT)
556
557 template <uint32_t N>
558 static void BM_HASH_BINARY_CRC32(const size_t num_iterations) {
559 benchmark_binary_hasher<N>(num_iterations, [](byte *buf, uint64_t fold) {
560 return ut::hash_uint64_pair(fold, ut_crc32(buf, N));
561 });
562 }
563 BENCHMARK_HASHES(BINARY_CRC32)
564
565 } // namespace innodb_ut0rnd_unittest