Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Sample the gate's memory while it runs, from inside its cgroup.
usage: gate_memory.py OUT -- COMMAND...Writes OUT/samples.jsonl (memory.stat every second, per-kind process RSS/PSSevery few seconds) and OUT/output.log (the command's output, timestamped),then prints a summary. Linux with cgroup v2 only. Not part of the gate."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathimport subprocessimport sysimport threadingimport time
STAT_KEYS = ( "anon", "file", "kernel", "shmem", "file_mapped", "file_dirty", "sock", "slab", "pagetables", "kernel_stack", "inactive_file", "active_file",)DAEMON_MARK = "ALBEDO_HOME="
def cgroup() -> Path: entry = next( line[3:] for line in Path("/proc/self/cgroup").read_text().splitlines() if line.startswith("0::") ) return Path("/sys/fs/cgroup") / entry.lstrip("/")
def memory_stat(group: Path) -> dict[str, int]: stat = dict( (key, int(value)) for key, value in ( line.split() for line in (group / "memory.stat").read_text().splitlines() ) ) out = {key: stat.get(key, 0) for key in STAT_KEYS} for name in ("memory.current", "memory.peak"): try: out[name] = int((group / name).read_text()) except OSError: pass return out
def kind(pid: str, comm: str, argv: list[str]) -> str: if comm.startswith("albedo-") and comm != "albedo-render": return "kernel:" + comm[len("albedo-") :] joined = " ".join(argv) if comm == "beam.smp": if "albedo_test" in joined or "gleam@@main" in joined: return "beam:gleam-test" try: environ = Path(f"/proc/{pid}/environ").read_bytes() except OSError: environ = b"" if DAEMON_MARK.encode() in environ: return "beam:test-daemon" return "beam:other" if comm in ("erl_child_setup", "epmd", "inet_gethost", "heart"): return "beam:aux" if comm in ("go", "compile", "link", "asm", "vet", "cgo", "gopls"): return "go:build" if comm.endswith(".test"): return "go:test-binary" if comm in ("cargo", "rustc", "cc", "ld", "cc1", "collect2") or comm.startswith( "ld." ): return "rust:build" if comm == "gleam": return "gleam:cli" if comm in ("node", "npm", "MainThread") or comm.startswith("node"): return "node" if comm == "albedo": return "cli" if comm.startswith("python"): script = next((Path(a).name for a in argv[1:] if a.endswith(".py")), "?") if script.startswith("albedo_"): return "kernel:" + script return "py:" + script return "other:" + comm
def home(pid: str) -> str: try: environ = Path(f"/proc/{pid}/environ").read_bytes().split(b"\0") except OSError: return "" found = next((v for v in environ if v.startswith(DAEMON_MARK.encode())), b"") return found[len(DAEMON_MARK) :].decode(errors="replace")
def processes(with_pss: bool) -> tuple[dict[str, dict[str, int]], list[list]]: """Return RSS and PSS by kind for the processes in this cgroup, and [pid, ppid, kind, ALBEDO_HOME, rss, cwd, argv] for each kernel and test daemon.""" totals: dict[str, dict[str, int]] = {} detail: list[list] = [] me = str(os.getpid()) own = Path("/proc/self/cgroup").read_text() for pid in os.listdir("/proc"): if not pid.isdigit() or pid == me: continue try: if Path(f"/proc/{pid}/cgroup").read_text() != own: continue comm = Path(f"/proc/{pid}/comm").read_text().strip() argv = ( Path(f"/proc/{pid}/cmdline") .read_bytes() .decode(errors="replace") .split("\0") ) rss = int(Path(f"/proc/{pid}/statm").read_text().split()[1]) * 4096 pss = 0 if with_pss: for line in Path(f"/proc/{pid}/smaps_rollup").read_text().splitlines(): if line.startswith("Pss:"): pss = int(line.split()[1]) * 1024 break except (OSError, ValueError, IndexError): continue if rss == 0: continue name = kind(pid, comm, argv) if name.startswith("kernel:") or name == "beam:test-daemon": try: stat = Path(f"/proc/{pid}/stat").read_text() except OSError: continue ppid = int(stat.rsplit(")", 1)[1].split()[1]) try: cwd = os.readlink(f"/proc/{pid}/cwd") except OSError: cwd = "" detail.append( [int(pid), ppid, name, home(pid), rss, cwd, " ".join(argv)[:300]] ) entry = totals.setdefault(name, {"n": 0, "rss": 0, "pss": 0}) entry["n"] += 1 entry["rss"] += rss entry["pss"] += pss return totals, detail
def main() -> int: out = Path(sys.argv[1]) command = sys.argv[sys.argv.index("--") + 1 :] out.mkdir(parents=True, exist_ok=True) group = cgroup() start = time.monotonic() log = open(out / "output.log", "w") child = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True )
def pump() -> None: assert child.stdout for line in child.stdout: stamp = f"[{time.monotonic() - start:7.1f}] " log.write(stamp + line) log.flush() sys.stdout.write(stamp + line) sys.stdout.flush()
reader = threading.Thread(target=pump, daemon=True) reader.start() samples = open(out / "samples.jsonl", "w") tick = 0 while child.poll() is None: record: dict[str, object] = {"t": round(time.monotonic() - start, 1)} record.update(memory_stat(group)) if tick % 3 == 0: record["procs"], record["detail"] = processes(with_pss=tick % 6 == 0) samples.write(json.dumps(record) + "\n") samples.flush() tick += 1 time.sleep(1) reader.join(timeout=10) final = memory_stat(group) elapsed = time.monotonic() - start samples.write(json.dumps({"t": round(elapsed, 1), "final": True, **final}) + "\n") print( f"gate_memory: exit={child.returncode} wall={elapsed:.0f}s peak={final.get('memory.peak', 0) / 2**30:.2f}GiB" ) return child.returncode
if __name__ == "__main__": sys.exit(main())