Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
memory guard: parking and session save/restore read the RAM the engine really has (--memory-limit-mib)
noon-at-cgndaa765524d7c
diff --git a/CMakeLists.txt b/CMakeLists.txtindex a72ac9dda..9bcec0b21 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -461,6 +461,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60)endif()+ # available_host_bytes(): MemAvailable, cgroup limits and the operator's --memory-limit-mib cap on fixture directories+ # - no GPU, no CUDA+ if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/memory_guard_test.cpp")+ add_executable(memory_guard_test tests/core/memory_guard_test.cpp src/core/conversation_memory.cpp)+ target_include_directories(memory_guard_test PRIVATE include)+ add_test(NAME memory_guard_test COMMAND memory_guard_test)+ set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60)+ endif()+if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")enable_testing()add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp)diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 4c92e50b2..47d915644 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -941,12 +941,80 @@ nothing and stores nothing; the log line is `conversation cache: skip parking (Nparked=P)`. 0 is the pre-flag behaviour and the flag leaves the answers untouched - it only decides whichconversations keep a slot.`--conversation-cache-min-free-mib N` (default 2560) additionally requires that-physical-RAM headroom remain available: the engine checks before allocation and-again after capture. Unknown telemetry or insufficient RAM skips parking. Windows-uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples,-not a reservation or enforcement of container/job memory limits. An 8 GiB budget+RAM headroom remain available: the engine checks before allocation (against the+snapshot's estimated size, less the K/V it already retains) and again after capture.+Unknown telemetry or insufficient RAM skips parking, and the same figure and floor+decide whether a session file may be saved or restored (below). An 8 GiB budgetis a cap, not a recommendation for every machine.+**The RAM figure (`available_host_bytes()`).** The headroom is the smallest of three+numbers, sampled each time it is asked and not a reservation (other writers can take the+room afterwards):++1. `MemAvailable` (Windows: `GlobalMemoryStatusEx`'s available physical memory).+2. The room under each memory limit of the engine's own cgroup and of every ancestor+ visible under `/sys/fs/cgroup` (the group named in `/proc/self/cgroup`, or the deepest+ part of that path this mount shows): cgroup v2 `memory.max` and `memory.high`, each+ minus `memory.current`; cgroup v1 `memory.limit_in_bytes` minus+ `memory.usage_in_bytes` (both less the clean inactive file cache, below). `max` and v1's "unlimited" count as no limit; a file that is+ absent (no memory controller at that level) is skipped; a file that is there but+ cannot be read or parsed makes the sample unknown, and unknown skips parking.+3. `--memory-limit-mib N` (or `STRATA_MEMORY_LIMIT_MIB=N`; the flag wins, `0` = none):+ N MiB is the total this engine's container or cgroup may use, minus what that+ container uses now. Use it when the container cannot see its own limit. The usage+ is `memory.current` of the top cgroup this mount shows (the container's own, in a+ container with its own cgroup namespace); if that file cannot be read it is+ `MemTotal - MemAvailable`, which is a weaker figure (it is only as true as the+ container's `/proc/meminfo`), and if `MemTotal` is missing too the sample is+ unknown. The cap is taken in addition to 1 and 2, never instead of them: whichever+ number is smallest decides. It is an engine argument, so the server config carries it in+ `args` (`"--memory-limit-mib", "102400"`); the variable also works from the config's+ `"env"`.++Usage is `memory.current` as the kernel reports it, **less one reclaimable kind: clean+inactive file cache**. That is the group's own `memory.stat` `inactive_file` (cgroup v1:+`total_inactive_file`), less its dirty and writeback pages when `memory.stat` lists them+(`file_dirty`, `file_writeback`; v1 `total_dirty`, `total_writeback`), and never more than+`memory.current`. The kernel gives such pages back at `memory.high` or the limit before+it kills anything, and a loaded model's file reads leave a lot of them behind. Nothing+else is credited: `active_file` (it holds the mlocked pages), `shmem` (pinned expert+complements, the KV pool) and anonymous memory stay charged in full, since a kill at a+hard limit is worse than a skipped park. For each limit the room is+`limit - (memory.current - credit)`, so it never exceeds the limit. A `memory.stat` that is missing or cannot be+parsed gives no credit; it does not make the sample unknown. The operator's cap uses the+`memory.stat` of the same top group whose `memory.current` it reads. A parked+conversation is part of the engine's own usage once captured; the check before+capture is what stops it from growing past the cap.++The startup log has one line for it, `strata generate: memory guard: limit X GiB+(source: flag|cgroup|meminfo), current Y GiB, reclaimable cache credited Z GiB;+available ...`, where `source` names the+number that was smallest at that moment (`meminfo`: MemTotal and `MemTotal -+MemAvailable`), and a skipped park or a refused save/restore says how much it had and+from which source. The line is printed before the model is loaded, so its credit is the+cache at that moment, not at the time of a park. Without a cgroup limit and without `--memory-limit-mib` the figure is+plain `MemAvailable`, as before.++What it does not touch: the startup sizing of the expert arena, the file tier's resident budget, the Windows commit+check and `STRATA_PIN_GUARD` (#1250: whether to page-lock the expert copy in steps follows `MemFree`, and each step+is checked against the cgroup-aware `host_available_memory`) keep their own probes (`--resident-budget-gib`, #633,+#1250), and `--memory-limit-mib` does not reach them. This figure is for what runs after the start: parking a+conversation and saving or restoring a session file, which read `MemAvailable` alone. `host_available_memory`+(expert_source.cpp) and this figure both read the cgroup limits; this one also reads `memory.high` and the operator's+cap, and an unreadable cgroup file makes it unknown.++Earlier measurement on a Proxmox LXC where the engine's container cannot see its limit (a 100 GiB cap on the parent+cgroup, outside the container's namespace; the container's own `memory.max` and `memory.high` read `max`):+`/proc/meminfo` showed about 25 GiB `MemAvailable` while about 1 GiB was really left, and right after the engine had+loaded the container's `memory.current` was 98.29 GiB with `anon` 1.29 GiB, `shmem` 65.51 GiB, `inactive_file`+3.81 GiB (clean page cache left from reading the model files) and `active_file` 0.01 GiB, of which the 3.8 GiB of+clean cache is what the credit gives back. There `--memory-limit-mib 102400` is the cap, and the floor+(`--conversation-cache-min-free-mib`) is measured against what is left under it: with the engine already near the cap,+a floor of several GiB refuses every park; a few hundred MiB keeps a margin for the allocator and the kernel while+letting a snapshot that really fits go through.+TODO-EVIDENCE: the same check on the test machine (lm-server, container CT105, 90 GiB cap): the figure with and without+`--memory-limit-mib`, a park that the old check let through and the guard refuses (or the reverse), n and the A/A.+The shared snapshot core validates all layers and checkpoints before applying anystate. Invalid entries are discarded; transfer/synchronization failure is fatalrather than permission to continue with partial state. Indexer spare keys and thediff --git a/include/strata/core/conversation_memory.hpp b/include/strata/core/conversation_memory.hppindex 0e908b40c..81ea0b077 100644--- a/include/strata/core/conversation_memory.hpp+++ b/include/strata/core/conversation_memory.hpp@@ -3,12 +3,67 @@#include <cstdint>#include <istream>#include <optional>+#include <string>namespace strata::core {-// Host physical memory, not swap/commit or a container/job memory reservation.-// Unknown telemetry is deliberately distinct from a measured zero.-std::optional<uint64_t> conversation_available_memory();+// The RAM a runtime allocation (parking a conversation, saving or restoring a session file) may still take.+//+// available_host_bytes() is the smallest of+// * MemAvailable (Windows: the available physical memory);+// * the room under every memory limit of this process's cgroup and of each ancestor visible under+// /sys/fs/cgroup (cgroup v2: memory.max and memory.high, each minus usage; cgroup v1:+// memory.limit_in_bytes minus memory.usage_in_bytes);+// * the operator's own cap, when one is set (--memory-limit-mib / STRATA_MEMORY_LIMIT_MIB): that many MiB minus+// what the container uses now - the top visible cgroup's memory.current, or MemTotal - MemAvailable when the+// cgroup files cannot be read. For a container whose real limit sits on a parent cgroup it cannot see.+//+// Usage is memory.current as the kernel reports it, less one reclaimable kind: the clean inactive file cache of the+// same group (memory.stat inactive_file, v1 total_inactive_file, less dirty and writeback pages, never more than+// memory.current), which the kernel gives back at memory.high or the limit before it kills anything. Nothing else is+// credited: active_file holds mlocked pages, and shmem is the pinned complements and the KV pool. A memory.stat that+// is missing or unparsable gives no credit (it does not make the sample unknown).+// Pinned, locked and shared memory stays charged in full: a hard-limit kill is worse than a skipped park.+//+// Unknown telemetry is deliberately distinct from a measured zero. A limit file that exists but cannot be parsed+// makes the sample unknown (fail closed); a file that is absent (no such controller, not mounted) is ignored.+// Not a reservation: other writers can take the room after the sample.++enum class MemorySource { meminfo, cgroup, flag };++const char* memory_source_name(MemorySource source);++/// One sample. `available` is the smallest term; `source`, `limit` and `current` describe the term that was the+/// smallest (meminfo: MemTotal and MemTotal - MemAvailable; cgroup: that group's limit and memory.current; flag: the+/// operator's cap and the usage it was measured against). `mem_available` is MemAvailable by itself (0 if unknown).+struct HostMemoryReading {+ uint64_t available = 0;+ MemorySource source = MemorySource::meminfo;+ uint64_t limit = 0;+ uint64_t current = 0; ///< memory.current (meminfo: MemTotal - MemAvailable), before the credit+ uint64_t credit = 0; ///< the clean inactive file cache counted as reclaimable (0 for meminfo)+ uint64_t mem_available = 0;+};++/// The files the sampler reads; the defaults are the real ones (tests point them at a fixture directory).+struct MemoryProbePaths {+ std::string meminfo = "/proc/meminfo";+ std::string self_cgroup = "/proc/self/cgroup";+ std::string cgroup_root = "/sys/fs/cgroup";+};++/// The operator's cap in bytes for the container/cgroup this engine runs in (0 = none). Set once at start.+void set_memory_limit_bytes(uint64_t bytes);+uint64_t memory_limit_bytes();++/// Linux: reads `paths`. `explicit_limit` 0 = no operator cap. nullopt when the RAM cannot be determined.+std::optional<HostMemoryReading> sample_host_memory(const MemoryProbePaths& paths, uint64_t explicit_limit);++/// The real files (Windows: GlobalMemoryStatusEx) and the cap set by set_memory_limit_bytes().+std::optional<HostMemoryReading> sample_host_memory();++std::optional<uint64_t> available_host_bytes();+std::optional<uint64_t> conversation_mem_available(std::istream& meminfo);inline bool conversation_memory_admit(std::optional<uint64_t> available,diff --git a/src/core/conversation_memory.cpp b/src/core/conversation_memory.cppindex bd5740f2f..5c234fee3 100644--- a/src/core/conversation_memory.cpp+++ b/src/core/conversation_memory.cpp@@ -1,10 +1,15 @@#include "strata/core/conversation_memory.hpp"+#include <algorithm>+#include <atomic>#include <charconv>+#include <filesystem>#include <fstream>#include <limits>#include <sstream>#include <string>+#include <system_error>+#include <vector>#if defined(_WIN32)#ifndef NOMINMAX@@ -15,13 +20,20 @@namespace strata::core {-std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {+namespace fs = std::filesystem;++namespace {++std::atomic<uint64_t> g_memory_limit_bytes{0};++// "<key> <n> kB", exactly once, nothing else on the line; the value in bytes. Anything else is unknown.+std::optional<uint64_t> meminfo_kb_bytes(std::istream& meminfo, const char* wanted) {std::optional<uint64_t> result;std::string line;while (std::getline(meminfo, line)) {std::istringstream fields(line);std::string key, value, unit, extra;- if (!(fields >> key) || key != "MemAvailable:") continue;+ if (!(fields >> key) || key != wanted) continue;if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {};uint64_t kb = 0;const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb);@@ -33,19 +45,245 @@ std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {return result;}-std::optional<uint64_t> conversation_available_memory() {+// One cgroup control file: absent (no such file), a number, "max", or unusable (unreadable, empty, not a number).+struct Value {+ enum Kind { absent, bad, max, number } kind = absent;+ uint64_t n = 0;+};++Value read_value(const fs::path& path) {+ std::error_code ec;+ const bool there = fs::exists(path, ec);+ if (ec) return {Value::bad, 0};+ if (!there) return {};+ std::ifstream file(path);+ if (!file) return {Value::bad, 0};+ char buf[64];+ file.read(buf, sizeof buf);+ if (file.bad()) return {Value::bad, 0};+ size_t len = (size_t) file.gcount();+ if (len == sizeof buf) return {Value::bad, 0};+ while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ' || buf[len - 1] == '\t')) --len;+ if (len == 0) return {Value::bad, 0};+ if (len == 3 && std::string(buf, 3) == "max") return {Value::max, 0};+ Value v{Value::number, 0};+ const auto parsed = std::from_chars(buf, buf + len, v.n);+ if (parsed.ec != std::errc{} || parsed.ptr != buf + len) return {Value::bad, 0};+ return v;+}++// The one reclaimable kind that is credited: clean inactive file cache, from the same group's memory.stat+// (v2 inactive_file, v1 total_inactive_file), less its dirty and writeback pages when those are listed, and never+// more than the group's charged usage. active_file (it holds mlocked pages) and shmem (pinned complements, the KV+// pool) are not credited. A memory.stat that is missing or unparsable gives no credit - not an unknown sample.+uint64_t reclaimable_cache(const fs::path& dir, uint64_t current, bool v1) {+ std::ifstream stat(dir / "memory.stat");+ if (!stat) return 0;+ const char* inactive_key = v1 ? "total_inactive_file" : "inactive_file";+ const char* dirty_key = v1 ? "total_dirty" : "file_dirty";+ const char* writeback_key = v1 ? "total_writeback" : "file_writeback";+ std::optional<uint64_t> inactive;+ uint64_t dirty = 0, writeback = 0;+ std::string line;+ while (std::getline(stat, line)) {+ std::istringstream fields(line);+ std::string key, value, extra;+ if (!(fields >> key >> value) || (fields >> extra)) continue;+ uint64_t* target = key == dirty_key ? &dirty : key == writeback_key ? &writeback : nullptr;+ uint64_t n = 0;+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), n);+ const bool ok = parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size();+ if (key == inactive_key) { if (!ok || inactive) return 0; inactive = n; }+ else if (target != nullptr) { if (!ok) return 0; *target = n; }+ }+ if (!inactive) return 0;+ uint64_t credit = std::min(*inactive, current);+ credit = dirty >= credit ? 0 : credit - dirty;+ credit = writeback >= credit ? 0 : credit - writeback;+ return credit;+}++// What the cgroup files say: every finite limit with the usage charged against it (and the cache credit of that+// group), and the usage and credit of the topmost visible group (the root of this namespace - what a container's own+// limit is measured over).+struct CgroupScan {+ struct Limit { uint64_t limit, current, credit; };+ std::vector<Limit> limits;+ std::optional<uint64_t> root_current;+ uint64_t root_credit = 0;+ bool any_files = false;+};++// `dirs` runs from the top visible group down to the process's own. False when a file that is there cannot be used.+bool scan_levels(const std::vector<fs::path>& dirs, const char* const* limit_names, size_t n_limits,+ const char* current_name, bool v1, CgroupScan& out) {+ for (size_t i = 0; i < dirs.size(); ++i) {+ const Value current = read_value(dirs[i] / current_name);+ std::vector<Value> limits;+ for (size_t k = 0; k < n_limits; ++k) limits.push_back(read_value(dirs[i] / limit_names[k]));+ bool unusable = current.kind == Value::bad || current.kind == Value::max;+ bool finite_limit = false;+ for (const Value& v : limits) {+ unusable = unusable || v.kind == Value::bad;+ finite_limit = finite_limit || v.kind == Value::number;+ }+ if (unusable) return false;+ if (current.kind == Value::absent) {+ if (finite_limit) return false; // a limit with no usage beside it: the room cannot be told+ continue; // no memory controller at this level (e.g. the host's root group)+ }+ out.any_files = true;+ const uint64_t credit = reclaimable_cache(dirs[i], current.n, v1);+ if (i == 0) { out.root_current = current.n; out.root_credit = credit; }+ for (const Value& v : limits) {+ if (v.kind != Value::number) continue;+ if (v1 && v.n >= (1ull << 62)) continue; // v1's "unlimited" is a number near 2^63+ out.limits.push_back({v.n, current.n, credit});+ }+ }+ return true;+}++// "/a/b/c" -> root, root/a, root/a/b, root/a/b/c, cut at the first one that is not a directory here: a container+// without its own cgroup namespace sees its group's host path in /proc/self/cgroup, but only its own subtree under+// the mount, so the deepest one that exists (at worst the mount itself) is the nearest group we can read.+bool group_dirs(const fs::path& root, const std::string& group, std::vector<fs::path>& dirs) {+ dirs.clear();+ std::vector<std::string> names;+ std::istringstream parts(group);+ for (std::string part; std::getline(parts, part, '/');) {+ if (part.empty()) continue;+ if (part == "." || part == "..") return false; // never walk out of the mount, nor trust a path that tries+ names.push_back(part);+ }+ std::error_code ec;+ if (!fs::is_directory(root, ec)) return true; // nothing mounted: no cgroup terms+ dirs.push_back(root);+ fs::path at = root;+ for (const std::string& part : names) {+ at /= part;+ if (!fs::is_directory(at, ec)) break;+ dirs.push_back(at);+ }+ return true;+}++bool scan_cgroups(const MemoryProbePaths& paths, CgroupScan& out) {+ std::optional<std::string> v2_group, v1_group;+ std::ifstream groups(paths.self_cgroup);+ if (!groups) {+ v2_group = "/"; // no /proc/self/cgroup: the mount's own top group is still readable+ } else {+ std::string line;+ while (std::getline(groups, line)) {+ const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);+ if (c2 == std::string::npos) continue;+ const std::string controllers = line.substr(c1 + 1, c2 - c1 - 1), group = line.substr(c2 + 1);+ if (line.compare(0, c1, "0") == 0 && controllers.empty()) { v2_group = group; continue; }+ std::istringstream names(controllers);+ for (std::string name; std::getline(names, name, ',');)+ if (name == "memory") v1_group = group;+ }+ }+ std::vector<fs::path> dirs;+ if (v2_group) {+ if (!group_dirs(paths.cgroup_root, *v2_group, dirs)) return false;+ static const char* const names[] = {"memory.max", "memory.high"};+ if (!scan_levels(dirs, names, 2, "memory.current", false, out)) return false;+ }+ if (!out.any_files && v1_group) { // cgroup v1: the memory controller's own tree+ if (!group_dirs(fs::path(paths.cgroup_root) / "memory", *v1_group, dirs)) return false;+ static const char* const names[] = {"memory.limit_in_bytes"};+ if (!scan_levels(dirs, names, 1, "memory.usage_in_bytes", true, out)) return false;+ }+ return true;+}++std::optional<HostMemoryReading> combine(std::optional<uint64_t> available, std::optional<uint64_t> total,+ const CgroupScan& cg, uint64_t explicit_limit) {+ if (!available) return {};+ HostMemoryReading r;+ r.mem_available = *available;+ r.available = *available;+ r.source = MemorySource::meminfo;+ r.limit = total.value_or(0);+ r.current = total && *total >= *available ? *total - *available : 0;+ for (const CgroupScan::Limit& l : cg.limits) {+ const uint64_t used = l.current - l.credit; // credit <= current+ const uint64_t room = l.limit > used ? l.limit - used : 0;+ if (room < r.available) {+ r.available = room;+ r.source = MemorySource::cgroup;+ r.limit = l.limit;+ r.current = l.current;+ r.credit = l.credit;+ }+ }+ if (explicit_limit != 0) {+ uint64_t used = 0, credit = 0;+ if (cg.root_current) { used = *cg.root_current; credit = cg.root_credit; }+ else if (total && *total >= *available) used = *total - *available;+ else return {};+ const uint64_t net = used - credit;+ const uint64_t room = explicit_limit > net ? explicit_limit - net : 0;+ if (room <= r.available) { // a tie goes to the operator's number: it is the one that names the real cap+ r.available = room;+ r.source = MemorySource::flag;+ r.limit = explicit_limit;+ r.current = used;+ r.credit = credit;+ }+ }+ return r;+}++} // namespace++const char* memory_source_name(MemorySource source) {+ switch (source) {+ case MemorySource::flag: return "flag";+ case MemorySource::cgroup: return "cgroup";+ default: return "meminfo";+ }+}++std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {+ return meminfo_kb_bytes(meminfo, "MemAvailable:");+}++void set_memory_limit_bytes(uint64_t bytes) { g_memory_limit_bytes.store(bytes, std::memory_order_relaxed); }+uint64_t memory_limit_bytes() { return g_memory_limit_bytes.load(std::memory_order_relaxed); }++std::optional<HostMemoryReading> sample_host_memory(const MemoryProbePaths& paths, uint64_t explicit_limit) {+ std::ifstream avail_file(paths.meminfo);+ if (!avail_file) return {};+ const std::optional<uint64_t> available = conversation_mem_available(avail_file);+ if (!available) return {};+ std::ifstream total_file(paths.meminfo);+ std::optional<uint64_t> total;+ if (total_file) total = meminfo_kb_bytes(total_file, "MemTotal:");+ CgroupScan cg;+ if (!scan_cgroups(paths, cg)) return {};+ return combine(available, total, cg, explicit_limit);+}++std::optional<HostMemoryReading> sample_host_memory() {#if defined(_WIN32)MEMORYSTATUSEX status{};status.dwLength = sizeof status;- if (GlobalMemoryStatusEx(&status)) return status.ullAvailPhys;- return {};+ if (!GlobalMemoryStatusEx(&status)) return {};+ return combine(status.ullAvailPhys, status.ullTotalPhys, CgroupScan{}, memory_limit_bytes());#elif defined(__linux__)- std::ifstream meminfo("/proc/meminfo");- if (!meminfo) return {};- return conversation_mem_available(meminfo);+ return sample_host_memory(MemoryProbePaths{}, memory_limit_bytes());#elsereturn {};#endif}+std::optional<uint64_t> available_host_bytes() {+ const auto reading = sample_host_memory();+ if (!reading) return {};+ return reading->available;+}+} // namespace strata::corediff --git a/src/core/conversation_memory_test.cpp b/src/core/conversation_memory_test.cppindex a8cb25d4e..c95e70bfa 100644--- a/src/core/conversation_memory_test.cpp+++ b/src/core/conversation_memory_test.cpp@@ -50,7 +50,7 @@ int main() {check(!conversation_memory_admit(std::numeric_limits<uint64_t>::max(),std::numeric_limits<uint64_t>::max(), 1), "maximal sum overflow rejected");// Test the real provider without assuming any particular amount of free RAM.- const auto available = conversation_available_memory();+ const auto available = available_host_bytes();check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown");#if defined(_WIN32)// Unknown must fail closed in production, but must not let a broken Windows provider pass this test.diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 9374183ca..a3ccfc756 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -596,6 +596,9 @@ struct Options {/// conversation_cache_slots whatever its length, so without it a client that interleaves short side requests/// with one long conversation evicts the long one (oldest first). 0 = park every conversation.int64_t conversation_cache_min_tokens = 0;+ /// --memory-limit-mib N / STRATA_MEMORY_LIMIT_MIB: the total RAM this engine's container or cgroup may use, for a+ /// container that cannot see its real limit (0 or unset = none; the flag wins over the variable)+ int64_t memory_limit_mib = -1;/// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check)int64_t session_min_free_mib = 4096;bool session_save_reclaim = false;@@ -739,8 +742,11 @@ void usage() {" of RAM each; 0 = read every prompt from the start)\n"" --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"" --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"- " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n"- " session file (default 2560)\n"+ " --conversation-cache-min-free-mib N --serve: RAM floor (under MemAvailable, the cgroup limits and\n"+ " --memory-limit-mib) when parking, saving or restoring a session (default 2560)\n"+ " --memory-limit-mib N --serve: the total RAM (MiB) this engine's container or cgroup may use, when\n"+ " the container cannot see its real limit (also STRATA_MEMORY_LIMIT_MIB; the flag\n"+ " wins; 0 = none). Parking and session save/restore keep their floor under it\n"" --conversation-cache-min-tokens N --serve: park only conversations of at least N tokens, so\n"" short side requests do not take the slots a long one needs (default 0 = park any)\n"" --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n"@@ -1033,6 +1039,13 @@ struct GpuStage {int32_t* mrope = nullptr; ///< --vision: the image-position table on its device};+// what a refusal on the RAM guard says it had: "900 MiB available, source cgroup" (the smallest of MemAvailable, the+// cgroup limits above the engine and --memory-limit-mib; see strata/core/conversation_memory.hpp)+static std::string ram_note(const std::optional<strata::core::HostMemoryReading>& mem) {+ if (!mem) return "RAM telemetry unavailable";+ return std::to_string(mem->available >> 20) + " MiB available, source " + strata::core::memory_source_name(mem->source);+}+// ---- issue #31: what the watchdog prints before it stops a stalled enginestruct MemSample {unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows)@@ -1825,7 +1838,7 @@ int main(int argc, char** argv) {else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||a == "--conversation-cache-min-free-mib" || a == "--conversation-cache-min-tokens" ||- a == "--session-min-free-mib") {+ a == "--session-min-free-mib" || a == "--memory-limit-mib") {const std::string value = next(a.c_str());int64_t number = 0;const auto result = std::from_chars(value.data(), value.data() + value.size(), number);@@ -1839,6 +1852,7 @@ int main(int argc, char** argv) {else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number;else if (a == "--conversation-cache-min-tokens") o.conversation_cache_min_tokens = number;else if (a == "--session-min-free-mib") o.session_min_free_mib = number;+ else if (a == "--memory-limit-mib") o.memory_limit_mib = number;else o.conversation_cache_slots = (int) number;}else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true;@@ -1978,6 +1992,38 @@ int main(int argc, char** argv) {if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last);}strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation)+ { // the RAM guard (parking, session save/restore): --memory-limit-mib, else STRATA_MEMORY_LIMIT_MIB, else none+ int64_t mib = o.memory_limit_mib;+ if (mib < 0) {+ const char* env = std::getenv("STRATA_MEMORY_LIMIT_MIB");+ if (env != nullptr && env[0] != '\0') {+ const size_t len = std::strlen(env);+ const auto parsed = std::from_chars(env, env + len, mib);+ if (parsed.ec != std::errc{} || parsed.ptr != env + len || mib < 0 || mib > INT64_MAX / (1024 * 1024)) {+ std::fprintf(stderr, "STRATA_MEMORY_LIMIT_MIB needs a nonnegative integer within range (got \"%s\")\n", env);+ return 2;+ }+ } else mib = 0;+ }+ strata::core::set_memory_limit_bytes((uint64_t) mib << 20);+ if (o.serve || mib > 0) {+ constexpr double GiB = 1073741824.0;+ const auto mem = strata::core::sample_host_memory();+ if (!mem) {+ std::fprintf(stderr, "strata generate: memory guard: the available RAM cannot be read; parking and session "+ "save/restore are refused\n");+ } else {+ std::fprintf(stderr, "strata generate: memory guard: limit %.1f GiB (source: %s), current %.1f GiB, "+ "reclaimable cache credited %.1f GiB; available %.1f GiB (MemAvailable %.1f GiB%s), "+ "floor %lld MiB\n",+ (double) mem->limit / GiB, strata::core::memory_source_name(mem->source),+ (double) mem->current / GiB, (double) mem->credit / GiB, (double) mem->available / GiB,+ (double) mem->mem_available / GiB,+ mib > 0 ? (", --memory-limit-mib " + std::to_string((long long) mib)).c_str() : "",+ (long long) o.conversation_cache_min_free_mib);+ }+ }+ }if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");@@ -7156,18 +7202,21 @@ int main(int argc, char** argv) {// left. Each ConversationBuffer is a list of 16 MiB segments, each segment its own// allocation, so an evicted entry is back with the kernel before the next check reads// /proc/meminfo; no waiting is needed. slots() bounds the loop, and the two lines- // below say what it did either way.+ // below say what it did either way. The reading is the guard's (MemAvailable, the cgroup+ // limits above the engine, --memory-limit-mib); `mem` keeps the last one for the refusal line.size_t evicted = 0;+ std::optional<strata::core::HostMemoryReading> mem;auto admit = [&] {+ mem = strata::core::sample_host_memory();return strata::core::conversation_memory_admit(- strata::core::conversation_available_memory(), additional, floor);+ mem ? std::optional<uint64_t>(mem->available) : std::nullopt, additional, floor);};while (!admit() && conversations.size() > 0 && evicted < conversations.slots() &&conversations.evict_oldest())++evicted;if (!admit()) {- std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor; evicted %zu, %zu still parked, or telemetry unavailable)\n",- additional >> 20, (long long) o.conversation_cache_min_free_mib,+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, %s; evicted %zu, %zu still parked)\n",+ additional >> 20, (long long) o.conversation_cache_min_free_mib, ram_note(mem).c_str(),evicted, conversations.size());return true;}@@ -7190,8 +7239,11 @@ int main(int argc, char** argv) {return false;image.stage_images.push_back(std::move(part));}- if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {- std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");+ const auto mem_after = strata::core::sample_host_memory();+ if (!strata::core::conversation_memory_admit(+ mem_after ? std::optional<uint64_t>(mem_after->available) : std::nullopt, 0, floor)) {+ std::fprintf(stderr, "strata serve: conversation cache: skip parking (RAM floor after capture: %lld MiB needed, %s)\n",+ (long long) o.conversation_cache_min_free_mib, ram_note(mem_after).c_str());return true;}const size_t snapshot_bytes = image.bytes();@@ -8815,7 +8867,7 @@ int main(int argc, char** argv) {const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;if (o.session_save_reclaim) {const auto freed = strata::core::session_save_reclaim(- checks, conversations, sl, floor, strata::core::conversation_available_memory);+ checks, conversations, sl, floor, strata::core::available_host_bytes);if (freed.bytes || freed.checkpoints || freed.parked) {// A removed tail must not mark a later checkpoint at this length as a tail.if (tail_ckpt_len >= 0 && std::none_of(checks.begin(), checks.end(), [&](const auto& c) {@@ -8827,13 +8879,13 @@ int main(int argc, char** argv) {}}auto admit = [&](uint64_t need, std::string& why) {- const auto avail = strata::core::conversation_available_memory();+ const auto mem = strata::core::sample_host_memory();+ const std::optional<uint64_t> avail = mem ? std::optional<uint64_t>(mem->available) : std::nullopt;if (strata::core::conversation_memory_admit(avail, need, floor)) return true;why = "not enough RAM to save the session (" +(need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) +" MiB plus a floor of " + std::to_string((long long) o.conversation_cache_min_free_mib) +- " MiB needed, " + (avail ? std::to_string(*avail >> 20) + " MiB available)"- : "RAM telemetry unavailable)");+ " MiB needed, " + ram_note(mem) + ")";return false;};std::vector<ConvCheckpoint> disk_checks;@@ -8885,11 +8937,12 @@ int main(int argc, char** argv) {limits.progress = moving;const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;limits.admit = [floor, &o](uint64_t need, std::string& why) {- const auto avail = strata::core::conversation_available_memory();+ const auto mem = strata::core::sample_host_memory();+ const std::optional<uint64_t> avail = mem ? std::optional<uint64_t>(mem->available) : std::nullopt;if (strata::core::conversation_memory_admit(avail, need, floor)) return true;why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " +std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " +- (avail ? std::to_string(*avail >> 20) + " MiB available)" : "RAM telemetry unavailable)");+ ram_note(mem) + ")";return false;};if (!strata::core::conversation_session_read_limits(diff --git a/sycl/src/program/generate.cpp b/sycl/src/program/generate.cppindex 35c1c4315..840880a57 100644--- a/sycl/src/program/generate.cpp+++ b/sycl/src/program/generate.cpp@@ -7400,7 +7400,7 @@ int main(int argc, char **argv) try {const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;const size_t retained = reuse.bytes() + stage_retained;const size_t additional = estimate > retained ? estimate - retained : 0;- if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(),+ if (!strata::core::conversation_memory_admit(strata::core::available_host_bytes(),additional, floor)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",additional >> 20, (long long) o.conversation_cache_min_free_mib);@@ -7424,7 +7424,7 @@ int main(int argc, char **argv) try {return false;image.stage_images.push_back(std::move(part));}- if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {+ if (!strata::core::conversation_memory_admit(strata::core::available_host_bytes(), 0, floor)) {std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");return true;}@@ -9100,7 +9100,7 @@ int main(int argc, char **argv) try {}const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;auto admit = [&](uint64_t need, std::string& why) {- const auto avail = strata::core::conversation_available_memory();+ const auto avail = strata::core::available_host_bytes();if (strata::core::conversation_memory_admit(avail, need, floor)) return true;why = "not enough RAM to save the session (" +(need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) +@@ -9158,7 +9158,7 @@ int main(int argc, char **argv) try {limits.progress = moving;const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;limits.admit = [floor, &o](uint64_t need, std::string& why) {- const auto avail = strata::core::conversation_available_memory();+ const auto avail = strata::core::available_host_bytes();if (strata::core::conversation_memory_admit(avail, need, floor)) return true;why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " +std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " +diff --git a/tests/core/memory_guard_test.cpp b/tests/core/memory_guard_test.cppnew file mode 100644index 000000000..c7abc665f--- /dev/null+++ b/tests/core/memory_guard_test.cpp@@ -0,0 +1,339 @@+// available_host_bytes(): MemAvailable, the cgroup limits above this process, and the operator's cap, on fixture+// directories standing in for /proc/meminfo, /proc/self/cgroup and /sys/fs/cgroup. CPU only, no GPU.+#include "strata/core/conversation_memory.hpp"++#include <unistd.h>++#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <fstream>+#include <string>++using namespace strata::core;+namespace fs = std::filesystem;++namespace {++int checks = 0;+void check(bool ok, const char* label) {+ ++checks;+ if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }+}++constexpr uint64_t MiB = 1ull << 20;+constexpr uint64_t GiB = 1ull << 30;++struct Fixture {+ fs::path dir;+ Fixture() {+ static int n = 0;+ dir = fs::temp_directory_path() / ("strata_memory_guard_" + std::to_string((long) ::getpid()) + "_" + std::to_string(n++));+ fs::remove_all(dir);+ fs::create_directories(dir / "cgroup");+ }+ ~Fixture() { std::error_code ec; fs::remove_all(dir, ec); }+ void put(const std::string& rel, const std::string& text) {+ const fs::path p = dir / rel;+ fs::create_directories(p.parent_path());+ std::ofstream(p, std::ios::binary) << text;+ }+ void put(const std::string& rel, uint64_t n) { put(rel, std::to_string(n) + "\n"); }+ void meminfo(uint64_t total, uint64_t available) {+ put("meminfo", "MemTotal: " + std::to_string(total / 1024) + " kB\nMemFree: 1 kB\nMemAvailable: " ++ std::to_string(available / 1024) + " kB\n");+ }+ void self(const std::string& text) { put("self_cgroup", text + "\n"); }+ MemoryProbePaths paths() const { return {(dir / "meminfo").string(), (dir / "self_cgroup").string(), (dir / "cgroup").string()}; }+ std::optional<HostMemoryReading> sample(uint64_t explicit_limit = 0) const { return sample_host_memory(paths(), explicit_limit); }+};++} // namespace++int main() {+ // no cgroup limit anywhere ("max" at every level, and the root without memory files): plain MemAvailable+ {+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB);+ f.self("0::/a/b");+ f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 90 * GiB);+ f.put("cgroup/a/memory.max", "max\n"); f.put("cgroup/a/memory.current", 60 * GiB);+ f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);+ const auto r = f.sample();+ check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "max everywhere is plain MemAvailable");+ check(r->limit == 120 * GiB && r->current == 95 * GiB && r->mem_available == 25 * GiB, "meminfo reading: MemTotal and used");+ }+ // nested v2 limits: the tightest room of the group and its ancestors wins, "max" levels are skipped+ {+ Fixture f;+ f.meminfo(120 * GiB, 80 * GiB);+ f.self("0::/a/b");+ f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 90 * GiB); // 10 GiB of room+ f.put("cgroup/a/memory.max", 60 * GiB); f.put("cgroup/a/memory.current", 58 * GiB); // 2 GiB of room+ f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);+ auto r = f.sample();+ check(r && r->available == 2 * GiB && r->source == MemorySource::cgroup, "tightest ancestor wins");+ check(r->limit == 60 * GiB && r->current == 58 * GiB, "reading names that group's limit and usage");+ f.put("cgroup/a/memory.current", 59 * GiB + 512 * MiB);+ r = f.sample();+ check(r && r->available == 512 * MiB, "the room follows memory.current");+ f.put("cgroup/a/memory.current", 61 * GiB);+ r = f.sample();+ check(r && r->available == 0 && r->source == MemorySource::cgroup, "usage over the limit is a known zero");+ f.put("cgroup/a/memory.current", 10 * GiB);+ r = f.sample();+ check(r && r->available == 10 * GiB && r->limit == 100 * GiB, "the root's room wins once the group has more");+ check(r->source == MemorySource::cgroup, "source cgroup");+ // the room under a limit larger than MemAvailable is bounded by MemAvailable+ f.meminfo(120 * GiB, 4 * GiB);+ r = f.sample();+ check(r && r->available == 4 * GiB && r->source == MemorySource::meminfo, "MemAvailable bounds a roomy cgroup");+ }+ // memory.high below memory.max counts, and a high of "max" does not+ {+ Fixture f;+ f.meminfo(120 * GiB, 80 * GiB);+ f.self("0::/g");+ f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", 99 * GiB + 900 * MiB);+ f.put("cgroup/g/memory.current", 99 * GiB);+ auto r = f.sample();+ check(r && r->available == 900 * MiB && r->limit == 99 * GiB + 900 * MiB, "memory.high lower than memory.max");+ f.put("cgroup/g/memory.high", "max\n");+ r = f.sample();+ check(r && r->available == 1 * GiB && r->limit == 100 * GiB, "memory.high max leaves memory.max");+ f.put("cgroup/g/memory.max", "max\n"); f.put("cgroup/g/memory.high", 90 * GiB);+ r = f.sample();+ check(r && r->available == 0, "memory.high alone, already exceeded");+ }+ // the operator's cap: the container cannot see its real limit (memory.max is "max" at the namespace root)+ {+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB); // the stale view: MemAvailable says 25 GiB+ f.self("0::/system.slice/strata.service");+ f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");+ f.put("cgroup/memory.current", 99 * GiB + 724 * MiB);+ f.put("cgroup/system.slice/strata.service/memory.max", "max\n");+ f.put("cgroup/system.slice/strata.service/memory.current", 97 * GiB);+ check(f.sample() && f.sample()->available == 25 * GiB && f.sample()->source == MemorySource::meminfo,+ "without the cap the stale MemAvailable is believed");+ auto r = f.sample(100 * GiB);+ check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "the cap minus the root's memory.current");+ check(r->limit == 100 * GiB && r->current == 99 * GiB + 724 * MiB, "reading names the cap and the usage");+ r = f.sample(99 * GiB);+ check(r && r->available == 0 && r->source == MemorySource::flag, "usage over the cap is a known zero");+ r = f.sample(200 * GiB);+ check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "a cap above everything else changes nothing");+ // a real limit visible and tighter than the cap: the tighter one+ f.put("cgroup/system.slice/memory.max", 98 * GiB); f.put("cgroup/system.slice/memory.current", 97 * GiB + 512 * MiB);+ r = f.sample(100 * GiB);+ check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "cap tighter than the visible cgroup limit");+ r = f.sample(150 * GiB);+ check(r && r->available == 512 * MiB && r->source == MemorySource::cgroup, "visible cgroup limit tighter than the cap");+ // equal rooms: the operator's number is the one reported+ r = f.sample(99 * GiB + 724 * MiB + 512 * MiB);+ check(r && r->available == 512 * MiB && r->source == MemorySource::flag, "a tie goes to the operator's cap");+ // no memory.current at the root: used = MemTotal - MemAvailable+ fs::remove(f.dir / "cgroup/system.slice/memory.max");+ fs::remove(f.dir / "cgroup/memory.current");+ r = f.sample(100 * GiB);+ check(r && r->available == 5 * GiB && r->source == MemorySource::flag && r->current == 95 * GiB,+ "without the root's memory.current the meminfo-derived usage is used");+ // ... and with no MemTotal either, the usage is unknown: unknown, not a guess+ f.put("meminfo", "MemAvailable: 1024 kB\n");+ check(!f.sample(100 * GiB), "cap with unknown usage is unknown");+ check(f.sample().has_value(), "no cap, no usage needed");+ }+ // malformed or unusable files: the sample is unknown (admission refuses), never a guess+ {+ const char* bad_values[] = {"garbage\n", "", "\n", "-5\n", "+5\n", "12x\n", "1 2\n", "18446744073709551616\n",+ "0x10\n", "MAX\n"};+ for (const char* file : {"memory.max", "memory.high", "memory.current"}) {+ for (const char* text : bad_values) {+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB);+ f.self("0::/g");+ f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", "max\n");+ f.put("cgroup/g/memory.current", 50 * GiB);+ f.put(std::string("cgroup/g/") + file, text);+ check(!f.sample(), "malformed cgroup file is unknown");+ check(!f.sample(100 * GiB), "malformed cgroup file is unknown with the cap too");+ }+ }+ Fixture f;+ f.self("0::/g");+ f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.current", 50 * GiB);+ f.meminfo(120 * GiB, 25 * GiB);+ check(f.sample() && f.sample()->available == 25 * GiB, "the fixture itself is sound");+ fs::remove(f.dir / "cgroup/g/memory.current");+ check(!f.sample(), "a finite limit with no usage beside it is unknown");+ f.put("cgroup/g/memory.max", "max\n");+ check(f.sample() && f.sample()->available == 25 * GiB, "no finite limit and no usage: the level is skipped");+ f.put("cgroup/g/memory.current", "max\n");+ check(!f.sample(), "memory.current is never \"max\"");+ f.put("cgroup/g/memory.current", 1ull);+ for (const char* text : {"", "MemAvailable: 12 MB\n", "MemAvailable: 1x kB\n", "MemTotal: 5 kB\n",+ "MemAvailable: 5 kB\nMemAvailable: 6 kB\n"}) {+ f.put("meminfo", text);+ check(!f.sample(), "malformed MemAvailable is unknown");+ }+ fs::remove(f.dir / "meminfo");+ check(!f.sample(), "no meminfo is unknown");+ f.meminfo(120 * GiB, 25 * GiB);+ f.self("0::/a/../g");+ check(!f.sample(), "a .. component in the cgroup path is refused");+ f.self("garbage without colons");+ check(f.sample() && f.sample()->available == 25 * GiB, "unparsable /proc/self/cgroup lines are ignored");+ }+ // a path from /proc/self/cgroup that this mount does not show: the deepest group that is there (at worst the root)+ {+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB);+ f.self("0::/lxc/105/ns/deep");+ f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 99 * GiB);+ auto r = f.sample();+ check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "an invisible group falls back to the mount's root");+ f.put("cgroup/lxc/memory.max", 100 * GiB); f.put("cgroup/lxc/memory.current", 99 * GiB + 256 * MiB);+ r = f.sample();+ check(r && r->available == 1 * GiB - 256 * MiB, "the deepest visible prefix is read too");+ }+ // no /proc/self/cgroup file: the mount's root group; no mount: MemAvailable alone+ {+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB);+ f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 98 * GiB);+ auto r = f.sample();+ check(r && r->available == 2 * GiB, "no cgroup file: the root group");+ fs::remove_all(f.dir / "cgroup");+ r = f.sample();+ check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "no cgroup mount: MemAvailable");+ check(f.sample(100 * GiB) && f.sample(100 * GiB)->source == MemorySource::flag &&+ f.sample(100 * GiB)->available == 5 * GiB, "no cgroup mount, a cap: meminfo-derived usage");+ }+ // cgroup v1+ {+ Fixture f;+ f.meminfo(120 * GiB, 80 * GiB);+ f.self("12:cpu,cpuacct:/x\n4:memory:/m/n\n1:name=systemd:/x");+ f.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull);+ f.put("cgroup/memory/memory.usage_in_bytes", 90 * GiB);+ f.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); f.put("cgroup/memory/m/memory.usage_in_bytes", 60 * GiB);+ f.put("cgroup/memory/m/n/memory.limit_in_bytes", 9223372036854771712ull);+ f.put("cgroup/memory/m/n/memory.usage_in_bytes", 1 * GiB);+ auto r = f.sample();+ check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup && r->limit == 64 * GiB, "v1: the tightest limit, unlimited skipped");+ r = f.sample(100 * GiB);+ check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup, "v1 with a looser cap");+ r = f.sample(92 * GiB);+ check(r && r->available == 2 * GiB && r->source == MemorySource::flag && r->current == 90 * GiB, "v1 with a tighter cap: the v1 root's usage");+ f.put("cgroup/memory/m/memory.limit_in_bytes", "junk\n");+ check(!f.sample(), "v1 malformed limit is unknown");+ }+ // hybrid: a v2 line, but the memory controller lives in the v1 tree+ {+ Fixture f;+ f.meminfo(120 * GiB, 80 * GiB);+ f.self("5:memory:/g\n0::/g");+ f.put("cgroup/cgroup.controllers", "cpu\n");+ f.put("cgroup/g/cpu.max", "max 100000\n");+ f.put("cgroup/memory/g/memory.limit_in_bytes", 10 * GiB); f.put("cgroup/memory/g/memory.usage_in_bytes", 9 * GiB);+ auto r = f.sample();+ check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "hybrid falls through to v1");+ f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 1 * GiB);+ r = f.sample();+ check(r && r->available == 80 * GiB, "v2 memory files win over v1 when both exist");+ }+ // the one credited kind of reclaimable memory: clean inactive file cache from the same group's memory.stat+ {+ const auto stat = [](uint64_t inactive, uint64_t active, uint64_t shmem, uint64_t dirty = 0, uint64_t wb = 0) {+ return "anon 1\nfile 2\nshmem " + std::to_string(shmem) + "\ninactive_file " + std::to_string(inactive) ++ "\nactive_file " + std::to_string(active) + "\nfile_dirty " + std::to_string(dirty) ++ "\nfile_writeback " + std::to_string(wb) + "\nunevictable 5\n";+ };+ Fixture f;+ f.meminfo(120 * GiB, 25 * GiB);+ f.self("0::/system.slice/strata.service");+ f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");+ f.put("cgroup/memory.current", 98 * GiB + 324 * MiB);+ f.put("cgroup/memory.stat", stat(3 * GiB + 800 * MiB, 27 * GiB, 65 * GiB));+ f.put("cgroup/system.slice/strata.service/memory.max", "max\n");+ f.put("cgroup/system.slice/strata.service/memory.current", 90 * GiB);+ // the operator's cap: the root's memory.current less the root's inactive_file; active_file and shmem are not credited+ auto r = f.sample(99 * GiB);+ check(r && r->source == MemorySource::flag && r->available == 99 * GiB - (98 * GiB + 324 * MiB - 3 * GiB - 800 * MiB),+ "the cap path credits the root's inactive_file");+ check(r->credit == 3 * GiB + 800 * MiB && r->current == 98 * GiB + 324 * MiB, "reading shows the credit and the raw usage");+ f.put("cgroup/memory.stat", stat(0, 27 * GiB, 65 * GiB));+ r = f.sample(99 * GiB);+ check(r && r->available == 700 * MiB && r->credit == 0, "only inactive_file counts: active_file and shmem give nothing");+ // dirty and writeback pages are not clean: taken off the credit+ f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 1 * GiB, 512 * MiB));+ r = f.sample(99 * GiB);+ check(r && r->credit == 1 * GiB + 512 * MiB && r->available == 700 * MiB + 1 * GiB + 512 * MiB, "dirty and writeback come off");+ f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 2 * GiB, 2 * GiB));+ r = f.sample(99 * GiB);+ check(r && r->credit == 0 && r->available == 700 * MiB, "dirty plus writeback over inactive_file leaves no credit");+ // inactive_file larger than the usage: the credit stops at the usage, headroom never exceeds the cap+ f.put("cgroup/memory.stat", stat(500 * GiB, 0, 0));+ f.meminfo(300 * GiB, 200 * GiB); // so the cap's room (not MemAvailable) is the smallest term+ r = f.sample(99 * GiB);+ check(r && r->credit == 98 * GiB + 324 * MiB && r->available == 99 * GiB && r->source == MemorySource::flag,+ "inactive_file above the usage cannot lift headroom over the cap");+ // no memory.stat, or one that cannot be read: no credit, still a sample+ fs::remove(f.dir / "cgroup/memory.stat");+ r = f.sample(99 * GiB);+ check(r && r->available == 700 * MiB && r->credit == 0, "no memory.stat: no credit");+ for (const char* text : {"", "garbage\n", "inactive_file\n", "inactive_file -1\n", "inactive_file 12x\n",+ "inactive_file 1\ninactive_file 2\n", "inactive_file 99999999999999999999\n",+ "inactive_file 4096\nfile_dirty zz\n"}) {+ f.put("cgroup/memory.stat", text);+ r = f.sample(99 * GiB);+ check(r && r->available == 700 * MiB && r->credit == 0, "unparsable memory.stat: no credit, not unknown");+ }+ // a cgroup limit's own group is credited from its own memory.stat+ f.put("cgroup/memory.stat", stat(0, 0, 0));+ f.put("cgroup/system.slice/strata.service/memory.max", 92 * GiB);+ f.put("cgroup/system.slice/strata.service/memory.stat", stat(1 * GiB, 0, 0));+ r = f.sample();+ check(r && r->source == MemorySource::cgroup && r->available == 3 * GiB && r->credit == 1 * GiB &&+ r->limit == 92 * GiB && r->current == 90 * GiB, "a cgroup limit credits its own group's inactive_file");+ f.put("cgroup/system.slice/strata.service/memory.stat", stat(500 * GiB, 0, 0));+ f.meminfo(300 * GiB, 200 * GiB);+ r = f.sample();+ check(r && r->available == 92 * GiB && r->credit == 90 * GiB, "cgroup term: the credit stops at the usage too");+ // cgroup v1: total_inactive_file (and total_dirty / total_writeback)+ Fixture g;+ g.meminfo(120 * GiB, 80 * GiB);+ g.self("4:memory:/m");+ g.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); g.put("cgroup/memory/m/memory.usage_in_bytes", 62 * GiB);+ g.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull); g.put("cgroup/memory/memory.usage_in_bytes", 62 * GiB);+ g.put("cgroup/memory/m/memory.stat", "cache 1\ninactive_file 7\ntotal_inactive_file " + std::to_string(3 * GiB) ++ "\ntotal_dirty " + std::to_string(1 * GiB) + "\ntotal_writeback 0\n");+ r = g.sample();+ check(r && r->available == 2 * GiB + 2 * GiB && r->credit == 2 * GiB && r->source == MemorySource::cgroup,+ "v1 credits total_inactive_file less total_dirty");+ g.put("cgroup/memory/m/memory.stat", "inactive_file " + std::to_string(3 * GiB) + "\n");+ r = g.sample();+ check(r && r->available == 2 * GiB && r->credit == 0, "v1 ignores the non-total inactive_file");+ }+ // the process-wide setting and the real files+ {+ check(memory_limit_bytes() == 0, "no cap by default");+ set_memory_limit_bytes(123 * MiB);+ check(memory_limit_bytes() == 123 * MiB, "cap round trip");+#if defined(__linux__)+ set_memory_limit_bytes(1); // one byte: whatever this machine uses, nothing is left+ const auto r = sample_host_memory();+ check(!r || (r->available == 0 && r->source == MemorySource::flag && available_host_bytes() == 0u),+ "the real files honour the process-wide cap");+#endif+ set_memory_limit_bytes(0);+ const auto none = available_host_bytes();+ check(!none || conversation_memory_admit(none, 0, 0), "the real files without a cap: bytes or unknown");+ check(std::string(memory_source_name(MemorySource::flag)) == "flag" &&+ std::string(memory_source_name(MemorySource::cgroup)) == "cgroup" &&+ std::string(memory_source_name(MemorySource::meminfo)) == "meminfo", "source names");+ }+ std::printf("memory_guard_test: %d checks passed\n", checks);+ return 0;+}