okami.mom/albedo

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

nekomimi.petcodemode: mcp callable from python, 256 MiB kernel memory cap, cell output spilled to a file4359cba

main
1.9 KiB53 linesraw
1"""The kernel's memory cap: a sampled physical footprint, not an allocator limit.
2
3A cell that pushes the process past the cap is interrupted within an
4interval; a single allocation larger than the cap is not refused, so this is
5a guard against a runaway cell taking the namespace down, not a sandbox.
6"""
7
8from __future__ import annotations
9
10import ctypes
11import os
12import struct
13import sys
14
15LIMIT = int(os.environ.get("ALBEDO_KERNEL_MEMORY_BYTES", str(256 * 1024 * 1024)))
16INTERVAL = 0.1  # seconds between samples while a cell runs
17# A cell that starts with the kernel already past the cap (a large variable
18# left behind) may still grow this much, so `del big` and gc.collect() run.
19SLACK = 8 * 1024 * 1024
20PAGE = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096
21
22
23def footprint() -> int | None:
24    """Bytes this process holds in physical memory: the resident set from
25    /proc, or Darwin's physical footprint (what vmmap and Activity Monitor
26    report). None where neither can tell."""
27    try:
28        with open("/proc/self/statm", "rb") as statm:
29            return int(statm.read().split()[1]) * PAGE
30    except (OSError, IndexError, ValueError):
31        return darwin_footprint(os.getpid()) if sys.platform == "darwin" else None
32
33
34def darwin_footprint(pid: int) -> int | None:
35    """ri_phys_footprint of a Darwin process's rusage_info_v0 (libproc's
36    proc_pid_rusage), the 10th field after the 16-byte uuid."""
37    try:
38        libproc = ctypes.CDLL("/usr/lib/libproc.dylib")
39    except OSError:
40        return None
41    buffer = ctypes.create_string_buffer(96)
42    if libproc.proc_pid_rusage(pid, 0, buffer) != 0:
43        return None
44    return struct.unpack_from("=Q", buffer.raw, 72)[0]
45
46
47def threshold(start: int) -> int:
48    """The footprint past which a cell that started at `start` is interrupted."""
49    return max(LIMIT, start + SLACK)
50
51
52def mebibytes(size: int) -> str:
53    return f"{size / (1024 * 1024):.0f} MiB"