okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ci-green-0215: the four red GitHub checks (cmake-cpu on MSVC, py-tools on a CRLF checkout and on macOS, the Windows snapshot time)b749503db

main
14.9 KiB294 linesraw
1// The segment pool (STRATA_PARK_SEGPOOL_MIB): the arena logic behind the OS interface, tested with a fake OS that counts its calls.
2#include "strata/core/conversation_segment_pool.hpp"
3#include "strata/core/park_pool_policy.hpp"
4
5#include <atomic>
6#include <chrono>
7#include <cstdio>
8#include <cstdlib>
9#include <cstring>
10#include <set>
11#include <thread>
12#include <vector>
13#ifdef _WIN32
14#include <malloc.h>
15#endif
16
17using namespace strata::core;
18
19namespace {
20// 2 MiB aligned memory from the C library: MSVC's C runtime has no std::aligned_alloc (its free cannot release it), so _aligned_malloc there
21void* aligned_2m(size_t bytes) {
22#ifdef _WIN32
23    return _aligned_malloc(bytes, size_t(2) << 20);
24#else
25    return std::aligned_alloc(size_t(2) << 20, bytes);
26#endif
27}
28void aligned_free(void* p) {
29#ifdef _WIN32
30    _aligned_free(p);
31#else
32    std::free(p);
33#endif
34}
35
36int checks = 0;
37void check(bool value, const char* description) {
38    ++checks;
39    if (!value) { std::fprintf(stderr, "FAIL: %s\n", description); std::exit(1); }
40}
41constexpr size_t MiB = size_t(1) << 20;
42
43// Real memory from the C library, 2 MiB aligned; release wipes the range (a released range loses its content, like madvise)
44struct FakeOs final : SegmentPoolOs {
45    size_t reserved = 0;
46    std::atomic<size_t> commits{0}, populates{0}, populated_bytes{0}, releases{0}, released_bytes{0};   // (several threads call the OS in the stress block)
47    bool refuse_commit = false, refuse_populate = false, refuse_reserve = false;
48    void* mem = nullptr;
49    void* reserve(size_t bytes) override {
50        if (refuse_reserve) return nullptr;
51        mem = aligned_2m(bytes);
52        if (mem) { std::memset(mem, 0, bytes); reserved = bytes; }
53        return mem;
54    }
55    void unreserve(void* base, size_t) override { aligned_free(base); }
56    bool commit(void*, size_t) override { ++commits; return !refuse_commit; }
57    bool populate(void*, size_t n) override { if (refuse_populate) return false; ++populates; populated_bytes += n; return true; }
58    void release(void* p, size_t n) override { ++releases; released_bytes += n; std::memset(p, 0, n); }
59};
60}
61
62int main() {
63    // an inert pool: too small to reserve, or the OS refuses
64    {
65        FakeOs os;
66        SegmentPool tiny(os, 1 * MiB);
67        check(!tiny.active() && tiny.capacity() == 0, "a pool under 2 MiB is inert");
68        check(tiny.allocate(MiB) == nullptr, "an inert pool serves nothing");
69        int x = 0;
70        check(!tiny.deallocate(&x, 16), "an inert pool owns no pointer");
71        FakeOs refusing;
72        refusing.refuse_reserve = true;
73        SegmentPool none(refusing, 64 * MiB);
74        check(!none.active(), "a refused reserve is an inert pool");
75    }
76    // take / give: sizes, the minimum, the capacity rounding, the same range again
77    {
78        FakeOs os;
79        SegmentPool pool(os, 64 * MiB);
80        check(pool.active() && pool.capacity() == 64 * MiB, "capacity is the reserved bytes");
81        check(pool.allocate(SegmentPool::min_alloc - 1) == nullptr, "below 512 KiB is not served");
82        void* a = pool.allocate(SegmentPool::min_alloc);
83        check(a != nullptr && pool.contains(a), "512 KiB is served from the region");
84        check(pool.live_requested() == SegmentPool::min_alloc, "live bytes are the bytes asked for");
85        void* b = pool.allocate(14 * MiB + 1);
86        check(b != nullptr && static_cast<char*>(b) >= static_cast<char*>(a) + SegmentPool::min_alloc, "a second range does not overlap the first");
87        check(pool.deallocate(a, SegmentPool::min_alloc), "a pool range is given back to the pool");
88        void* a2 = pool.allocate(SegmentPool::min_alloc);
89        check(a2 == a, "a freed range is the next best fit");
90        check(pool.deallocate(a2, SegmentPool::min_alloc) && pool.deallocate(b, 14 * MiB + 1), "all given back");
91        check(pool.live_requested() == 0, "nothing live after every range is given back");
92        int outside = 0;
93        check(!pool.deallocate(&outside, 16), "a foreign pointer is not the pool's");
94    }
95    // a request larger than the pool, or than any free run, is not served (the caller falls back to the heap) and is counted
96    {
97        FakeOs os;
98        SegmentPool pool(os, 8 * MiB);
99        check(pool.allocate(16 * MiB) == nullptr, "a request larger than the pool is a miss");
100        void* a = pool.allocate(6 * MiB);
101        check(a != nullptr, "6 MiB of an 8 MiB pool");
102        check(pool.allocate(4 * MiB) == nullptr, "4 MiB does not fit beside it");
103        check(pool.misses() == 2 && pool.hits() == 1, "misses and hits are counted");
104        check(pool.allocate(2 * MiB) != nullptr, "the 2 MiB that is left");
105    }
106    // best fit and coalescing
107    {
108        FakeOs os;
109        SegmentPool pool(os, 32 * MiB);
110        void* s[8];
111        for (int i = 0; i < 8; ++i) s[i] = pool.allocate(4 * MiB);
112        check(s[7] != nullptr, "eight 4 MiB ranges fill the pool");
113        check(pool.allocate(SegmentPool::min_alloc) == nullptr, "full");
114        pool.deallocate(s[1], 4 * MiB);          // a 4 MiB hole
115        pool.deallocate(s[3], 4 * MiB);          // 4 MiB hole, then s[4] and s[5] freed make it 12 MiB
116        pool.deallocate(s[4], 4 * MiB);
117        pool.deallocate(s[5], 4 * MiB);
118        void* small = pool.allocate(3 * MiB);    // best fit: the 4 MiB hole at s[1], not the 12 MiB one
119        check(small == s[1], "best fit takes the smallest hole that fits");
120        void* big = pool.allocate(12 * MiB);
121        check(big == s[3], "freed neighbours coalesce into one 12 MiB run");
122        pool.deallocate(small, 3 * MiB);
123        pool.deallocate(big, 12 * MiB);
124    }
125    // bytes written to a range survive the neighbours' allocation and release; ranges never overlap
126    {
127        FakeOs os;
128        SegmentPool pool(os, 64 * MiB);
129        std::vector<std::pair<uint8_t*, size_t>> held;
130        for (int i = 0; i < 12; ++i) {
131            const size_t n = size_t(600 + 311 * i) * 1024;
132            uint8_t* p = static_cast<uint8_t*>(pool.allocate(n));
133            check(p != nullptr, "ranges of mixed sizes");
134            std::memset(p, 0x10 + i, n);
135            held.push_back({p, n});
136        }
137        for (int i = 0; i < 12; i += 2) { pool.deallocate(held[i].first, held[i].second); }
138        for (int i = 1; i < 12; i += 2)
139            for (size_t k = 0; k < held[i].second; k += 4099)
140                check(held[i].first[k] == uint8_t(0x10 + i), "a live range keeps its bytes while its neighbours are freed");
141        std::set<std::pair<const uint8_t*, const uint8_t*>> spans;
142        for (int i = 1; i < 12; i += 2) spans.insert({held[i].first, held[i].first + held[i].second});
143        const uint8_t* end = nullptr;
144        for (const auto& s : spans) { check(end == nullptr || s.first >= end, "live ranges do not overlap"); end = s.second; }
145    }
146    // residency accounting: populate, idle, shrink; idle + live = resident
147    {
148        FakeOs os;
149        SegmentPool pool(os, 64 * MiB);
150        check(pool.resident_bytes() == 0 && pool.idle_bytes() == 0 && pool.cold_free_bytes() == 64 * MiB, "a new pool is cold");
151        check(pool.populate_step(100 * MiB) == 32 * MiB, "a populate step is at most 32 MiB");
152        check(pool.populate_step(1 * MiB) == 1 * MiB && pool.resident_bytes() == 33 * MiB, "a smaller step is honoured");
153        check(pool.idle_bytes() == 33 * MiB, "everything resident is idle while nothing is live");
154        void* a = pool.allocate(10 * MiB);
155        check(a != nullptr && pool.live_requested() == 10 * MiB, "a live range");
156        check(pool.idle_bytes() == pool.resident_bytes() - 10 * MiB, "idle = resident minus the live bytes asked for");
157        void* far = pool.allocate(40 * MiB);   // needs the cold granules too: counted resident once used
158        check(far != nullptr && os.commits >= 1, "a range over cold granules commits them");
159        check(pool.resident_bytes() >= 50 * MiB && pool.idle_bytes() == pool.resident_bytes() - 50 * MiB, "used cold granules count as resident");
160        pool.deallocate(far, 40 * MiB);
161        const size_t idle = pool.idle_bytes();
162        const size_t gave = pool.shrink(8 * MiB);
163        check(gave >= 8 * MiB && gave < 8 * MiB + SegmentPool::granule, "shrink gives back what it was asked for, to the granule");
164        check(pool.idle_bytes() == idle - gave && os.released_bytes == gave, "idle falls by what was released, the OS saw the release");
165        check(pool.shrink(1000 * MiB) > 0 && pool.idle_bytes() == 0 && pool.live_requested() == 10 * MiB, "shrinking everything leaves only the live range");
166        check(pool.resident_bytes() >= 10 * MiB, "the live range stays resident");
167        pool.deallocate(a, 10 * MiB);
168        check(pool.idle_bytes() == pool.resident_bytes(), "after the last range is given back all that is resident is idle");
169    }
170    // a refused commit or populate changes nothing
171    {
172        FakeOs os;
173        SegmentPool pool(os, 16 * MiB);
174        os.refuse_commit = true;
175        check(pool.allocate(4 * MiB) == nullptr && pool.live_requested() == 0 && pool.resident_bytes() == 0, "a refused commit is a miss with no state change");
176        os.refuse_commit = false;
177        os.refuse_populate = true;
178        check(pool.populate_step(4 * MiB) == 0 && pool.populate_failed() && pool.resident_bytes() == 0, "a refused populate makes nothing resident");
179        check(pool.allocate(4 * MiB) != nullptr, "the granules stayed usable after a refused populate");
180    }
181    // the background filler: tops the pool up to what permit allows, nothing when it allows nothing, stops at destruction
182    {
183        FakeOs os;
184        SegmentPool pool(os, 128 * MiB);
185        std::atomic<size_t> cap{40 * MiB};   // the most the pool may hold resident
186        std::atomic<int> started{0};
187        {
188            SegmentPoolFiller filler(pool, [&](size_t step) {
189                const size_t have = pool.resident_bytes();
190                return cap.load() > have ? std::min(step, cap.load() - have) : size_t(0);
191            }, [&] { ++started; });
192            auto settle = [&] {
193                for (int i = 0; i < 5000 && filler.busy(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(1));
194                check(!filler.busy(), "the filler finished its pass");
195            };
196            filler.kick();
197            settle();
198            check(pool.resident_bytes() == 40 * MiB, "the filler stops at what is permitted");
199            check(started.load() == 1, "the thread's start hook ran once");
200            cap = 128 * MiB;
201            filler.kick();
202            settle();
203            check(pool.resident_bytes() == 128 * MiB, "with the whole pool permitted the filler reaches it");
204            pool.shrink(64 * MiB);
205            cap = 0;
206            filler.kick();
207            settle();
208            check(pool.resident_bytes() == 64 * MiB, "a zero permit populates nothing");
209            cap = 100 * MiB;
210            filler.kick();
211            settle();
212            check(pool.resident_bytes() == 100 * MiB, "after a shrink and a larger permit the pool is topped up to it");
213        }
214    }
215    // upkeep only while idle (park_pool_policy.hpp): a permit gated by a "request in flight" flag populates nothing while it is set (a
216    // kick during the request is a no-op), the allocation still works from cold granules, and one kick after the request fills the pool
217    {
218        FakeOs os;
219        SegmentPool pool(os, 128 * MiB);
220        std::atomic<bool> busy{true};
221        SegmentPoolFiller filler(pool, [&](size_t step) {
222            const size_t have = pool.resident_bytes();
223            return park_pool_permit(busy.load(), 128 * MiB > have ? std::min(step, 128 * MiB - have) : size_t(0));
224        });
225        auto settle = [&] {
226            for (int i = 0; i < 5000 && filler.busy(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(1));
227            check(!filler.busy(), "the filler finished its pass");
228        };
229        filler.kick();
230        settle();
231        check(pool.resident_bytes() == 0 && os.populates.load() == 0, "a kick during a request populates nothing");
232        void* p = pool.allocate(4 * MiB);
233        check(p != nullptr, "an allocation during a request is served from the cold pool (never waits for the upkeep)");
234        pool.deallocate(p, 4 * MiB);
235        busy = false;
236        filler.kick();
237        settle();
238        check(pool.resident_bytes() == 128 * MiB, "one kick after the request fills the pool");
239    }
240    // threads: workers allocate, write, verify and free while the filler populates and the main thread shrinks.  A 192 MiB pool, 3 workers
241    // holding at most 6 MiB each (the memory cap of this test is the pool's size)
242    {
243        FakeOs os;
244        SegmentPool pool(os, 192 * MiB);
245        std::atomic<int> bad{0};
246        std::atomic<size_t> cap{192 * MiB};
247        SegmentPoolFiller filler(pool, [&](size_t step) {
248            const size_t have = pool.resident_bytes();
249            return cap.load() > have ? std::min(step, cap.load() - have) : size_t(0);
250        });
251        std::atomic<bool> stop{false};
252        std::vector<std::thread> workers;
253        for (int w = 0; w < 3; ++w)
254            workers.emplace_back([&, w] {
255                uint64_t s = 88172645463325252ull + w;
256                for (int it = 0; it < 600 && !stop.load(); ++it) {
257                    s ^= s << 13; s ^= s >> 7; s ^= s << 17;
258                    const size_t n = SegmentPool::min_alloc + size_t(s % (6 * MiB));
259                    uint8_t* p = static_cast<uint8_t*>(pool.allocate(n));
260                    if (p == nullptr) continue;
261                    const uint8_t tag = uint8_t(w * 80 + it);
262                    for (size_t k = 0; k < n; k += 4093) p[k] = tag;
263                    std::this_thread::yield();
264                    for (size_t k = 0; k < n; k += 4093) if (p[k] != tag) ++bad;
265                    pool.deallocate(p, n);
266                }
267            });
268        for (int i = 0; i < 300; ++i) {
269            filler.kick();
270            pool.shrink(8 * MiB);
271            (void) pool.idle_bytes();
272            std::this_thread::sleep_for(std::chrono::microseconds(300));
273        }
274        for (auto& t : workers) t.join();
275        stop = true;
276        check(bad.load() == 0, "no worker saw another's bytes in its range (ranges never overlap under threads)");
277        check(pool.live_requested() == 0, "every range was given back");
278        check(pool.resident_bytes() <= pool.capacity() && pool.idle_bytes() == pool.resident_bytes(), "residency stays within the pool and all of it is idle at the end");
279        check(pool.hits() > 0, "the workers were served");
280    }
281    // the process-wide hook: installed once
282    {
283        FakeOs os;
284        SegmentPool pool(os, 8 * MiB);
285        check(segment_pool() == nullptr, "no process-wide pool at first");
286        check(segment_pool_install(&pool) && segment_pool() == &pool, "installed");
287        SegmentPool other(os, 8 * MiB);
288        check(!segment_pool_install(&other) && segment_pool() == &pool, "a second install is refused");
289        segment_pool_uninstall_for_test();
290        check(segment_pool() == nullptr, "uninstalled by the test");
291    }
292    std::printf("conversation_segment_pool_test: %d checks passed\n", checks);
293    return 0;
294}