Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
howard_fallback_memory_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
31
46// Self-containment check: must stay the first include.
48
49# include <gtest/gtest.h>
50
51# include <cstdio>
52# include <cstdlib>
53# include <new>
54# include <random>
55# include <tuple>
56# include <vector>
57
58# include <tpl_graph.H>
59
61
62using namespace Aleph;
63using namespace Negative_Cycles_Test_Support;
64
65# if defined(__SANITIZE_ADDRESS__) or defined(__SANITIZE_THREAD__) \
66 or defined(__SANITIZE_HWADDRESS__)
67# define PROBE_ALLOCATIONS 0
68# elif defined(__has_feature)
69# if __has_feature(address_sanitizer) or __has_feature(thread_sanitizer) \
70 or __has_feature(memory_sanitizer) or __has_feature(hwaddress_sanitizer)
71# define PROBE_ALLOCATIONS 0
72# endif
73# endif
74# ifndef PROBE_ALLOCATIONS
75# define PROBE_ALLOCATIONS 1
76# endif
77
78namespace
79{
80 // The two largest allocation requests while `active`. Plain variables: the
81 // tests record in a single thread, and the functions below cannot allocate.
82 struct Allocation_Probe
83 {
84 bool active = false;
85 size_t largest = 0;
86 size_t second = 0;
87
88 void start() noexcept
89 {
90 largest = 0;
91 second = 0;
92 active = true;
93 }
94
95 void stop() noexcept
96 {
97 active = false;
98 }
99 };
100
101 Allocation_Probe probe;
102} // namespace
103
104# if PROBE_ALLOCATIONS
105
106// Not inlined: GCC cannot then pair the malloc behind `operator new` with the
107// free behind `operator delete` and warn about a mismatch.
108# if defined(__GNUC__)
109# define PROBE_NOINLINE __attribute__((noinline))
110# else
111# define PROBE_NOINLINE
112# endif
113
114namespace
115{
116 void * probed_malloc(const std::size_t size) noexcept
117 {
118 if (probe.active)
119 {
120 if (size > probe.largest)
121 {
122 probe.second = probe.largest;
123 probe.largest = size;
124 }
125 else if (size > probe.second)
126 probe.second = size;
127 }
128 return std::malloc(size == 0 ? 1 : size);
129 }
130} // namespace
131
132// Every form without an alignment: the nothrow ones too, which gtest uses
133// and a sanitizer would otherwise serve with its own allocator, mismatched
134// with the free() below.
135PROBE_NOINLINE void * operator new(const std::size_t size)
136{
137 if (void * p = probed_malloc(size))
138 return p;
139 std::fputs("howard_fallback_memory_test: out of memory\n", stderr);
140 std::abort();
141}
142
143PROBE_NOINLINE void * operator new[](const std::size_t size) { return operator new(size); }
144PROBE_NOINLINE void * operator new(const std::size_t size, const std::nothrow_t &) noexcept
145{
146 return probed_malloc(size);
147}
148PROBE_NOINLINE void * operator new[](const std::size_t size, const std::nothrow_t &) noexcept
149{
150 return probed_malloc(size);
151}
152PROBE_NOINLINE void operator delete(void * p) noexcept { std::free(p); }
153PROBE_NOINLINE void operator delete[](void * p) noexcept { std::free(p); }
154PROBE_NOINLINE void operator delete(void * p, std::size_t) noexcept { std::free(p); }
155PROBE_NOINLINE void operator delete[](void * p, std::size_t) noexcept { std::free(p); }
156PROBE_NOINLINE void operator delete(void * p, const std::nothrow_t &) noexcept { std::free(p); }
157PROBE_NOINLINE void operator delete[](void * p, const std::nothrow_t &) noexcept { std::free(p); }
158
159# endif // PROBE_ALLOCATIONS
160
161namespace
162{
163 // What Array reserves for `count` elements: the smallest power of two not
164 // below it.
165 size_t reserved(const size_t count)
166 {
167 size_t p = 1;
168 while (p < count)
169 p <<= 1;
170 return p;
171 }
172
173 // A single strongly connected component: a ring through the n nodes, plus
174 // one random chord out of each node.
175 template <class GT, typename W, class Weight>
176 Built_Graph_T<GT> ring(const size_t n, std::mt19937_64 & rng, Weight weight)
177 {
178 std::vector<std::tuple<size_t, size_t, W>> arcs;
179 for (size_t i = 0; i < n; ++i)
180 {
181 arcs.emplace_back(i, (i + 1) % n, weight(rng));
182 arcs.emplace_back(i, static_cast<size_t>(rng() % n), weight(rng));
183 }
185 }
186
187 // Run the fallback (iteration limit 0) under the probe, with the limit
188 // `limit`, with or without the witness.
189 template <bool With_Witness, class GT>
191 probed_fallback(const GT & g, const size_t limit)
192 {
193 using D = Dft_Dist<GT>;
194 using S = Dft_Show_Arc<GT>;
195 probe.start();
196 auto r = howard_detail::minimum_mean_cycle<GT, D, S, With_Witness>(g, D(), S(), 0, limit);
197 probe.stop();
198 return r;
199 }
200
201 template <bool With_Witness, class GT>
202 bool refused(const GT & g, const size_t limit)
203 {
204 using D = Dft_Dist<GT>;
205 using S = Dft_Show_Arc<GT>;
206 try
207 {
208 (void) howard_detail::minimum_mean_cycle<GT, D, S, With_Witness>(g, D(), S(), 0, limit);
209 }
210 catch (const std::length_error &)
211 {
212 return true;
213 }
214 return false;
215 }
216} // namespace
217
218
220{
222 GTEST_SKIP() << "a sanitizer provides the allocation functions";
223
224 // For one component of n nodes, Karp's tables are the largest allocations
225 // of the whole call: (n + 1) * n sums and, with the witness, as many
226 // predecessor positions, each table rounded up by Array to a power of two
227 // (1101 * 1100 = 1211100 entries take 2^21). The limit has to count exactly
228 // that: the call passes with it and is refused one byte below.
229 std::mt19937_64 rng(0xC3);
230 const auto small = [](std::mt19937_64 & r) { return static_cast<long long>(r() % 2001) - 1000; };
231 const auto unit = [](std::mt19937_64 & r) { return std::uniform_real_distribution<double>(-1, 1)(r); };
232
233 for (const size_t n : {120u, 400u, 1100u})
234 {
235 const size_t entries = reserved((n + 1) * n);
236
237 auto ib = ring<Graph, long long>(n, rng, small);
238 const size_t sums = entries * sizeof(long long);
239 const size_t preds = entries * sizeof(size_t);
240 const auto r = probed_fallback<true>(ib.g, sums + preds);
241 ASSERT_TRUE(r.used_karp) << "n=" << n;
242 EXPECT_EQ(probe.largest, sums) << "n=" << n;
243 EXPECT_EQ(probe.second, preds) << "n=" << n;
244 EXPECT_TRUE(refused<true>(ib.g, sums + preds - 1)) << "n=" << n;
245
246 const auto v = probed_fallback<false>(ib.g, sums);
247 ASSERT_TRUE(v.used_karp) << "n=" << n;
248 EXPECT_EQ(v.minimum_mean, r.minimum_mean) << "n=" << n;
249 EXPECT_EQ(probe.largest, sums) << "n=" << n;
250 EXPECT_LT(probe.second, sums / 4) << "n=" << n; // no second table
251 EXPECT_TRUE(refused<false>(ib.g, sums - 1)) << "n=" << n;
252
254 const size_t dsums = entries * sizeof(double);
255 const auto f = probed_fallback<true>(fb.g, dsums + preds);
256 ASSERT_TRUE(f.used_karp) << "n=" << n;
257 EXPECT_EQ(probe.largest, dsums) << "n=" << n;
258 EXPECT_TRUE(refused<true>(fb.g, dsums + preds - 1)) << "n=" << n;
259 }
260}
261
262
264{
266 GTEST_SKIP() << "a sanitizer provides the allocation functions";
267
268 // Weights of about 2^61: n * max|w| leaves long long, so the sums of the
269 // table take 128 bits where the compiler has them, 8 checked bytes
270 // otherwise. Only the value: the cost of a witness could leave long long.
271 std::mt19937_64 rng(0x16);
272 const auto big = [](std::mt19937_64 & r)
273 {
274 const long long m = (1LL << 61) + static_cast<long long>(r() % (1ULL << 60));
275 return r() % 2 ? m : -m;
276 };
277 const size_t n = 300;
278 auto built = ring<Graph, long long>(n, rng, big);
279# if ALEPH_KARP_INT128
280 const size_t sums = reserved((n + 1) * n) * 16;
281# else
282 const size_t sums = reserved((n + 1) * n) * sizeof(long long);
283# endif
285 try
286 {
287 v = probed_fallback<false>(built.g, sums);
288 }
289 catch (const std::overflow_error &) // only possible with checked long long sums
290 {
291 probe.stop();
292 GTEST_SKIP() << "the checked long long sums overflowed";
293 }
295 EXPECT_EQ(probe.largest, sums);
296 EXPECT_TRUE(refused<false>(built.g, sums - 1));
297}
298
299
301{
303 GTEST_SKIP() << "a sanitizer provides the allocation functions";
304
305 // Audit 2026-10-02, H5, and the acceptance of stage C: two components of
306 // three nodes among thousands of isolated ones. Howard falls back (the
307 // scaled bias of the first component overflows), and no allocation of the
308 // whole call grows with the square of the number of nodes. The largest
309 // ones are the snapshot's, linear in it; a table over all the nodes would
310 // take hundreds of MiB.
311 const long long big = 3100000000000000000LL;
312 for (const size_t isolated : {1000u, 3000u})
313 {
314 const size_t nodes = 6 + isolated;
315 auto built = build_graph(nodes, {{0, 1, big}, {1, 2, -big}, {2, 0, 1},
316 {3, 4, -1}, {4, 5, -1}, {5, 3, -2}});
317 probe.start();
318 const auto r = howard_minimum_mean_cycle(built.g);
319 probe.stop();
320 ASSERT_TRUE(r.used_karp) << "isolated=" << isolated;
321 ASSERT_EQ(r.fallback_reason, Howard_Fallback_Reason::Arithmetic_Overflow);
322 EXPECT_EQ(r.minimum_mean, -4.0L / 3.0L);
323 EXPECT_LT(probe.largest, 64 * nodes) << "isolated=" << isolated; // linear, not quadratic
324 }
325}
Minimum mean cycle by Howard's policy iteration.
Default distance accessor for arc weights.
#define TEST(name)
static mt19937 rng
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Howard_Mean_Cycle_Result< GT, typename Distance::Distance_Type > howard_minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA(), const size_t max_fallback_bytes=std::numeric_limits< size_t >::max())
Minimum mean cycle by Howard's policy iteration.
#define PROBE_ALLOCATIONS
#define PROBE_NOINLINE
@ S
Susceptible.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
Graph types and probe helpers shared by negative_cycles_test.cc and bounded_negative_cycle_test....
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Result of howard_minimum_mean_cycle().
bool used_karp
True if Karp's algorithm produced the answer: fallback_reason is not None.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Gsl_Compatible_Rng r
Generic graph and digraph implementations.