okami.mom/strata

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

Niko1221Merge f-container-mem-core: memory checks that read a container's limit correctly6b63729a9

main
33.9 KiB524 linesraw
1// available_host_bytes(): MemAvailable, the cgroup limits above this process, and the operator's cap, on fixture
2// directories standing in for /proc/meminfo, /proc/self/cgroup and /sys/fs/cgroup.  CPU only, no GPU.
3#include "strata/core/conversation_memory.hpp"
4
5#ifdef _WIN32
6#include <process.h>
7#define getpid _getpid
8#else
9#include <unistd.h>
10#endif
11
12#include <cstdint>
13#include <cstdio>
14#include <cstdlib>
15#include <filesystem>
16#include <fstream>
17#include <string>
18
19using namespace strata::core;
20namespace fs = std::filesystem;
21
22namespace {
23
24int checks = 0;
25void check(bool ok, const char* label) {
26    ++checks;
27    if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
28}
29
30constexpr uint64_t MiB = 1ull << 20;
31constexpr uint64_t GiB = 1ull << 30;
32
33struct Fixture {
34    fs::path dir;
35    Fixture() {
36        static int n = 0;
37        dir = fs::temp_directory_path() / ("strata_memory_guard_" + std::to_string((long) ::getpid()) + "_" + std::to_string(n++));
38        fs::remove_all(dir);
39        fs::create_directories(dir / "cgroup");
40        // this process's own mappings: none unless a test says so (the real /proc/self/status is never read)
41        std::ofstream(dir / "status", std::ios::binary) << "Name:\tstrata\nRssAnon:\t    1024 kB\nRssFile:\t       0 kB\nRssShmem:\t       0 kB\n";
42    }
43    ~Fixture() { std::error_code ec; fs::remove_all(dir, ec); }
44    void put(const std::string& rel, const std::string& text) {
45        const fs::path p = dir / rel;
46        fs::create_directories(p.parent_path());
47        std::ofstream(p, std::ios::binary) << text;
48    }
49    void put(const std::string& rel, uint64_t n) { put(rel, std::to_string(n) + "\n"); }
50    void meminfo(uint64_t total, uint64_t available) {
51        put("meminfo", "MemTotal:       " + std::to_string(total / 1024) + " kB\nMemFree: 1 kB\nMemAvailable:   " +
52                           std::to_string(available / 1024) + " kB\n");
53    }
54    void self(const std::string& text) { put("self_cgroup", text + "\n"); }
55    MemoryProbePaths paths() const {
56        return {(dir / "meminfo").string(), (dir / "self_cgroup").string(), (dir / "cgroup").string(), (dir / "status").string()};
57    }
58    void rss_file(uint64_t bytes) { put("status", "Name:\tstrata\nRssFile:\t" + std::to_string(bytes / 1024) + " kB\n"); }
59    std::optional<HostMemoryReading> sample(uint64_t explicit_limit = 0) const { return sample_host_memory(paths(), explicit_limit); }
60};
61
62}  // namespace
63
64int main() {
65    // no cgroup limit anywhere ("max" at every level, and the root without memory files): plain MemAvailable
66    {
67        Fixture f;
68        f.meminfo(120 * GiB, 25 * GiB);
69        f.self("0::/a/b");
70        f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 90 * GiB);
71        f.put("cgroup/a/memory.max", "max\n"); f.put("cgroup/a/memory.current", 60 * GiB);
72        f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);
73        const auto r = f.sample();
74        check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "max everywhere is plain MemAvailable");
75        check(r->limit == 120 * GiB && r->current == 95 * GiB && r->mem_available == 25 * GiB, "meminfo reading: MemTotal and used");
76    }
77    // nested v2 limits: the tightest room of the group and its ancestors wins, "max" levels are skipped
78    {
79        Fixture f;
80        f.meminfo(120 * GiB, 80 * GiB);
81        f.self("0::/a/b");
82        f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 90 * GiB);   // 10 GiB of room
83        f.put("cgroup/a/memory.max", 60 * GiB); f.put("cgroup/a/memory.current", 58 * GiB);  // 2 GiB of room
84        f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);
85        auto r = f.sample();
86        check(r && r->available == 2 * GiB && r->source == MemorySource::cgroup, "tightest ancestor wins");
87        check(r->limit == 60 * GiB && r->current == 58 * GiB, "reading names that group's limit and usage");
88        f.put("cgroup/a/memory.current", 59 * GiB + 512 * MiB);
89        r = f.sample();
90        check(r && r->available == 512 * MiB, "the room follows memory.current");
91        f.put("cgroup/a/memory.current", 61 * GiB);
92        r = f.sample();
93        check(r && r->available == 0 && r->source == MemorySource::cgroup, "usage over the limit is a known zero");
94        f.put("cgroup/a/memory.current", 10 * GiB);
95        r = f.sample();
96        check(r && r->available == 10 * GiB && r->limit == 100 * GiB, "the root's room wins once the group has more");
97        check(r->source == MemorySource::cgroup, "source cgroup");
98        // the room under a limit larger than MemAvailable is bounded by MemAvailable
99        f.meminfo(120 * GiB, 4 * GiB);
100        r = f.sample();
101        check(r && r->available == 4 * GiB && r->source == MemorySource::meminfo, "MemAvailable bounds a roomy cgroup");
102    }
103    // memory.high below memory.max counts, and a high of "max" does not
104    {
105        Fixture f;
106        f.meminfo(120 * GiB, 80 * GiB);
107        f.self("0::/g");
108        f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", 99 * GiB + 900 * MiB);
109        f.put("cgroup/g/memory.current", 99 * GiB);
110        auto r = f.sample();
111        check(r && r->available == 900 * MiB && r->limit == 99 * GiB + 900 * MiB, "memory.high lower than memory.max");
112        f.put("cgroup/g/memory.high", "max\n");
113        r = f.sample();
114        check(r && r->available == 1 * GiB && r->limit == 100 * GiB, "memory.high max leaves memory.max");
115        f.put("cgroup/g/memory.max", "max\n"); f.put("cgroup/g/memory.high", 90 * GiB);
116        r = f.sample();
117        check(r && r->available == 0, "memory.high alone, already exceeded");
118    }
119    // the operator's cap: the container cannot see its real limit (memory.max is "max" at the namespace root)
120    {
121        Fixture f;
122        f.meminfo(120 * GiB, 25 * GiB);   // the stale view: MemAvailable says 25 GiB
123        f.self("0::/system.slice/strata.service");
124        f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");
125        f.put("cgroup/memory.current", 99 * GiB + 724 * MiB);
126        f.put("cgroup/system.slice/strata.service/memory.max", "max\n");
127        f.put("cgroup/system.slice/strata.service/memory.current", 97 * GiB);
128        check(f.sample() && f.sample()->available == 25 * GiB && f.sample()->source == MemorySource::meminfo,
129              "without the cap the stale MemAvailable is believed");
130        auto r = f.sample(100 * GiB);
131        check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "the cap minus the root's memory.current");
132        check(r->limit == 100 * GiB && r->current == 99 * GiB + 724 * MiB, "reading names the cap and the usage");
133        r = f.sample(99 * GiB);
134        check(r && r->available == 0 && r->source == MemorySource::flag, "usage over the cap is a known zero");
135        r = f.sample(200 * GiB);
136        check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "a cap above everything else changes nothing");
137        // a real limit visible and tighter than the cap: the tighter one
138        f.put("cgroup/system.slice/memory.max", 98 * GiB); f.put("cgroup/system.slice/memory.current", 97 * GiB + 512 * MiB);
139        r = f.sample(100 * GiB);
140        check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "cap tighter than the visible cgroup limit");
141        r = f.sample(150 * GiB);
142        check(r && r->available == 512 * MiB && r->source == MemorySource::cgroup, "visible cgroup limit tighter than the cap");
143        // equal rooms: the operator's number is the one reported
144        r = f.sample(99 * GiB + 724 * MiB + 512 * MiB);
145        check(r && r->available == 512 * MiB && r->source == MemorySource::flag, "a tie goes to the operator's cap");
146        // no memory.current at the root: used = MemTotal - MemAvailable
147        fs::remove(f.dir / "cgroup/system.slice/memory.max");
148        fs::remove(f.dir / "cgroup/memory.current");
149        r = f.sample(100 * GiB);
150        check(r && r->available == 5 * GiB && r->source == MemorySource::flag && r->current == 95 * GiB,
151              "without the root's memory.current the meminfo-derived usage is used");
152        // ... and with no MemTotal either, the usage is unknown: unknown, not a guess
153        f.put("meminfo", "MemAvailable: 1024 kB\n");
154        check(!f.sample(100 * GiB), "cap with unknown usage is unknown");
155        check(f.sample().has_value(), "no cap, no usage needed");
156    }
157    // malformed or unusable files: without a cap the guard falls back to MemAvailable alone (meminfo source, once-warned);
158    // with a cap the sample is unknown (admission refuses), never a guess
159    {
160        const char* bad_values[] = {"garbage\n", "", "\n", "-5\n", "+5\n", "12x\n", "1 2\n", "18446744073709551616\n",
161                                    "0x10\n", "MAX\n"};
162        for (const char* file : {"memory.max", "memory.high", "memory.current"}) {
163            for (const char* text : bad_values) {
164                Fixture f;
165                f.meminfo(120 * GiB, 25 * GiB);
166                f.self("0::/g");
167                f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", "max\n");
168                f.put("cgroup/g/memory.current", 50 * GiB);
169                f.put(std::string("cgroup/g/") + file, text);
170                {
171                    const auto r = f.sample();
172                    check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo,
173                          "malformed cgroup file without a cap: MemAvailable alone");
174                }
175                check(!f.sample(100 * GiB), "malformed cgroup file is unknown with the cap too");
176            }
177        }
178        Fixture f;
179        f.self("0::/g");
180        f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.current", 50 * GiB);
181        f.meminfo(120 * GiB, 25 * GiB);
182        check(f.sample() && f.sample()->available == 25 * GiB, "the fixture itself is sound");
183        fs::remove(f.dir / "cgroup/g/memory.current");
184        check(f.sample() && f.sample()->available == 25 * GiB && f.sample()->source == MemorySource::meminfo,
185              "a finite limit with no usage beside it, no cap: MemAvailable alone");
186        check(!f.sample(100 * GiB), "... and with the cap it is unknown");
187        f.put("cgroup/g/memory.max", "max\n");
188        check(f.sample() && f.sample()->available == 25 * GiB, "no finite limit and no usage: the level is skipped");
189        f.put("cgroup/g/memory.current", "max\n");
190        check(f.sample() && f.sample()->source == MemorySource::meminfo, "memory.current is never \"max\": MemAvailable alone");
191        check(!f.sample(100 * GiB), "... unknown with the cap");
192        f.put("cgroup/g/memory.current", 1ull);
193        for (const char* text : {"", "MemAvailable: 12 MB\n", "MemAvailable: 1x kB\n", "MemTotal: 5 kB\n",
194                                 "MemAvailable: 5 kB\nMemAvailable: 6 kB\n"}) {
195            f.put("meminfo", text);
196            check(!f.sample(), "malformed MemAvailable is unknown");
197        }
198        fs::remove(f.dir / "meminfo");
199        check(!f.sample(), "no meminfo is unknown");
200        f.meminfo(120 * GiB, 25 * GiB);
201        f.self("0::/a/../g");
202        check(f.sample() && f.sample()->source == MemorySource::meminfo, "a .. component in the cgroup path: MemAvailable alone");
203        check(!f.sample(100 * GiB), "a .. component with the cap is refused");
204        f.self("garbage without colons");
205        check(f.sample() && f.sample()->available == 25 * GiB, "unparsable /proc/self/cgroup lines are ignored");
206    }
207    // a path from /proc/self/cgroup that this mount does not show: the deepest group that is there (at worst the root)
208    {
209        Fixture f;
210        f.meminfo(120 * GiB, 25 * GiB);
211        f.self("0::/lxc/105/ns/deep");
212        f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 99 * GiB);
213        auto r = f.sample();
214        check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "an invisible group falls back to the mount's root");
215        f.put("cgroup/lxc/memory.max", 100 * GiB); f.put("cgroup/lxc/memory.current", 99 * GiB + 256 * MiB);
216        r = f.sample();
217        check(r && r->available == 1 * GiB - 256 * MiB, "the deepest visible prefix is read too");
218    }
219    // no /proc/self/cgroup file: the mount's root group; no mount: MemAvailable alone
220    {
221        Fixture f;
222        f.meminfo(120 * GiB, 25 * GiB);
223        f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 98 * GiB);
224        auto r = f.sample();
225        check(r && r->available == 2 * GiB, "no cgroup file: the root group");
226        fs::remove_all(f.dir / "cgroup");
227        r = f.sample();
228        check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "no cgroup mount: MemAvailable");
229        check(f.sample(100 * GiB) && f.sample(100 * GiB)->source == MemorySource::flag &&
230                  f.sample(100 * GiB)->available == 5 * GiB, "no cgroup mount, a cap: meminfo-derived usage");
231    }
232    // cgroup v1
233    {
234        Fixture f;
235        f.meminfo(120 * GiB, 80 * GiB);
236        f.self("12:cpu,cpuacct:/x\n4:memory:/m/n\n1:name=systemd:/x");
237        f.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull);
238        f.put("cgroup/memory/memory.usage_in_bytes", 90 * GiB);
239        f.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); f.put("cgroup/memory/m/memory.usage_in_bytes", 60 * GiB);
240        f.put("cgroup/memory/m/n/memory.limit_in_bytes", 9223372036854771712ull);
241        f.put("cgroup/memory/m/n/memory.usage_in_bytes", 1 * GiB);
242        auto r = f.sample();
243        check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup && r->limit == 64 * GiB, "v1: the tightest limit, unlimited skipped");
244        r = f.sample(100 * GiB);
245        check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup, "v1 with a looser cap");
246        r = f.sample(92 * GiB);
247        check(r && r->available == 2 * GiB && r->source == MemorySource::flag && r->current == 90 * GiB, "v1 with a tighter cap: the v1 root's usage");
248        f.put("cgroup/memory/m/memory.limit_in_bytes", "junk\n");
249        check(f.sample() && f.sample()->source == MemorySource::meminfo, "v1 malformed limit, no cap: MemAvailable alone");
250        check(!f.sample(100 * GiB), "v1 malformed limit with the cap is unknown");
251    }
252    // hybrid: a v2 line, but the memory controller lives in the v1 tree
253    {
254        Fixture f;
255        f.meminfo(120 * GiB, 80 * GiB);
256        f.self("5:memory:/g\n0::/g");
257        f.put("cgroup/cgroup.controllers", "cpu\n");
258        f.put("cgroup/g/cpu.max", "max 100000\n");
259        f.put("cgroup/memory/g/memory.limit_in_bytes", 10 * GiB); f.put("cgroup/memory/g/memory.usage_in_bytes", 9 * GiB);
260        auto r = f.sample();
261        check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "hybrid falls through to v1");
262        f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 1 * GiB);
263        r = f.sample();
264        check(r && r->available == 80 * GiB, "v2 memory files win over v1 when both exist");
265    }
266    // the one credited kind of reclaimable memory: clean inactive file cache from the same group's memory.stat
267    {
268        const auto stat = [](uint64_t inactive, uint64_t active, uint64_t shmem, uint64_t dirty = 0, uint64_t wb = 0) {
269            return "anon 1\nfile 2\nshmem " + std::to_string(shmem) + "\ninactive_file " + std::to_string(inactive) +
270                   "\nactive_file " + std::to_string(active) + "\nfile_dirty " + std::to_string(dirty) +
271                   "\nfile_writeback " + std::to_string(wb) + "\nunevictable 5\n";
272        };
273        Fixture f;
274        f.meminfo(120 * GiB, 25 * GiB);
275        f.self("0::/system.slice/strata.service");
276        f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");
277        f.put("cgroup/memory.current", 98 * GiB + 324 * MiB);
278        f.put("cgroup/memory.stat", stat(3 * GiB + 800 * MiB, 27 * GiB, 65 * GiB));
279        f.put("cgroup/system.slice/strata.service/memory.max", "max\n");
280        f.put("cgroup/system.slice/strata.service/memory.current", 90 * GiB);
281        // the operator's cap: the root's memory.current less the root's inactive_file; active_file and shmem are not credited
282        auto r = f.sample(99 * GiB);
283        check(r && r->source == MemorySource::flag && r->available == 99 * GiB - (98 * GiB + 324 * MiB - 3 * GiB - 800 * MiB),
284              "the cap path credits the root's inactive_file");
285        check(r->credit == 3 * GiB + 800 * MiB && r->current == 98 * GiB + 324 * MiB, "reading shows the credit and the raw usage");
286        f.put("cgroup/memory.stat", stat(0, 27 * GiB, 65 * GiB));
287        r = f.sample(99 * GiB);
288        check(r && r->available == 700 * MiB && r->credit == 0, "only inactive_file counts: active_file and shmem give nothing");
289        // dirty and writeback pages are not clean: taken off the credit
290        f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 1 * GiB, 512 * MiB));
291        r = f.sample(99 * GiB);
292        check(r && r->credit == 1 * GiB + 512 * MiB && r->available == 700 * MiB + 1 * GiB + 512 * MiB, "dirty and writeback come off");
293        f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 2 * GiB, 2 * GiB));
294        r = f.sample(99 * GiB);
295        check(r && r->credit == 0 && r->available == 700 * MiB, "dirty plus writeback over inactive_file leaves no credit");
296        // inactive_file larger than the usage: the credit stops at the usage, headroom never exceeds the cap
297        f.put("cgroup/memory.stat", stat(500 * GiB, 0, 0));
298        f.meminfo(300 * GiB, 200 * GiB);   // so the cap's room (not MemAvailable) is the smallest term
299        r = f.sample(99 * GiB);
300        check(r && r->credit == 98 * GiB + 324 * MiB && r->available == 99 * GiB && r->source == MemorySource::flag,
301              "inactive_file above the usage cannot lift headroom over the cap");
302        // no memory.stat, or one that cannot be read: no credit, still a sample
303        fs::remove(f.dir / "cgroup/memory.stat");
304        r = f.sample(99 * GiB);
305        check(r && r->available == 700 * MiB && r->credit == 0, "no memory.stat: no credit");
306        for (const char* text : {"", "garbage\n", "inactive_file\n", "inactive_file -1\n", "inactive_file 12x\n",
307                                 "inactive_file 1\ninactive_file 2\n", "inactive_file 99999999999999999999\n",
308                                 "inactive_file 4096\nfile_dirty zz\n"}) {
309            f.put("cgroup/memory.stat", text);
310            r = f.sample(99 * GiB);
311            check(r && r->available == 700 * MiB && r->credit == 0, "unparsable memory.stat: no credit, not unknown");
312        }
313        // a cgroup limit's own group is credited from its own memory.stat
314        f.put("cgroup/memory.stat", stat(0, 0, 0));
315        f.put("cgroup/system.slice/strata.service/memory.max", 92 * GiB);
316        f.put("cgroup/system.slice/strata.service/memory.stat", stat(1 * GiB, 0, 0));
317        r = f.sample();
318        check(r && r->source == MemorySource::cgroup && r->available == 3 * GiB && r->credit == 1 * GiB &&
319                  r->limit == 92 * GiB && r->current == 90 * GiB, "a cgroup limit credits its own group's inactive_file");
320        f.put("cgroup/system.slice/strata.service/memory.stat", stat(500 * GiB, 0, 0));
321        f.meminfo(300 * GiB, 200 * GiB);
322        r = f.sample();
323        check(r && r->available == 92 * GiB && r->credit == 90 * GiB, "cgroup term: the credit stops at the usage too");
324        // cgroup v1: total_inactive_file (and total_dirty / total_writeback)
325        Fixture g;
326        g.meminfo(120 * GiB, 80 * GiB);
327        g.self("4:memory:/m");
328        g.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); g.put("cgroup/memory/m/memory.usage_in_bytes", 62 * GiB);
329        g.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull); g.put("cgroup/memory/memory.usage_in_bytes", 62 * GiB);
330        g.put("cgroup/memory/m/memory.stat", "cache 1\ninactive_file 7\ntotal_inactive_file " + std::to_string(3 * GiB) +
331                                                  "\ntotal_dirty " + std::to_string(1 * GiB) + "\ntotal_writeback 0\n");
332        r = g.sample();
333        check(r && r->available == 2 * GiB + 2 * GiB && r->credit == 2 * GiB && r->source == MemorySource::cgroup,
334              "v1 credits total_inactive_file less total_dirty");
335        g.put("cgroup/memory/m/memory.stat", "inactive_file " + std::to_string(3 * GiB) + "\n");
336        r = g.sample();
337        check(r && r->available == 2 * GiB && r->credit == 0, "v1 ignores the non-total inactive_file");
338    }
339    // the credit's two forms from one memory.stat text
340    {
341        const std::string v2 = "anon 9\nfile 999\nshmem 500\nfile_mapped 77\nactive_file 30\ninactive_file 20\n"
342                               "file_dirty 3\nfile_writeback 2\nunevictable 400\nactive_anon 1\n";
343        CacheCredit c = cache_credit_from_stat(v2, 1000, false);
344        check(c.inactive == 15 && c.lists == 45, "inactive 20 and lists 50, each less dirty 3 and writeback 2");
345        check(cache_credit_from_stat(v2, 40, false).lists == 35 && cache_credit_from_stat(v2, 40, false).inactive == 15,
346              "the lists figure stops at memory.current too");
347        c = cache_credit_from_stat("inactive_file 20\nfile 999\nshmem 900\nunevictable 900\n", 1000, false);
348        check(c.inactive == 20 && c.lists == 20, "no active_file line: lists = inactive; file, shmem and unevictable never count");
349        c = cache_credit_from_stat("inactive_file 20\nactive_file x\n", 1000, false);
350        check(c.inactive == 20 && c.lists == 20, "a malformed active_file adds nothing and does not cost the inactive credit");
351        c = cache_credit_from_stat("inactive_file 20\nactive_file 5\nactive_file 6\n", 1000, false);
352        check(c.inactive == 20 && c.lists == 20, "a repeated active_file adds nothing");
353        c = cache_credit_from_stat("active_file 30\n", 1000, false);
354        check(c.inactive == 0 && c.lists == 0, "no inactive_file: no credit at all, as before");
355        c = cache_credit_from_stat("inactive_file 18446744073709551615\nactive_file 18446744073709551615\n", 1000, false);
356        check(c.inactive == 1000 && c.lists == 1000, "no overflow in inactive + active");
357        c = cache_credit_from_stat("active_file 30\ninactive_file 20\ntotal_active_file 300\ntotal_inactive_file 200\n"
358                                   "total_dirty 10\ntotal_writeback 0\n", 10000, true);
359        check(c.inactive == 190 && c.lists == 490, "v1 reads the total_ names");
360        const std::optional<uint64_t> total11(11), none0(0), own3(3), own20(20);
361        check(cache_credit_for_limit({5, 9}, 10, total11, false, none0) == 9, "a limit below MemTotal: lists");
362        check(cache_credit_for_limit({5, 9}, 10, total11, false, own3) == 6, "... less the process's own mappings");
363        check(cache_credit_for_limit({5, 9}, 10, total11, false, own20) == 0, "... floor 0");
364        check(cache_credit_for_limit({5, 9}, 10, total11, false, std::nullopt) == 5, "own mappings unknown: inactive");
365        check(cache_credit_for_limit({5, 9}, 11, total11, false, none0) == 5, "a limit at MemTotal: inactive");
366        check(cache_credit_for_limit({5, 9}, 12, total11, false, own3) == 5, "a limit above MemTotal: inactive, own mappings ignored");
367        check(cache_credit_for_limit({5, 9}, 10, std::nullopt, false, none0) == 5, "MemTotal unknown: inactive");
368        check(cache_credit_for_limit({5, 9}, 10, total11, true, none0) == 5, "the switch: inactive");
369        // RssFile from /proc/self/status, less the locked file bytes
370        const std::string status = "Name:\tstrata\nVmLck:\t  999 kB\nRssAnon:\t 100 kB\nRssFile:\t 2048 kB\nRssShmem:\t 64 kB\n";
371        check(own_evictable_mapped_bytes(status, 0) == std::optional<uint64_t>(2 * MiB), "RssFile in bytes");
372        check(own_evictable_mapped_bytes(status, 1 * MiB) == std::optional<uint64_t>(1 * MiB), "locked file bytes come off");
373        check(own_evictable_mapped_bytes(status, 3 * MiB) == std::optional<uint64_t>(0), "floor 0");
374        check(!own_evictable_mapped_bytes("Name:\tstrata\nRssAnon:\t 1 kB\n", 0), "no RssFile: unknown");
375        check(!own_evictable_mapped_bytes("RssFile:\t 12 MB\n", 0) && !own_evictable_mapped_bytes("RssFile:\t x kB\n", 0) &&
376                  !own_evictable_mapped_bytes("RssFile:\t 1 kB\nRssFile:\t 2 kB\n", 0), "malformed RssFile: unknown");
377        check(locked_own_file_bytes() == 0, "nothing locked by default");
378        set_locked_own_file_bytes(5 * MiB);
379        check(locked_own_file_bytes() == 5 * MiB, "locked bytes round trip");
380        set_locked_own_file_bytes(0);
381        check(mem_credit_inactive_only("1") && !mem_credit_inactive_only("0") && !mem_credit_inactive_only(nullptr) &&
382                  !mem_credit_inactive_only(""), "STRATA_MEM_CREDIT_INACTIVE=1 only");
383    }
384    // a container (limit below MemTotal) restarted with its model file's pages still cached: the same figure cold and warm
385    {
386        const auto stat = [](uint64_t active, uint64_t inactive) {
387            return "anon " + std::to_string(5 * GiB) + "\nfile " + std::to_string(active + inactive) + "\nactive_file " +
388                   std::to_string(active) + "\ninactive_file " + std::to_string(inactive) + "\nfile_dirty 0\nfile_writeback 0\n";
389        };
390        const uint64_t limit = 57 * GiB + 760 * MiB, table = 26 * GiB + 820 * MiB;
391        Fixture f;
392        f.meminfo(503 * GiB, 420 * GiB);   // the host's view
393        f.self("0::/");
394        f.put("cgroup/memory.max", limit);
395        // cold: 7 GiB used, 1 GiB of it inactive cache
396        f.put("cgroup/memory.current", 7 * GiB); f.put("cgroup/memory.stat", stat(0, 1 * GiB));
397        const auto cold = f.sample();
398        check(cold && cold->source == MemorySource::cgroup && cold->available == limit - 6 * GiB, "cold start: limit - (current - cache)");
399        // warm, the table's pages on the active list (the pod: credited 1.0 GiB, available 26.7 GiB under the old rule)
400        f.put("cgroup/memory.current", 7 * GiB + table); f.put("cgroup/memory.stat", stat(table, 1 * GiB));
401        const auto warm = f.sample();
402        check(warm && warm->available == cold->available && warm->credit == table + 1 * GiB, "warm, active: the same figure");
403        f.put("cgroup/memory.stat", stat(1 * GiB, table));
404        check(f.sample() && f.sample()->available == cold->available, "warm, inactive: the same figure");
405        // the way back
406#ifdef _WIN32
407        _putenv_s("STRATA_MEM_CREDIT_INACTIVE", "1");
408#else
409        setenv("STRATA_MEM_CREDIT_INACTIVE", "1", 1);
410#endif
411        f.put("cgroup/memory.stat", stat(table, 1 * GiB));
412        const auto old = f.sample();
413        check(old && old->available == limit - (7 * GiB + table - 1 * GiB) && old->credit == 1 * GiB,
414              "STRATA_MEM_CREDIT_INACTIVE=1: active pages are not credited, as before");
415#ifdef _WIN32
416        _putenv_s("STRATA_MEM_CREDIT_INACTIVE", "");
417#else
418        unsetenv("STRATA_MEM_CREDIT_INACTIVE");
419#endif
420        check(f.sample() && f.sample()->available == cold->available, "switch cleared: the lists rule again");
421        // the engine maps the table (ram mode, lock refused): its resident pages are its own, not free - cold and warm alike
422        f.rss_file(table + 300 * MiB);   // the table and 300 MiB of libraries
423        const auto mapped = f.sample();
424        check(mapped && mapped->credit == 1 * GiB - 300 * MiB && mapped->available == limit - (7 * GiB + table - (1 * GiB - 300 * MiB)),
425              "own mapped table and libraries: not credited");
426        // the lock worked: the table is on the unevictable list, not on the file lists, and is added back
427        f.put("cgroup/memory.stat", stat(0, 1 * GiB));   // the locked table is in neither list
428        set_locked_own_file_bytes(table);
429        const auto locked = f.sample();
430        check(locked && locked->credit == 1 * GiB - 300 * MiB, "locked table: only the libraries come off the file credit");
431        set_locked_own_file_bytes(0);
432        // no status file: the own mappings cannot be told, the inactive credit is taken
433        f.put("cgroup/memory.stat", stat(table, 1 * GiB));
434        fs::remove(f.dir / "status");
435        check(f.sample() && f.sample()->credit == 1 * GiB, "no /proc/self/status: inactive credit");
436        f.rss_file(0);
437        // a limit at or above MemTotal (not a container's view): the inactive rule, bit for bit
438        f.meminfo(57 * GiB, 50 * GiB);
439        const auto at = f.sample();
440        check(at && at->credit == 1 * GiB && at->available == limit - (7 * GiB + table - 1 * GiB) && at->source == MemorySource::cgroup,
441              "limit above MemTotal: active pages are not credited, as before");
442        f.meminfo(limit, 50 * GiB);
443        check(f.sample() && f.sample()->credit == 1 * GiB, "limit equal to MemTotal: inactive only");
444        // no limit at all: MemAvailable, untouched by memory.stat
445        f.meminfo(503 * GiB, 420 * GiB);
446        f.put("cgroup/memory.max", "max\n");
447        check(f.sample() && f.sample()->available == 420 * GiB && f.sample()->source == MemorySource::meminfo && f.sample()->credit == 0,
448              "no limit: MemAvailable");
449        // the operator's cap keeps the inactive rule (its usage is the namespace root's)
450        check(f.sample(40 * GiB) && f.sample(40 * GiB)->credit == 1 * GiB && f.sample(40 * GiB)->source == MemorySource::flag,
451              "--memory-limit-mib: inactive only");
452    }
453    // the expert arena's figure under a container's limit: the same file-list credit (never shmem, never locked pages), its own margin
454    {
455        // the 24 GiB scope with a 3 GiB memfd held (l620, 11-14): the earlier figure credited the shmem in "file" and an
456        // allocation up to it was OOM-killed; this one leaves it charged
457        const std::string memfd = "anon 1048576\nfile " + std::to_string(3 * GiB) + "\nfile_mapped " + std::to_string(3 * GiB) +
458                                  "\nshmem " + std::to_string(3 * GiB) + "\nactive_file 0\ninactive_file 0\nunevictable 0\n"
459                                  "file_dirty 0\nfile_writeback 0\n";
460        const std::optional<uint64_t> host(251 * GiB);
461        ArenaCgroupRoom a = arena_cgroup_room(24 * GiB, 3 * GiB + 20 * MiB, memfd, host, false);
462        check(a.applies && a.credit == 0 && a.room == 21 * GiB - 20 * MiB, "memfd: the shmem stays charged");
463        // active and inactive file pages count, less min(half, limit / 64); locked pages (unevictable) do not
464        const std::string cache = "file " + std::to_string(14 * GiB) + "\nactive_file " + std::to_string(8 * GiB) + "\ninactive_file " +
465                                  std::to_string(4 * GiB) + "\nunevictable " + std::to_string(2 * GiB) + "\nfile_dirty 0\nfile_writeback 0\n";
466        a = arena_cgroup_room(48 * GiB, 16 * GiB, cache, host, false);
467        check(a.applies && a.credit == 12 * GiB - 48 * GiB / 64 && a.room == 44 * GiB - 48 * GiB / 64, "file lists less the margin");
468        a = arena_cgroup_room(48 * GiB, 16 * GiB, cache, std::optional<uint64_t>(48 * GiB), false);
469        check(!a.applies, "a limit at MemTotal: the earlier rule (caller)");
470        check(!arena_cgroup_room(48 * GiB, 16 * GiB, cache, std::nullopt, false).applies, "MemTotal unknown: the earlier rule");
471        check(!arena_cgroup_room(48 * GiB, 16 * GiB, cache, host, true).applies, "STRATA_MEM_CREDIT_INACTIVE=1: the earlier rule");
472        a = arena_cgroup_room(8 * GiB, 9 * GiB, "inactive_file 0\n", host, false);
473        check(a.applies && a.room == 0, "usage over the limit: 0");
474        a = arena_cgroup_room(48 * GiB, 16 * GiB, "", host, false);
475        check(a.applies && a.credit == 0 && a.room == 32 * GiB, "no memory.stat text: no credit");
476    }
477    // the limit on a parent level, credited from that level's own memory.stat; memory.high below memory.max
478    {
479        Fixture f;
480        f.meminfo(256 * GiB, 200 * GiB);
481        f.self("0::/a/b");
482        f.put("cgroup/a/memory.max", 24 * GiB); f.put("cgroup/a/memory.current", 20 * GiB);
483        f.put("cgroup/a/memory.stat", "active_file " + std::to_string(10 * GiB) + "\ninactive_file " + std::to_string(2 * GiB) + "\n");
484        f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 19 * GiB);
485        f.put("cgroup/a/b/memory.stat", "active_file 0\ninactive_file 0\n");
486        auto r = f.sample();
487        check(r && r->source == MemorySource::cgroup && r->limit == 24 * GiB && r->credit == 12 * GiB && r->available == 16 * GiB,
488              "parent limit: 24 - (20 - 12)");
489        f.put("cgroup/a/memory.high", 18 * GiB);
490        r = f.sample();
491        check(r && r->limit == 18 * GiB && r->available == 10 * GiB && r->credit == 12 * GiB, "memory.high below max: 18 - (20 - 12)");
492    }
493    // cgroup v1 under a limit below MemTotal: total_active_file counts too
494    {
495        Fixture g;
496        g.meminfo(120 * GiB, 80 * GiB);
497        g.self("4:memory:/m");
498        g.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); g.put("cgroup/memory/m/memory.usage_in_bytes", 62 * GiB);
499        g.put("cgroup/memory/m/memory.stat", "total_active_file " + std::to_string(4 * GiB) + "\ntotal_inactive_file " +
500                                                  std::to_string(3 * GiB) + "\ntotal_dirty " + std::to_string(1 * GiB) + "\n");
501        const auto r = g.sample();
502        check(r && r->credit == 6 * GiB && r->available == 8 * GiB && r->source == MemorySource::cgroup, "v1: 64 - (62 - (7 - 1))");
503    }
504    // the process-wide setting and the real files
505    {
506        check(memory_limit_bytes() == 0, "no cap by default");
507        set_memory_limit_bytes(123 * MiB);
508        check(memory_limit_bytes() == 123 * MiB, "cap round trip");
509#if defined(__linux__)
510        set_memory_limit_bytes(1);   // one byte: whatever this machine uses, nothing is left
511        const auto r = sample_host_memory();
512        check(!r || (r->available == 0 && r->source == MemorySource::flag && available_host_bytes() == 0u),
513              "the real files honour the process-wide cap");
514#endif
515        set_memory_limit_bytes(0);
516        const auto none = available_host_bytes();
517        check(!none || conversation_memory_admit(none, 0, 0), "the real files without a cap: bytes or unknown");
518        check(std::string(memory_source_name(MemorySource::flag)) == "flag" &&
519                  std::string(memory_source_name(MemorySource::cgroup)) == "cgroup" &&
520                  std::string(memory_source_name(MemorySource::meminfo)) == "meminfo", "source names");
521    }
522    std::printf("memory_guard_test: %d checks passed\n", checks);
523    return 0;
524}