Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
hash_allocation_failure_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
41#include <gtest/gtest.h>
42
43#include "allocation_failure.H"
44
45#include <cstdlib>
46#include <new>
47#include <string>
48#include <utility>
49#include <vector>
50
51#include <tpl_dynLhash.H>
52#include <tpl_dynSetHash.H>
53#include <tpl_lhash.H>
54#include <tpl_linHash.H>
55#include <tpl_odhash.H>
56#include <tpl_olhash.H>
57
58using namespace Aleph;
59
60// The tests need the operator new of allocation_failure.H
61struct HashTableWithoutMemory : public ::testing::Test
62{
63 void SetUp() override
64 {
66 GTEST_SKIP() << "ThreadSanitizer replaces the global operator new";
67 }
68};
69
70namespace
71{
72 // Number of non-empty lists of a chained or linear table, counted
73 template <class Table> size_t busy_lists(const Table & table)
74 {
75 const auto stats = table.stats();
76 return table.capacity() - (stats.lens.size() > 0 ? stats.lens(0) : 0);
77 }
78}
79
80// remove() of a chained table is noexcept; when it shrank the table and
81// there was no memory for the smaller one, it ended the program.
82TEST_F(HashTableWithoutMemory, ChainedRemovalKeepsTheCapacity)
83{
85 LhashTable<int> table(101, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
87 true, true);
88 std::vector<Bucket *> buckets;
89 for (int k = 0; k < 1000; ++k)
90 {
91 buckets.push_back(new Bucket(k));
92 ASSERT_NE(table.insert(buckets.back()), nullptr) << "key " << k;
93 }
94 const size_t grown = table.capacity();
95
96 size_t refused = 0;
97 {
98 No_Memory no_memory;
99 for (int k = 0; k < 990; ++k)
100 delete table.remove(buckets[k]);
101 refused = refused_allocations;
102 }
103
104 EXPECT_GT(refused, 0u); // it tried to shrink
105 EXPECT_EQ(table.capacity(), grown);
106 EXPECT_EQ(table.size(), 10u);
107 EXPECT_EQ(table.get_num_busy_slots(), busy_lists(table));
108 for (int k = 990; k < 1000; ++k)
109 EXPECT_EQ(table.search(k), buckets[k]) << "key " << k;
110
111 // with memory again, the next removal shrinks it
112 delete table.remove(buckets[990]);
113 EXPECT_LT(table.capacity(), grown);
114 for (int k = 991; k < 1000; ++k)
115 {
116 EXPECT_EQ(table.search(k), buckets[k]) << "key " << k;
117 delete table.remove(buckets[k]);
118 }
119 EXPECT_TRUE(table.is_empty());
120}
121
122// next_prime() gives a prime of its table, and the one after 101 is 211:
123// half of 211 is 211 again, so every removal from a table of 211 lists
124// under the lower threshold rebuilt it as it was.
125TEST_F(HashTableWithoutMemory, ChainedRemovalDoesNotRebuildToTheSameCapacity)
126{
127 using Bucket = LhashBucket<int>;
128 LhashTable<int> table(211, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
130 true, true);
131 ASSERT_EQ(table.capacity(), 211u);
132 std::vector<Bucket *> buckets;
133 for (int k = 0; k < 20; ++k) // under 0.25 of 211
134 {
135 buckets.push_back(new Bucket(k));
136 ASSERT_NE(table.insert(buckets.back()), nullptr) << "key " << k;
137 }
138
139 const size_t before = allocations;
140 for (int k = 0; k < 10; ++k)
141 delete table.remove(buckets[k]);
142 EXPECT_EQ(allocations, before);
143 EXPECT_EQ(table.capacity(), 211u);
144
145 for (int k = 10; k < 20; ++k)
146 delete table.remove(buckets[k]);
147}
148
149// With a lower threshold over half the upper one, half the capacity may
150// leave the keys over the upper threshold. Such a removal shrank the
151// table, and resize(), which places the keys again with insert(), grew it
152// back at once: two rebuilds for nothing.
153TEST_F(HashTableWithoutMemory, ChainedRemovalDoesNotShrinkWhereTheKeysWouldNotFit)
154{
155 using Bucket = LhashBucket<int>;
156 LhashTable<int> table(47, Aleph::dft_hash_fct<int>, Aleph::equal_to<int>(),
157 0.85f, 0.9f, true, true);
158 ASSERT_EQ(table.capacity(), 47u);
159 std::vector<Bucket *> buckets;
160 for (int k = 0; k < 22; ++k)
161 {
162 buckets.push_back(new Bucket(k));
163 ASSERT_NE(table.insert(buckets.back()), nullptr) << "key " << k;
164 }
165
166 const size_t before = allocations;
167 delete table.remove(buckets[0]); // 21 keys in 23 lists: 0.91
168 EXPECT_EQ(allocations, before);
169 EXPECT_EQ(table.capacity(), 47u);
170
171 delete table.remove(buckets[1]); // 20 keys in 23 lists: 0.87
172 EXPECT_EQ(table.capacity(), 23u);
173
174 for (int k = 2; k < 22; ++k)
175 delete table.remove(buckets[k]);
176}
177
178template <class Table> struct OpenTableWithoutMemory : public HashTableWithoutMemory
179{
180 static Table make()
181 {
182 if constexpr (requires (Table & t) { t.get_second_hash_fct(); })
183 return Table(11, Aleph::dft_hash_ptr_fct<long>,
184 Aleph::snd_hash_ptr_fct<long>, Aleph::equal_to<long>(),
186 else
187 return Table(11, Aleph::dft_hash_ptr_fct<long>, Aleph::equal_to<long>(),
189 }
190};
191
192using Open_Tables = ::testing::Types<OLhashTable<long>, ODhashTable<long>>;
194
195// remove_ptr() threw std::bad_alloc after it had removed the key.
196TYPED_TEST(OpenTableWithoutMemory, RemovalsKeepTheCapacity)
197{
198 TypeParam table = this->make();
199 for (long k = 0; k < 1000; ++k)
200 ASSERT_NE(table.insert(k), nullptr) << "key " << k;
201 const size_t grown = table.capacity();
202
203 size_t refused = 0, threw = 0;
204 {
205 No_Memory no_memory;
206 for (long k = 0; k < 990; ++k)
207 try
208 {
209 if (k % 2 == 0)
210 table.remove(k);
211 else
212 table.remove_ptr(table.search(k));
213 }
214 catch (...)
215 {
216 ++threw;
217 }
218 refused = refused_allocations;
219 }
220
221 EXPECT_EQ(threw, 0u);
222 EXPECT_GT(refused, 0u);
223 EXPECT_EQ(table.capacity(), grown);
224 EXPECT_EQ(table.size(), 10u);
225 for (long k = 0; k < 1000; ++k)
226 EXPECT_EQ(table.contains(k), k >= 990) << "key " << k;
227
228 table.remove(990L);
229 EXPECT_LT(table.capacity(), grown);
230 for (long k = 991; k < 1000; ++k)
231 EXPECT_TRUE(table.contains(k)) << "key " << k;
232}
233
234namespace
235{
236 size_t identity_hash(const size_t & k) noexcept
237 {
238 return k;
239 }
240}
241
242// When linear hashing contracts, it merges its last list into the list
243// that it was split from. In a lazily allocated table that list may never
244// have been written, and contract() allocates it. contract() was noexcept
245// and changed the table before allocating.
246//
247// The table starts with 8193 lists. Its keys never touch the block of
248// lists [4096, 8192) of its array (blocks have 4096 lists): their values
249// modulo 8193 are under 4096. Once list 4096 has been split, key 12289
250// goes straight to list 12289 = 4096 + 8193, so contracting into list
251// 4096 has to allocate that block.
252TEST_F(HashTableWithoutMemory, LinearContractionKeepsTheTable)
253{
255 using Bucket = Table::Bucket;
256 constexpr size_t len = 8193;
257 Table table(len, identity_hash, Aleph::equal_to<size_t>(),
259
260 std::vector<Bucket *> fillers;
261 for (size_t t = 0; table.capacity() <= len + 4097; ++t)
262 for (size_t r = 0; r < 4096 and table.capacity() <= len + 4097; ++r)
263 {
264 fillers.push_back(new Bucket(r + len * t));
265 ASSERT_NE(table.insert(fillers.back()), nullptr);
266 }
267 auto * special = new Bucket(4096 + len);
268 ASSERT_NE(table.insert(special), nullptr);
269 const size_t expanded = table.capacity();
270 ASSERT_GT(expanded, len + 4097);
271
272 size_t refused = 0, removed = 0;
273 {
274 No_Memory no_memory;
275 for (; removed < fillers.size() - 100; ++removed)
276 delete table.remove(fillers[removed]);
277 refused = refused_allocations;
278 }
279
280 EXPECT_GT(refused, 0u); // it had to allocate the block of list 4096
281 EXPECT_GE(table.capacity(), len + 4097); // it stopped before that list
282 EXPECT_EQ(table.size(), 101u);
283 EXPECT_EQ(table.busy_slots(), busy_lists(table));
284 EXPECT_EQ(table.search(4096 + len), special);
285 for (size_t i = removed; i < fillers.size(); ++i)
286 EXPECT_EQ(table.search(fillers[i]->get_key()), fillers[i]) << i;
287
288 // with memory again, the next removal goes on contracting
289 delete table.remove(fillers[removed++]);
290 EXPECT_LT(table.capacity(), len + 4097);
291 EXPECT_EQ(table.busy_slots(), busy_lists(table));
292 EXPECT_EQ(table.search(4096 + len), special);
293 for (size_t i = removed; i < fillers.size(); ++i)
294 EXPECT_EQ(table.search(fillers[i]->get_key()), fillers[i]) << i;
295}
296
297namespace
298{
299 // A key that counts those that are alive: a bucket that is not freed
300 // keeps one
301 struct Live_Key
302 {
303 static inline long alive = 0;
304 int value = 0;
305
306 Live_Key() noexcept { ++alive; }
307 Live_Key(const int v) noexcept : value(v) { ++alive; }
308 Live_Key(const Live_Key & k) noexcept : value(k.value) { ++alive; }
309 Live_Key & operator = (const Live_Key &) noexcept = default;
310 ~Live_Key() { --alive; }
311
312 bool operator == (const Live_Key & k) const noexcept { return value == k.value; }
313 };
314
315 size_t aleph_hash_value(const Live_Key & k) noexcept
316 {
317 return static_cast<size_t>(k.value) * 40503u;
318 }
319
320 // The first insertion in `moved_from`, a set that a move left, fails for
321 // want of memory after the bucket of the key was made: the bucket must
322 // be freed, the set must be as it was, and with memory it takes the key
323 template <class Set>
324 void expect_a_failed_first_insertion_to_leak_nothing(Set & moved_from, const size_t failing)
325 {
326 const long alive = Live_Key::alive;
327 const size_t capacity = moved_from.capacity();
328 {
329 const Fail_At fail_at(failing);
330 EXPECT_THROW((void) moved_from.insert(Live_Key(7)), std::bad_alloc);
331 }
332 EXPECT_EQ(Live_Key::alive, alive);
333 EXPECT_TRUE(moved_from.is_empty());
334 EXPECT_EQ(moved_from.capacity(), capacity);
335 EXPECT_FALSE(moved_from.contains(Live_Key(7)));
336
337 ASSERT_NE(moved_from.insert(Live_Key(7)), nullptr);
338 EXPECT_EQ(Live_Key::alive, alive + 1);
339 EXPECT_TRUE(moved_from.contains(Live_Key(7)));
340 }
341}
342
343// A table of chained lists that a move left without lists takes those of
344// the default capacity when a key enters it. Without memory for them the
345// insertion throws, when the bucket of the key is made already: nothing
346// else holds it, so it must be freed
347TEST_F(HashTableWithoutMemory, AFailedFirstInsertionInAChainedSetWithoutListsFreesItsBucket)
348{
350 for (int i = 0; i < 20; ++i)
351 ASSERT_NE(source.insert(Live_Key(i)), nullptr);
352 DynSetLhash<Live_Key> target(std::move(source));
353 ASSERT_EQ(source.capacity(), 0u);
354
355 // the bucket is the first allocation of the insertion, and the lists
356 // are the second one
357 expect_a_failed_first_insertion_to_leak_nothing(source, 2);
358 EXPECT_EQ(source.capacity(), Primes::DefaultPrime);
359 EXPECT_EQ(target.size(), 20u);
360}
361
362TEST_F(HashTableWithoutMemory, AFailedFirstInsertionInAChainedMapWithoutListsFreesItsBucket)
363{
364 const long before = Live_Key::alive;
365 {
367 for (int i = 0; i < 20; ++i)
368 source.insert(i, Live_Key(i));
369 DynMapHash<int, Live_Key> target(std::move(source));
370 ASSERT_EQ(source.capacity(), 0u);
371
372 const long alive = Live_Key::alive;
373 {
374 const Fail_At fail_at(2);
375 EXPECT_THROW((void) source.insert(7, Live_Key(7)), std::bad_alloc);
376 }
377 EXPECT_EQ(Live_Key::alive, alive);
378 EXPECT_TRUE(source.is_empty());
379 EXPECT_EQ(source.search(7), nullptr);
380
381 source.insert(7, Live_Key(70));
382 EXPECT_EQ(source.find(7).value, 70);
383 EXPECT_EQ(target.size(), 20u);
384 }
385 EXPECT_EQ(Live_Key::alive, before);
386}
387
388TEST_F(HashTableWithoutMemory, AFailedFirstInsertionInADynLhashTableWithoutListsFreesItsBucket)
389{
390 const long before = Live_Key::alive;
391 {
393 for (int i = 0; i < 20; ++i)
394 ASSERT_NE(source.insert(i, Live_Key(i)), nullptr);
395 DynLhashTable<int, Live_Key> target(std::move(source));
396 ASSERT_EQ(source.search(3), nullptr);
397
398 const long alive = Live_Key::alive;
399 {
400 const Fail_At fail_at(2);
401 EXPECT_THROW((void) source.insert(7, Live_Key(7)), std::bad_alloc);
402 }
403 EXPECT_EQ(Live_Key::alive, alive);
404 {
405 const Fail_At fail_at(2);
406 EXPECT_THROW(source[8] = Live_Key(8), std::bad_alloc);
407 }
408 EXPECT_EQ(Live_Key::alive, alive);
409 EXPECT_EQ(source.search(7), nullptr);
410 EXPECT_EQ(source.search(8), nullptr);
411
412 ASSERT_NE(source.insert(7, Live_Key(70)), nullptr);
413 source[8] = Live_Key(80);
414 ASSERT_NE(source.search(7), nullptr);
415 EXPECT_EQ(source.search(7)->value, 70);
416 ASSERT_NE(source.search(8), nullptr);
417 EXPECT_EQ(source.search(8)->value, 80);
418 ASSERT_NE(target.search(3), nullptr);
419 }
420 EXPECT_EQ(Live_Key::alive, before);
421}
422
423// The first key of a list of a linear table makes that list, in a block
424// of the array of the table. Without memory for the block the insertion
425// throws, when the bucket of the key is made already: it was not freed
426TEST_F(HashTableWithoutMemory, AFailedInsertionInALinearSetFreesItsBucket)
427{
428 const long before = Live_Key::alive;
429 {
431 const long alive = Live_Key::alive;
432 bool threw = false;
433 // the allocation that fails is the first one after that of the bucket
434 // that the insertion makes for the array of the table
435 for (size_t failing = 2; failing < 6 and not threw; ++failing)
436 {
437 const Fail_At fail_at(failing);
438 try
439 {
440 (void) set.insert(Live_Key(7));
441 }
442 catch (const std::bad_alloc &)
443 {
444 threw = true;
445 }
446 if (not threw)
447 {
448 ASSERT_TRUE(set.contains(Live_Key(7)));
449 set.remove(Live_Key(7));
450 }
451 }
452 if (threw) // an array that allocates with malloc() does not fail here
453 {
454 EXPECT_EQ(Live_Key::alive, alive);
455 EXPECT_TRUE(set.is_empty());
456 EXPECT_FALSE(set.contains(Live_Key(7)));
457 }
458 ASSERT_NE(set.insert(Live_Key(7)), nullptr);
459 EXPECT_TRUE(set.contains(Live_Key(7)));
460 }
461 EXPECT_EQ(Live_Key::alive, before);
462}
463
464// The searches that insert the key that they do not find take the lists as
465// insert() does
466TEST_F(HashTableWithoutMemory, AFailedFirstSearchOrInsertInAChainedSetWithoutListsFreesItsBucket)
467{
469 for (int i = 0; i < 20; ++i)
470 ASSERT_NE(source.insert(Live_Key(i)), nullptr);
471 DynSetLhash<Live_Key> target(std::move(source));
472 ASSERT_EQ(source.capacity(), 0u);
473
474 const long alive = Live_Key::alive;
475 {
476 const Fail_At fail_at(2);
477 EXPECT_THROW((void) source.search_or_insert(Live_Key(7)), std::bad_alloc);
478 }
479 EXPECT_EQ(Live_Key::alive, alive);
480 {
481 const Fail_At fail_at(2);
482 EXPECT_THROW((void) source.contains_or_insert(Live_Key(7)), std::bad_alloc);
483 }
484 EXPECT_EQ(Live_Key::alive, alive);
485 EXPECT_TRUE(source.is_empty());
486 EXPECT_EQ(source.capacity(), 0u);
487
488 ASSERT_NE(source.search_or_insert(Live_Key(7)), nullptr);
489 EXPECT_TRUE(source.contains(Live_Key(7)));
490 EXPECT_EQ(Live_Key::alive, alive + 1);
491}
492
493// An insertion that fills a table makes it grow. Without memory for the
494// larger table the insertion throws, when the bucket is in its list
495// already: the table has the key, and owns its bucket
496TEST_F(HashTableWithoutMemory, AFailedGrowthKeepsTheKeyThatWasInserted)
497{
498 // the number of keys whose insertion makes a table grow for the first time
499 int growing = 0;
500 {
502 const size_t capacity = probe.capacity();
503 while (probe.capacity() == capacity)
504 ASSERT_NE(probe.insert(Live_Key(growing++)), nullptr);
505 }
506 ASSERT_GT(growing, 1);
507
508 const long before = Live_Key::alive;
509 {
511 for (int i = 0; i < growing - 1; ++i)
512 ASSERT_NE(set.insert(Live_Key(i)), nullptr);
513 const size_t capacity = set.capacity();
514 const long alive = Live_Key::alive;
515 {
516 // the bucket is the first allocation, and the larger table the second
517 const Fail_At fail_at(2);
518 EXPECT_THROW((void) set.insert(Live_Key(growing - 1)), std::bad_alloc);
519 }
520 EXPECT_EQ(set.capacity(), capacity);
521 EXPECT_EQ(set.size(), static_cast<size_t>(growing));
522 EXPECT_TRUE(set.contains(Live_Key(growing - 1)));
523 EXPECT_EQ(Live_Key::alive, alive + 1);
524 for (int i = 0; i < growing; ++i)
525 ASSERT_TRUE(set.contains(Live_Key(i))) << i;
526 }
527 EXPECT_EQ(Live_Key::alive, before); // each bucket was freed once
528}
A global operator new that a test can make fail.
#define ALEPH_ALLOCATION_FAILURE_UNDER_TSAN
size_t size_t int32_t value
Definition ca-c-api.h:116
bool contains(const Key &key) const noexcept
Return true if the key exists in the table.
void remove(Key *key)
Removes a key from the hash table using its pointer.
Key * insert(const Key &key)
Inserts key into the hash set.
bool is_empty() const noexcept
Checks if the container is empty.
Dynamic hash table mapping keys to records with separate chaining.
Record * search(const Key &key)
Search for a key in the table.
Bucket * remove(Bucket *bucket) noexcept
Removes bucket from the table.
Definition tpl_lhash.H:587
Bucket * insert(Bucket *bucket)
Inserts bucket into the table and returns its address if the key is not already in the table; otherwi...
Definition tpl_lhash.H:503
const size_t & get_num_busy_slots() const noexcept
Returns the number of occupied entries in the array.
Definition tpl_lhash.H:701
const size_t & size() const noexcept
Returns the number of elements contained in the table.
Definition tpl_lhash.H:697
const size_t & capacity() const noexcept
Returns the table capacity.
Definition tpl_lhash.H:694
Bucket * search(const Key &key) const noexcept
Search in the table for a bucket with key.
Definition tpl_lhash.H:555
constexpr bool is_empty() const noexcept
Definition tpl_lhash.H:703
Generic linear hash table.
const size_t & capacity() const noexcept
Returns the table capacity.
const size_t & size() const noexcept
Returns the number of elements in the table.
Bucket * remove(Bucket *bucket) noexcept
Removes bucket from the table, without freeing it.
BucketType< Key > Bucket
The bucket type.
const size_t & busy_slots() const noexcept
Returns the number of busy slots in the table.
Bucket * insert(Bucket *bucket)
Insert bucket in the table.
Bucket * search(const Key &key) const noexcept
Search for key in the linear hash table.
Open addressing hash table with double hashing collision resolution.
Definition tpl_odhash.H:193
Stats stats() const
Computes statistics about chain length distribution.
Definition hashDry.H:1470
TEST_F(HashTableWithoutMemory, ChainedRemovalKeepsTheCapacity)
TYPED_TEST(OpenTableWithoutMemory, RemovalsKeepTheCapacity)
TYPED_TEST_SUITE(OpenTableWithoutMemory, Open_Tables)
::testing::Types< OLhashTable< long >, ODhashTable< long > > Open_Tables
Table::Bucket Bucket
Definition lin-hash.cc:57
LinearHashTable< int > Table
Definition lin-hash.cc:56
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
const float hash_default_upper_alpha
Definition hash-dry.C:40
size_t aleph_hash_value(const AdversarialTranspositionKey< StateKey > &key) noexcept
Definition Negamax.H:134
and
Check uniqueness with explicit hash + equality functors.
const float hash_default_lower_alpha
Definition hash-dry.C:38
const unsigned long DefaultPrime
Default prime number used when no specific size is requested.
Definition primes.C:381
Hash-based dynamic set (defined in tpl_dynSetHash.H).
Generic hash table with collision resolution by separate chaining and buckets without virtual destruc...
Definition tpl_lhash.H:1008
static int * k
Gsl_Compatible_Rng r
Dynamic hash table mapping keys to records with separate chaining.
Dynamic set implementations based on hash tables.
Hash tables with collision resolution by separate chaining.
Linear hashing with chaining.
Open addressing hash table with double hashing.
Open addressing hash table with linear probing.