"""Retained major-GC BEAM bytes, Linux tree PSS/USS reusing density accounting, and bytes the tree writes to storage.""" from __future__ import annotations import ctypes import functools import json import os from pathlib import Path import re import struct import subprocess import sys import tempfile import threading import time from typing import Any import uuid ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "test/manual")) from manual.agent_density import linux_home, processes # noqa: E402 from inspect_support import Inspection # noqa: E402 def tree(app, others=False): items = processes(app, others) items.extend( {"pid": command.pid, "kind": "cli"} for command in app.daemon._commands if command.poll() is None ) for item in items: # One read gives PSS and USS from the same instant. A process that # exits after listing is gone: missing, ESRCH, or an empty zombie rollup. try: fields = Path(f"/proc/{item['pid']}/smaps_rollup").read_text().splitlines() except (FileNotFoundError, ProcessLookupError): fields = [] sizes = { line.split()[0]: int(line.split()[1]) * 1024 for line in fields if line.endswith(" kB") } item["pss"] = sizes.get("Pss:", 0) # Anonymous pages, shared ones divided among their mappers: a fork's # pages still shared with its zygote count once in the pair, and # libpython's text is not private just because nothing else maps it. # Swapped-out pages still belong to the process: a runner short of # memory moves them to swap, and resident counts alone then fall. # SwapPss stands in for private swap, which smaps_rollup does not # report; it differs only for anonymous pages shared with a fork. swapped = sizes.get("SwapPss:", 0) item["pss_anon"] = sizes.get("Pss_Anon:", 0) + swapped item["uss"] = swapped + sum( sizes.get(key, 0) for key in ("Private_Clean:", "Private_Dirty:", "Private_Hugetlb:") ) return items def split(items): """The gated tree, and the daemon's other descendants (helpers, jobs).""" other = [item["kind"].startswith("other:") for item in items] return ( [item for item, flag in zip(items, other) if not flag], [item for item, flag in zip(items, other) if flag], ) def uss_by_kind(items): kinds = {} for item in items: kinds[item["kind"]] = kinds.get(item["kind"], 0) + item["uss"] return kinds def dump_smaps(directory, items): """Diagnostic: each measured process's smaps, numbered by checkpoint.""" directory.mkdir(parents=True, exist_ok=True) count = len(list(directory.iterdir())) for item in items: try: text = Path(f"/proc/{item['pid']}/smaps").read_text() except OSError: continue (directory / f"{count:04d}-{item['kind']}-{item['pid']}").write_text(text) count += 1 LIBC = ctypes.CDLL(None, use_errno=True) @functools.cache def write_shim(): """writes_shim.c built once per run, for LD_PRELOAD.""" directory = Path(tempfile.mkdtemp(prefix="albedo-perf-shim-")) library = directory / "writes_shim.so" subprocess.run( [ "cc", "-shared", "-fPIC", "-O2", "-o", str(library), str(Path(__file__).with_name("writes_shim.c")), "-ldl", ], check=True, ) return library def proc_io(pid): """A process's /proc//io counters, or None once it is gone or while it is unreadable (mid-exec of a program with other credentials); its bytes reach its parent when it is reaped.""" try: lines = Path(f"/proc/{pid}/io").read_text().splitlines() except (FileNotFoundError, ProcessLookupError, PermissionError): return None return {key: int(value) for key, value in (line.split(": ") for line in lines)} # Long runs of digits or hex (session ids, pids, temp-file suffixes) differ # between runs; a path keeps its shape so runs aggregate by file. VARYING = re.compile( r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-fA-F]{8,}|[0-9]{4,}" ) class Writes: """Bytes the daemon's process tree writes to storage, and to which files. The total is /proc//io write_bytes less cancelled_write_bytes (pages dirtied, then truncated before writeback), summed over the daemon, its descendants and the helpers that name themselves albedo-* with this home. A reaped child's counters move into its parent's, so a process that exits under a measured parent stays counted there; one reparented outside the tree (a fork whose zygote exited) keeps its last sampled value. The by-file breakdown comes from writes_shim.c, preloaded into the tree: bytes each write call returned, per file. It counts calls, not pages, and misses writes through shared mappings and stdio, so it names files rather than adding up to the total.""" SLOT = struct.Struct("=QQQQQ216s") SLOTS = 2048 def __init__(self): # tmpfs: the table is written through a shared mapping, which on a # disk-backed file would count as the tree's own writes. handle, name = tempfile.mkstemp( prefix="albedo-perf-writes-", dir="/dev/shm" if Path("/dev/shm").is_dir() else None, ) os.ftruncate(handle, self.SLOT.size * self.SLOTS) os.close(handle) self.table = Path(name) self.env = {"LD_PRELOAD": str(write_shim()), "ALBEDO_PERF_WRITES": name} # The fixture, once attach() has a booted daemon to count. self.app: Any = None self.seen = {} self.departed = {"write_bytes": 0, "cancelled_write_bytes": 0} self.lock = threading.Lock() def attach(self, app): """Start counting for a booted daemon whose home accounts writes.""" self.app = app calibration = app.root / "write-calibration" before = proc_io("self") with open(calibration, "wb") as handle: handle.write(os.urandom(1 << 18)) os.fsync(handle.fileno()) after = proc_io("self") calibration.unlink() if ( not before or not after or after["write_bytes"] - before["write_bytes"] < 1 << 18 ): raise RuntimeError( f"{app.root} does not account written bytes (tmpfs?); " "disk writes need a disk-backed TMPDIR" ) self.sample() def ours(self): """Pid to parent pid for every process of the measured tree.""" parents, names = {}, {} for entry in os.scandir("/proc"): if not entry.name.isdigit(): continue try: stat = Path(f"/proc/{entry.name}/stat").read_text() except OSError: continue head, tail = stat.rsplit(")", 1) parents[int(entry.name)] = int(tail.split()[1]) names[int(entry.name)] = head.split("(", 1)[1] roots = {self.app.connection["pid"]} roots.update( pid for pid, name in names.items() if name.startswith("albedo-") and linux_home(pid) == str(self.app.home) ) children = {} for pid, parent in parents.items(): children.setdefault(parent, []).append(pid) found, frontier = set(), list(roots) while frontier: pid = frontier.pop() if pid in found or pid not in parents: continue found.add(pid) frontier.extend(children.get(pid, [])) return {pid: parents[pid] for pid in found} def sample(self): with self.lock: current = {} for pid, parent in self.ours().items(): counters = proc_io(pid) if counters is not None: current[pid] = (parent, counters) for pid, (parent, counters) in self.seen.items(): # Reaped by a measured parent: already in that parent's counters. if pid not in current and parent not in current: for key in self.departed: self.departed[key] += counters[key] self.seen = current totals = dict(self.departed) for _, counters in current.values(): for key in totals: totals[key] += counters[key] totals["written"] = totals["write_bytes"] - totals["cancelled_write_bytes"] return totals def files(self): """Bytes written per file, by path relative to the fixture root.""" app = self.app inodes = {} for directory, _, names in os.walk(app.root): for name in names: path = Path(directory, name) try: info = path.lstat() except OSError: continue inodes[(info.st_dev, info.st_ino)] = path data = self.table.read_bytes() result = {} for offset in range(0, len(data), self.SLOT.size): key, size, _, device, inode, raw = self.SLOT.unpack_from(data, offset) if not key or not size: continue path = inodes.get((device, inode)) or Path( raw.split(b"\0", 1)[0].decode(errors="replace") ) if path.is_relative_to(app.root): path = path.relative_to(app.root) name = VARYING.sub("*", str(path)) result[name] = result.get(name, 0) + size return result def backfilled(self, timeout=60): """Wait until the store's checkpoint worker has copied every WAL frame into the database, read from the wal-index in -shm: the backfilled frame count (nBackfill) equals the last committed frame (mxFrame). Closing a descriptor of -shm drops every POSIX lock the closing process holds there, so this is safe only because the harness never opens the database itself; the daemon's locks are its own.""" shm = self.app.home / "albedo.sqlite-shm" deadline = time.monotonic() + timeout while True: data = shm.read_bytes()[:100] # Two copies of the header; a writer between them is mid-update. if len(data) == 100 and data[:48] == data[48:96]: frames = struct.unpack_from("=I", data, 16)[0] if struct.unpack_from("=I", data, 96)[0] == frames: return if time.monotonic() > deadline: raise AssertionError(f"WAL not backfilled after {timeout} s") time.sleep(0.1) def flush(self): """Write back the home filesystem's dirty pages (syncfs).""" handle = os.open(self.app.home, os.O_RDONLY) try: if LIBC.syncfs(handle) != 0: raise OSError(ctypes.get_errno(), "syncfs") finally: os.close(handle) def close(self): self.table.unlink(missing_ok=True) class Probe: """One erl node that stays connected to the daemon's inspect node and calls albedo_perf_probe functions; starting an erl per call cost ~0.5 s each.""" MARK = "<>" def __init__(self, app): source = Path(__file__).with_name("albedo_perf_probe.erl") Inspection(app, source) # compiles the probe into app.root log = (app.home / "daemon.log").read_text(errors="replace") node = re.findall(rf"inspect: node (albedo_{app.daemon._pid}@[^\s]+)", log)[-1] cookie = (app.home / "inspect.cookie").read_text().strip() beam = json.dumps(str(app.root / "albedo_perf_probe.beam")) loop = ( f"Node = '{node}', {{ok, Bin}} = file:read_file({beam}), " "{module, _} = rpc:call(Node, code, load_binary, " '[albedo_perf_probe, "probe.erl", Bin]), ' 'Loop = fun L() -> case io:get_line("") of eof -> halt(); Line -> ' "F = list_to_atom(string:trim(Line)), " "case rpc:call(Node, albedo_perf_probe, F, [], 60000) of " '{badrpc, E} -> io:format("ERROR ~p~n", [E]); ' "R -> io:put_chars(R), io:nl() end, " f'io:put_chars("{self.MARK}\\n"), L() end end, Loop().' ) self.process = subprocess.Popen( [ "erl", "+S", "1:1", "-sname", f"perf_{uuid.uuid4().hex}", "-setcookie", cookie, "-noshell", "-eval", loop, ], cwd=app.root, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, ) self.lock = threading.Lock() def call_json(self, function): assert self.process.stdin and self.process.stdout with self.lock: self.process.stdin.write(function + "\n") self.process.stdin.flush() lines = [] while (line := self.process.stdout.readline()) and line.rstrip( "\n" ) != self.MARK: lines.append(line) output = "".join(lines).strip() if not line or output.startswith("ERROR"): raise AssertionError(f"probe {function} failed: {output}") return json.loads(output) def close(self): if self.process.stdin: self.process.stdin.close() try: self.process.wait(timeout=10) except subprocess.TimeoutExpired: self.process.kill() self.process.wait() class Measurement: def __init__(self, app, writes): self.app = app self.writes = writes writes.attach(app) self.probe = Probe(app) self.probe.call_json("start") self.peak_pss = 0 self.peak_uss = 0 self.peak_kinds = {} self.at_peak = {} self.samples = 0 self.errors = [] self.done = threading.Event() self.lock = threading.Lock() self.thread = threading.Thread(target=self.sample, daemon=True) self.thread.start() # Its own thread: a /proc scan takes long enough to thin the memory # sampler's peaks. self.write_thread = threading.Thread(target=self.sample_writes, daemon=True) self.write_thread.start() def sample_writes(self): # Often enough to see a reparented helper before it exits. while not self.done.wait(0.5): try: self.writes.sample() except Exception as error: self.errors.append(str(error)) return def sample(self): while not self.done.is_set(): started = time.monotonic() try: items, others = split(tree(self.app, others=True)) kinds = uss_by_kind(items + others) with self.lock: self.peak_pss = max( self.peak_pss, sum(item["pss"] for item in items) ) uss = sum(item["uss"] for item in items) if uss > self.peak_uss: self.peak_uss = uss self.at_peak = kinds for kind, value in kinds.items(): self.peak_kinds[kind] = max(self.peak_kinds.get(kind, 0), value) self.samples += 1 except Exception as error: self.errors.append(str(error)) return self.done.wait(max(0, 0.05 - (time.monotonic() - started))) def retained(self): # Session actors hibernate after two quiet 100 ms ticks. No adaptive # settling or minimum selection: every checkpoint follows the same rule. time.sleep(0.3) snapshot = self.probe.call_json("snapshot") snapshot["processes"], snapshot["others"] = split(tree(self.app, others=True)) snapshot["writes"] = self.writes.sample() snapshot["written_files"] = self.writes.files() snapshot["tree_pss"] = sum(item["pss"] for item in snapshot["processes"]) snapshot["tree_uss"] = sum(item["uss"] for item in snapshot["processes"]) if directory := os.environ.get("PERF_SMAPS"): dump_smaps(Path(directory), snapshot["processes"]) by_pid = {item["pid"]: item for item in snapshot["processes"]} for session, pid in snapshot["kernels"].items(): if pid not in by_pid: raise RuntimeError(f"live kernel {pid} missing from measured tree") snapshot["sessions"].setdefault(session, {"bytes": 0, "processes": 0})[ "kernel_uss" ] = by_pid[pid]["uss"] return snapshot def written(self): """Bytes the tree has written so far, net of cancelled writes.""" return self.writes.sample()["written"] def flush(self): self.writes.flush() def backfilled(self): self.writes.backfilled() def load_code(self): self.probe.call_json("load_code") def kernels(self): """Held session kernels by session id, and the tree's processes.""" return self.probe.call_json("kernels"), tree(self.app) def peaks(self): beam = self.probe.call_json("peak") with self.lock: values = { "tree_pss": self.peak_pss, "tree_uss": self.peak_uss, "beam": beam["total"], "beam_peak": beam, "kinds": self.peak_kinds, "at_peak": self.at_peak, "samples": self.samples, } self.peak_pss = self.peak_uss = self.samples = 0 self.peak_kinds, self.at_peak = {}, {} return values def close(self): self.done.set() self.thread.join() self.write_thread.join() self.probe.call_json("stop") self.probe.close() if self.errors: raise RuntimeError(self.errors)