okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6b63729a9
main
1#include "strata/core/conversation_memory.hpp" 2 3#include <algorithm> 4#include <atomic> 5#include <cstdio> 6#include <cstdlib> 7#include <charconv> 8#include <filesystem> 9#include <fstream> 10#include <limits> 11#include <sstream> 12#include <string> 13#include <system_error> 14#include <vector> 15 16#if defined(_WIN32 ) 17#ifndef NOMINMAX 18#define NOMINMAX 19#endif 20#include <windows.h> 21#elif defined(__APPLE__ ) 22#include <mach/mach.h> 23#include <sys/sysctl.h> 24#endif 25 26namespace strata::core { 27 28namespace fs= std::filesystem; 29 30CacheCredit cache_credit_from_stat (const std::string & stat ,uint64_t current ,bool v1 ) { 31const char * inactive_key = v1 ?"total_inactive_file" :"inactive_file" ; 32const char * active_key = v1 ?"total_active_file" :"active_file" ; 33const char * dirty_key = v1 ?"total_dirty" :"file_dirty" ; 34const char * writeback_key = v1 ?"total_writeback" :"file_writeback" ; 35 std::optional < uint64_t > inactive ,active ; 36bool active_bad = false; 37uint64_t dirty = 0 ,writeback = 0 ; 38 std::istringstream in (stat ); 39 std::string line ; 40while (std::getline (in ,line )) { 41 std::istringstream fields (line ); 42 std::string key ,value ,extra ; 43if (!(fields >>key >>value )|| (fields >>extra ))continue ; 44uint64_t * target = key == dirty_key ?& dirty :key == writeback_key ?& writeback :nullptr ; 45uint64_t n = 0 ; 46const auto parsed = std::from_chars (value .data (),value .data ()+ value .size (),n ); 47const bool ok = parsed .ec == std::errc {}&& parsed .ptr == value .data ()+ value .size (); 48if (key == inactive_key ) {if (!ok || inactive )return {};inactive = n ; } 49else if (key == active_key ) {if (!ok || active )active_bad = true;else active = n ; } 50else if (target != nullptr ) {if (!ok )return {};* target = n ; } 51 } 52if (!inactive )return {}; 53auto clean = [& ](uint64_t cached ) { 54uint64_t credit = std::min (cached ,current ); 55credit = dirty >=credit ?0 :credit - dirty ; 56credit = writeback >=credit ?0 :credit - writeback ; 57return credit ; 58 }; 59CacheCredit c ; 60c .inactive = clean (* inactive ); 61// an active_file that is missing or cannot be read adds nothing: the lists figure is then the inactive one 62const uint64_t both = active && !active_bad ? (* active > UINT64_MAX - * inactive ?UINT64_MAX :* inactive + * active ) :* inactive ; 63c .lists = clean (both ); 64return c ; 65} 66 67bool mem_credit_inactive_only (const char * env_value ) { 68return env_value != nullptr && env_value [0 ]== '1' ; 69} 70 71uint64_t cache_credit_for_limit (const CacheCredit & credit ,uint64_t limit , std::optional < uint64_t > mem_total ,bool inactive_only , 72 std::optional < uint64_t > own_mapped ) { 73if (inactive_only || !mem_total || limit >=* mem_total || !own_mapped )return credit .inactive ; 74return credit .lists > * own_mapped ?credit .lists - * own_mapped :0 ; 75} 76 77ArenaCgroupRoom arena_cgroup_room (uint64_t limit ,uint64_t current ,const std::string & stat_text , std::optional < uint64_t > mem_total , 78bool inactive_only ) { 79ArenaCgroupRoom r ; 80if (inactive_only || !mem_total || limit >=* mem_total )return r ; 81r .applies = true; 82uint64_t credit = cache_credit_from_stat (stat_text ,current , false).lists ;// <= current 83credit -= std::min (credit /2 ,limit /64 ); 84r .credit = credit ; 85const uint64_t used = current - credit ; 86r .room = used < limit ?limit - used :0 ; 87return r ; 88} 89 90namespace { 91std::atomic < uint64_t > g_locked_own_file_bytes {0 }; 92} 93 94void set_locked_own_file_bytes (uint64_t bytes ) {g_locked_own_file_bytes .store (bytes , std::memory_order_relaxed ); } 95uint64_t locked_own_file_bytes () {return g_locked_own_file_bytes .load (std::memory_order_relaxed ); } 96 97std::optional < uint64_t > own_evictable_mapped_bytes (const std::string & status_text ,uint64_t locked_file_bytes ) { 98 std::istringstream in (status_text ); 99 std::string line ; 100 std::optional < uint64_t > rss ; 101while (std::getline (in ,line )) { 102 std::istringstream fields (line ); 103 std::string key ,value ,unit ,extra ; 104if (!(fields >>key )|| key != "RssFile:" )continue ; 105if (rss || !(fields >>value >>unit )|| unit != "kB" || (fields >>extra ))return {}; 106uint64_t kb = 0 ; 107const auto parsed = std::from_chars (value .data (),value .data ()+ value .size (),kb ); 108if (parsed .ec != std::errc {}|| parsed .ptr != value .data ()+ value .size ()|| kb > UINT64_MAX /1024 )return {}; 109rss = kb * 1024 ; 110 } 111if (!rss )return {}; 112return * rss > locked_file_bytes ?* rss - locked_file_bytes :0 ; 113} 114 115namespace { 116 117std::atomic < uint64_t > g_memory_limit_bytes {0 }; 118 119// "<key> <n> kB", exactly once, nothing else on the line; the value in bytes. Anything else is unknown. 120std::optional < uint64_t > meminfo_kb_bytes (std::istream & meminfo ,const char * wanted ) { 121 std::optional < uint64_t > result ; 122 std::string line ; 123while (std::getline (meminfo ,line )) { 124 std::istringstream fields (line ); 125 std::string key ,value ,unit ,extra ; 126if (!(fields >>key )|| key != wanted )continue ; 127if (result || !(fields >>value >>unit )|| unit != "kB" || (fields >>extra ))return {}; 128uint64_t kb = 0 ; 129const auto parsed = std::from_chars (value .data (),value .data ()+ value .size (),kb ); 130if (parsed .ec != std::errc {}|| parsed .ptr != value .data ()+ value .size ()|| 131kb > std::numeric_limits < uint64_t > ::max () /1024 )return {}; 132result = kb * 1024 ; 133 } 134if (meminfo .bad ()|| (meminfo .fail ()&& !meminfo .eof ()))return {}; 135return result ; 136} 137 138// One cgroup control file: absent (no such file), a number, "max", or unusable (unreadable, empty, not a number). 139struct Value { 140enum Kind {absent ,bad ,max ,number }kind = absent ; 141uint64_t n = 0 ; 142}; 143 144Value read_value (const fs::path & path ) { 145 std::error_code ec ; 146const bool there = fs::exists (path ,ec ); 147if (ec )return {Value ::bad ,0 }; 148if (!there )return {}; 149 std::ifstream file (path ); 150if (!file )return {Value ::bad ,0 }; 151char buf [64 ]; 152file .read (buf ,sizeof buf ); 153if (file .bad ())return {Value ::bad ,0 }; 154size_t len = (size_t )file .gcount (); 155if (len == sizeof buf )return {Value ::bad ,0 }; 156while (len > 0 && (buf [len - 1 ]== '\n' || buf [len - 1 ]== '\r' || buf [len - 1 ]== ' ' || buf [len - 1 ]== '\t' ))-- len ; 157if (len == 0 )return {Value ::bad ,0 }; 158if (len == 3 && std::string (buf ,3 )== "max" )return {Value ::max ,0 }; 159Value v {Value ::number ,0 }; 160const auto parsed = std::from_chars (buf ,buf + len ,v .n ); 161if (parsed .ec != std::errc {}|| parsed .ptr != buf + len )return {Value ::bad ,0 }; 162return v ; 163} 164 165// The reclaimable file cache of one group, from its memory.stat, in the two forms the guard uses 166// (cache_credit_from_stat in the header has the rules). A memory.stat that is missing gives no credit - not an 167// unknown sample. 168CacheCredit reclaimable_cache (const fs::path & dir ,uint64_t current ,bool v1 ) { 169 std::ifstream stat (dir /"memory.stat" ); 170if (!stat )return {}; 171 std::ostringstream text ; 172text <<stat .rdbuf (); 173return cache_credit_from_stat (text .str (),current ,v1 ); 174} 175 176// What the cgroup files say: every finite limit with the usage charged against it (and the cache credits of that 177// group), and the usage and credit of the topmost visible group (the root of this namespace - what a container's own 178// limit is measured over). 179struct CgroupScan { 180struct Limit {uint64_t limit ,current ;CacheCredit credit ; }; 181 std::vector < Limit > limits ; 182 std::optional < uint64_t > root_current ; 183uint64_t root_credit = 0 ; 184bool any_files = false; 185}; 186 187// `dirs` runs from the top visible group down to the process's own. False when a file that is there cannot be used. 188bool scan_levels (const std::vector < fs::path >& dirs ,const char * const * limit_names ,size_t n_limits , 189const char * current_name ,bool v1 ,CgroupScan & out ) { 190for (size_t i = 0 ;i < dirs .size ();++ i ) { 191const Value current = read_value (dirs [i ] /current_name ); 192 std::vector < Value > limits ; 193for (size_t k = 0 ;k < n_limits ;++ k )limits .push_back (read_value (dirs [i ] /limit_names [k ])); 194bool unusable = current .kind == Value ::bad || current .kind == Value ::max ; 195bool finite_limit = false; 196for (const Value & v :limits ) { 197unusable = unusable || v .kind == Value ::bad ; 198finite_limit = finite_limit || v .kind == Value ::number ; 199 } 200if (unusable )return false; 201if (current .kind == Value ::absent ) { 202if (finite_limit )return false;// a limit with no usage beside it: the room cannot be told 203continue ;// no memory controller at this level (e.g. the host's root group) 204 } 205out .any_files = true; 206const CacheCredit credit = reclaimable_cache (dirs [i ],current .n ,v1 ); 207if (i == 0 ) {out .root_current = current .n ;out .root_credit = credit .inactive ; } 208for (const Value & v :limits ) { 209if (v .kind != Value ::number )continue ; 210if (v1 && v .n >= (1ull <<62 ))continue ;// v1's "unlimited" is a number near 2^63 211out .limits .push_back ({v .n ,current .n ,credit }); 212 } 213 } 214return true; 215} 216 217// "/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 218// without its own cgroup namespace sees its group's host path in /proc/self/cgroup, but only its own subtree under 219// the mount, so the deepest one that exists (at worst the mount itself) is the nearest group we can read. 220bool group_dirs (const fs::path & root ,const std::string & group , std::vector < fs::path >& dirs ) { 221dirs .clear (); 222 std::vector < std::string > names ; 223 std::istringstream parts (group ); 224for (std::string part ; std::getline (parts ,part ,'/' );) { 225if (part .empty ())continue ; 226if (part == "." || part == ".." )return false;// never walk out of the mount, nor trust a path that tries 227names .push_back (part ); 228 } 229 std::error_code ec ; 230if (!fs::is_directory (root ,ec ))return true;// nothing mounted: no cgroup terms 231dirs .push_back (root ); 232 fs::path at = root ; 233for (const std::string & part :names ) { 234at /=part ; 235if (!fs::is_directory (at ,ec ))break ; 236dirs .push_back (at ); 237 } 238return true; 239} 240 241bool scan_cgroups (const MemoryProbePaths & paths ,CgroupScan & out ) { 242 std::optional < std::string > v2_group ,v1_group ; 243 std::ifstream groups (paths .self_cgroup ); 244if (!groups ) { 245v2_group = "/" ;// no /proc/self/cgroup: the mount's own top group is still readable 246 }else { 247 std::string line ; 248while (std::getline (groups ,line )) { 249const size_t c1 = line .find (':' ),c2 = c1 == std::string::npos ?c1 :line .find (':' ,c1 + 1 ); 250if (c2 == std::string::npos )continue ; 251const std::string controllers = line .substr (c1 + 1 ,c2 - c1 - 1 ),group = line .substr (c2 + 1 ); 252if (line .compare (0 ,c1 ,"0" )== 0 && controllers .empty ()) {v2_group = group ;continue ; } 253 std::istringstream names (controllers ); 254for (std::string name ; std::getline (names ,name ,',' );) 255if (name == "memory" )v1_group = group ; 256 } 257 } 258 std::vector < fs::path > dirs ; 259if (v2_group ) { 260if (!group_dirs (paths .cgroup_root ,* v2_group ,dirs ))return false; 261static const char * const names []= {"memory.max" ,"memory.high" }; 262if (!scan_levels (dirs ,names ,2 ,"memory.current" , false,out ))return false; 263 } 264if (!out .any_files && v1_group ) {// cgroup v1: the memory controller's own tree 265if (!group_dirs (fs::path (paths .cgroup_root ) /"memory" ,* v1_group ,dirs ))return false; 266static const char * const names []= {"memory.limit_in_bytes" }; 267if (!scan_levels (dirs ,names ,1 ,"memory.usage_in_bytes" , true,out ))return false; 268 } 269return true; 270} 271 272std::optional < HostMemoryReading > combine (std::optional < uint64_t > available , std::optional < uint64_t > total , 273const CgroupScan & cg ,uint64_t explicit_limit ,bool inactive_only , 274 std::optional < uint64_t > own_mapped ) { 275if (!available )return {}; 276HostMemoryReading r ; 277r .mem_available = * available ; 278r .available = * available ; 279r .source = MemorySource ::meminfo ; 280r .limit = total .value_or (0 ); 281r .current = total && * total >=* available ?* total - * available :0 ; 282for (const CgroupScan ::Limit & l :cg .limits ) { 283const uint64_t credit = cache_credit_for_limit (l .credit ,l .limit ,total ,inactive_only ,own_mapped ); 284const uint64_t used = l .current - credit ;// credit <= current 285const uint64_t room = l .limit > used ?l .limit - used :0 ; 286if (room < r .available ) { 287r .available = room ; 288r .source = MemorySource ::cgroup ; 289r .limit = l .limit ; 290r .current = l .current ; 291r .credit = credit ; 292 } 293 } 294if (explicit_limit != 0 ) { 295uint64_t used = 0 ,credit = 0 ; 296if (cg .root_current ) {used = * cg .root_current ;credit = cg .root_credit ; } 297else if (total && * total >=* available )used = * total - * available ; 298else return {}; 299const uint64_t net = used - credit ; 300const uint64_t room = explicit_limit > net ?explicit_limit - net :0 ; 301if (room <=r .available ) {// a tie goes to the operator's number: it is the one that names the real cap 302r .available = room ; 303r .source = MemorySource ::flag ; 304r .limit = explicit_limit ; 305r .current = used ; 306r .credit = credit ; 307 } 308 } 309return r ; 310} 311 312}// namespace 313 314const char * memory_source_name (MemorySource source ) { 315switch (source ) { 316case MemorySource ::flag :return "flag" ; 317case MemorySource ::cgroup :return "cgroup" ; 318default :return "meminfo" ; 319 } 320} 321 322std::optional < uint64_t > conversation_mem_available (std::istream & meminfo ) { 323return meminfo_kb_bytes (meminfo ,"MemAvailable:" ); 324} 325 326void set_memory_limit_bytes (uint64_t bytes ) {g_memory_limit_bytes .store (bytes , std::memory_order_relaxed ); } 327uint64_t memory_limit_bytes () {return g_memory_limit_bytes .load (std::memory_order_relaxed ); } 328 329std::optional < HostMemoryReading > sample_host_memory (const MemoryProbePaths & paths ,uint64_t explicit_limit ) { 330 std::ifstream avail_file (paths .meminfo ); 331if (!avail_file )return {}; 332const std::optional < uint64_t > available = conversation_mem_available (avail_file ); 333if (!available )return {}; 334 std::ifstream total_file (paths .meminfo ); 335 std::optional < uint64_t > total ; 336if (total_file )total = meminfo_kb_bytes (total_file ,"MemTotal:" ); 337CgroupScan cg ; 338if (!scan_cgroups (paths ,cg )) { 339// Without an operator cap the cgroup files are only an extra: the guard falls back to MemAvailable alone (what 340// 0.1.41 used), once-warned. With a cap the usage cannot be told, so the sample stays unknown. 341if (explicit_limit != 0 )return {}; 342static std::atomic < bool > warned {false}; 343if (!warned .exchange (true)) 344 std::fprintf (stderr ,"[strata] memory guard: the cgroup memory files could not be read or parsed, using " 345"MemAvailable; set --memory-limit-mib to the container's limit\n" ); 346cg = CgroupScan {}; 347 } 348 std::optional < uint64_t > own_mapped ; 349if (!cg .limits .empty ()) {// only a limit can use it 350 std::ifstream status (paths .self_status ); 351if (status ) { 352 std::ostringstream text ; 353text <<status .rdbuf (); 354own_mapped = own_evictable_mapped_bytes (text .str (),locked_own_file_bytes ()); 355 } 356 } 357return combine (available ,total ,cg ,explicit_limit ,mem_credit_inactive_only (std::getenv ("STRATA_MEM_CREDIT_INACTIVE" )),own_mapped ); 358} 359 360std::optional < HostMemoryReading > sample_host_memory () { 361#if defined(_WIN32 ) 362MEMORYSTATUSEX status {}; 363status .dwLength = sizeof status ; 364// #1607: the commit limit (RAM + page file) refuses an allocation while physical RAM is still free 365if (!GlobalMemoryStatusEx (& status ))return {}; 366return combine (std::min < uint64_t > (status .ullAvailPhys ,status .ullAvailPageFile ),status .ullTotalPhys ,CgroupScan {},memory_limit_bytes (), true, std::nullopt ); 367#elif defined(__linux__ ) 368return sample_host_memory (MemoryProbePaths {},memory_limit_bytes ()); 369#elif defined(__APPLE__ ) 370// The rule of metal/src/engine/arena_budget.h's arena_avail(): free + purgeable pages, plus the inactive and speculative 371// ones only up to the file-backed page count (other programs' inactive anonymous memory is what compresses or swaps). 372vm_statistics64_data_t vs {}; 373mach_msg_type_number_t count = HOST_VM_INFO64_COUNT ; 374if (host_statistics64 (mach_host_self (),HOST_VM_INFO64 , (host_info64_t )& vs ,& count )!= KERN_SUCCESS )return {}; 375uint64_t total = 0 ; 376size_t len = sizeof total ; 377if (sysctlbyname ("hw.memsize" ,& total ,& len ,nullptr ,0 )!= 0 || total == 0 )return {}; 378const uint64_t pg = (uint64_t )vm_page_size ; 379const uint64_t available = ((uint64_t )vs .free_count + vs .purgeable_count )* pg + 380 std::min < uint64_t > (((uint64_t )vs .inactive_count + vs .speculative_count )* pg , 381 (uint64_t )vs .external_page_count * pg ); 382return combine (available ,total ,CgroupScan {},memory_limit_bytes (), true, std::nullopt ); 383#else 384return {}; 385#endif 386} 387 388std::optional < uint64_t > available_host_bytes () { 389const auto reading = sample_host_memory (); 390if (!reading )return {}; 391return reading -> available ; 392} 393 394}// namespace strata::core