diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index 9ec7e61821..133b4ad67f 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -1,4 +1,7 @@ self-hosted-runner: labels: - darkbloom-linux-arm64 - - darkbloom-macos-arm64 + - darkbloom-macos-arm64-4x16 + - darkbloom-macos-arm64-4x24 + - darkbloom-macos-arm64-8x16 + - darkbloom-macos-arm64-12x32 diff --git a/.github/scripts/ci-resource-sampler.py b/.github/scripts/ci-resource-sampler.py new file mode 100755 index 0000000000..bfa54280c9 --- /dev/null +++ b/.github/scripts/ci-resource-sampler.py @@ -0,0 +1,720 @@ +#!/usr/bin/env python3 +"""Sample a macOS CI job's memory and CPU use and report the peaks. Report-only. + +`start` runs the sampler in the background and gives later steps the samples +directory as CI_RESOURCE_SAMPLES. Every INTERVAL seconds it writes one CSV row: + +- memory by class, from `vm_stat`: app (anonymous pages less purgeable ones; + Metal buffers count here), wired, file cache (file-backed and purgeable + pages, which the kernel can reclaim), compressed, + and used = app + wired + compressed, as Activity Monitor counts it; swap in + use (`sysctl vm.swapusage`) and the kernel's memory pressure level + (`kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical); +- busy vCPUs over the interval, from the host's CPU ticks (`host_statistics`), + or the sum of the `ps` %cpu averages where those are not available; +- the physical footprint of every process this user can read, from + `proc_pid_rusage`: `ri_phys_footprint` is the counter `footprint` and + Activity Monitor show, and it includes IOAccelerator (Metal) memory. The row + keeps their sum and the three largest by lifetime peak + (`ri_lifetime_max_phys_footprint`, so a peak between samples counts), each + with the test selection it runs under; +- the largest resident process (`ps` RSS), to compare with earlier runs. + +When the largest footprint first reaches 2 GiB, and again when it is 2 GiB +above the last capture, `/usr/bin/footprint`, where present, writes that +process's breakdown by category beside the samples (at most twice a job). Test +runners call `mark start|end LABEL PID` around each selection; a process below +PID belongs to LABEL. + +`report` stops the sampler. It prints the peak of each class, the three +largest processes, the selections that ran at the peak, the busy vCPU mean, +95th percentile and maximum, and the sampled time scaled to 4 and 8 vCPUs; in +CI it also writes them to the step summary, and to summary.json beside the +samples. No subcommand ever fails a job: every error is printed and exits 0. + +Subcommands: + start DIRECTORY [--interval SECONDS] + report DIRECTORY + mark start|end LABEL [PID] into $CI_RESOURCE_SAMPLES (nothing without it); + PID defaults to the caller, the mark's parent + run DIRECTORY [--interval SECONDS] the background loop `start` launches +""" + +import argparse +import csv +import ctypes +import json +import os +import re +import signal +import subprocess +import sys +import time +from pathlib import Path + +FIELDS = ( + "time", + "used_bytes", + "app_bytes", + "wired_bytes", + "file_bytes", + "compressed_bytes", + "swap_bytes", + "pressure", + "busy_vcpus", + "footprint_bytes", + "top_rss_bytes", + "top_command", + "top_footprints", +) +CLASSES = ( + ("used_bytes", "Used"), + ("app_bytes", "App"), + ("wired_bytes", "Wired"), + ("file_bytes", "File cache"), + ("compressed_bytes", "Compressed"), + ("swap_bytes", "Swap"), +) +SAMPLES = "samples.csv" +PID = "sampler.pid" +MACHINE = "machine.txt" +MARKS = "marks.csv" +SUMMARY = "summary.json" +ENVIRONMENT = "CI_RESOURCE_SAMPLES" +FOOTPRINT = "/usr/bin/footprint" +CAPTURES = 2 +CAPTURE_STEP = 2 * 2**30 +CAPTURE_SECONDS = 60 +TOP = 3 +SCALED_VCPUS = (4, 8) +GIB = 2**30 +UNITS = {"K": 2**10, "M": 2**20, "G": 2**30} +RUSAGE_INFO_V4 = 4 +HOST_CPU_LOAD_INFO = 3 + + +class RusageInfoV4(ctypes.Structure): + """struct rusage_info_v4 ().""" + + _fields_ = [("ri_uuid", ctypes.c_uint8 * 16)] + [ + (name, ctypes.c_uint64) + for name in ( + "ri_user_time", + "ri_system_time", + "ri_pkg_idle_wkups", + "ri_interrupt_wkups", + "ri_pageins", + "ri_wired_size", + "ri_resident_size", + "ri_phys_footprint", + "ri_proc_start_abstime", + "ri_proc_exit_abstime", + "ri_child_user_time", + "ri_child_system_time", + "ri_child_pkg_idle_wkups", + "ri_child_interrupt_wkups", + "ri_child_pageins", + "ri_child_elapsed_abstime", + "ri_diskio_bytesread", + "ri_diskio_byteswritten", + "ri_cpu_time_qos_default", + "ri_cpu_time_qos_maintenance", + "ri_cpu_time_qos_background", + "ri_cpu_time_qos_utility", + "ri_cpu_time_qos_legacy", + "ri_cpu_time_qos_user_initiated", + "ri_cpu_time_qos_user_interactive", + "ri_billed_system_time", + "ri_serviced_system_time", + "ri_logical_writes", + "ri_lifetime_max_phys_footprint", + "ri_instructions", + "ri_cycles", + "ri_billed_energy", + "ri_serviced_energy", + "ri_interval_max_phys_footprint", + "ri_runnable_time", + ) + ] + + +# Native calls fail with these; the sampler then records what it can without them. +NATIVE_ERRORS = (OSError, AttributeError, TypeError, ctypes.ArgumentError) +_system = None + + +def system(): + """(libSystem with the calls the sampler makes, the host port). + + OSError where there is none. + """ + global _system + if _system is None: + if sys.platform != "darwin": + raise OSError("proc_pid_rusage and host_statistics need macOS") + library = ctypes.CDLL("/usr/lib/libSystem.B.dylib") + library.proc_pid_rusage.argtypes = [ + ctypes.c_int, + ctypes.c_int, + ctypes.POINTER(RusageInfoV4), + ] + library.proc_pid_rusage.restype = ctypes.c_int + library.mach_host_self.argtypes = [] + library.mach_host_self.restype = ctypes.c_uint32 + library.host_statistics.argtypes = [ + ctypes.c_uint32, + ctypes.c_int, + ctypes.POINTER(ctypes.c_uint32 * 4), + ctypes.POINTER(ctypes.c_uint32), + ] + library.host_statistics.restype = ctypes.c_int + _system = (library, library.mach_host_self()) + return _system + + +def output(*argv): + return subprocess.run( + argv, capture_output=True, text=True, timeout=10, check=True + ).stdout + + +def memory(vm_stat): + """Bytes of each memory class (CLASSES but swap) from `vm_stat` text.""" + size = int(re.search(r"page size of (\d+) bytes", vm_stat).group(1)) + pages = { + name.strip().lower(): int(value) + for name, value in re.findall(r'^"?([^:"]+)"?:\s+(\d+)\.', vm_stat, re.M) + } + purgeable = pages["pages purgeable"] + app = pages["anonymous pages"] - purgeable + wired = pages["pages wired down"] + compressed = pages["pages occupied by compressor"] + return { + "used_bytes": (app + wired + compressed) * size, + "app_bytes": app * size, + "wired_bytes": wired * size, + "file_bytes": (pages["file-backed pages"] + purgeable) * size, + "compressed_bytes": compressed * size, + } + + +def swap_used(swapusage): + """Bytes of swap in use from `sysctl -n vm.swapusage` text.""" + match = re.search(r"used = ([0-9.]+)([KMG])", swapusage) + return int(float(match.group(1)) * UNITS[match.group(2)]) + + +def processes(ps): + """[(pid, ppid, %cpu, RSS bytes, command)] from `ps` text. + + The text is the output of `ps -A -o pid=,ppid=,%cpu=,rss=,comm=`. + """ + rows = [] + for line in ps.splitlines(): + fields = line.split(None, 4) + try: + rows.append( + ( + int(fields[0]), + int(fields[1]), + float(fields[2]), + int(fields[3]) * 1024, + os.path.basename(fields[4].strip()) if len(fields) > 4 else "", + ) + ) + except (IndexError, ValueError): + continue + return rows + + +def footprints(pids): + """{pid: (physical footprint, lifetime peak)} of the processes this user reads.""" + library, _ = system() + info = RusageInfoV4() + found = {} + for pid in pids: + if library.proc_pid_rusage(pid, RUSAGE_INFO_V4, ctypes.byref(info)) == 0: + found[pid] = (info.ri_phys_footprint, info.ri_lifetime_max_phys_footprint) + return found + + +def cpu_ticks(): + """(busy, all) CPU ticks of every CPU since boot. + + HOST_CPU_LOAD_INFO: user, system, idle, nice. + """ + library, host = system() + ticks = (ctypes.c_uint32 * 4)() + count = ctypes.c_uint32(4) + if ( + library.host_statistics( + host, HOST_CPU_LOAD_INFO, ctypes.byref(ticks), ctypes.byref(count) + ) + != 0 + ): + raise OSError("host_statistics(HOST_CPU_LOAD_INFO) failed") + return ticks[0] + ticks[1] + ticks[3], sum(ticks) + + +def busy_vcpus(before, after, cpus): + """Busy vCPUs between two cpu_ticks() readings; None when no tick passed.""" + busy, total = ((now - then) % 2**32 for now, then in zip(after, before)) + return busy / total * cpus if total else None + + +def read_marks(path): + """[(time, event, label, pid)] of the whole rows of a marks file; [] without one.""" + try: + text = path.read_text() + except OSError: + return [] + marks = [] + for row in csv.reader(text.splitlines()): + if len(row) != 4 or not row[3].isdigit(): + continue + stamp, event, label, pid = row + try: + marks.append((float(stamp), event, label, int(pid))) + except ValueError: + continue + return marks + + +def active_marks(path): + """{pid: label} of the selections started under pid and not yet ended. + + From a marks file. + """ + active = {} + for _, event, label, pid in read_marks(path): + if event == "start": + active[pid] = label + elif event == "end" and active.get(pid) == label: + del active[pid] + return active + + +def selection_of(pid, parents, active): + """The label of the nearest marked ancestor of pid (itself included), or "".""" + seen = set() + while pid and pid not in seen: + if pid in active: + return active[pid] + seen.add(pid) + pid = parents.get(pid) + return "" + + +class Sampler: + """One sample a call; keeps the CPU ticks and footprint captures between calls.""" + + def __init__(self, directory): + self.directory = directory + self.cpus = os.cpu_count() or 1 + self.ticks = self.read_ticks() + self.captured_bytes = 0 + self.captures = [] + + def read_ticks(self): + try: + return cpu_ticks() + except NATIVE_ERRORS: + return None + + def busy(self, listed): + ticks = self.read_ticks() + busy = ( + busy_vcpus(self.ticks, ticks, self.cpus) if ticks and self.ticks else None + ) + self.ticks = ticks + return sum(cpu for _, _, cpu, _, _ in listed) / 100 if busy is None else busy + + def sample(self): + row = {"time": f"{time.time():.0f}", **memory(output("vm_stat"))} + row["swap_bytes"] = swap_used(output("sysctl", "-n", "vm.swapusage")) + row["pressure"] = output( + "sysctl", "-n", "kern.memorystatus_vm_pressure_level" + ).strip() + listed = processes(output("ps", "-A", "-o", "pid=,ppid=,%cpu=,rss=,comm=")) + row["busy_vcpus"] = f"{self.busy(listed):.2f}" + largest = max( + listed, key=lambda process: process[3], default=(0, 0, 0.0, 0, "") + ) + row["top_rss_bytes"], row["top_command"] = largest[3], largest[4] + try: + found = footprints([pid for pid, *_ in listed]) + except NATIVE_ERRORS: + found = {} + if found: + parents = {pid: ppid for pid, ppid, *_ in listed} + commands = {pid: command for pid, _, _, _, command in listed} + active = active_marks(self.directory / MARKS) + ranked = sorted(found, key=lambda pid: found[pid][1], reverse=True)[:TOP] + row["footprint_bytes"] = sum(current for current, _ in found.values()) + row["top_footprints"] = json.dumps( + [ + [ + pid, + commands[pid], + *found[pid], + selection_of(pid, parents, active), + ] + for pid in ranked + ] + ) + current = max(found, key=lambda pid: found[pid][0]) + self.capture(current, found[current][0], row["time"]) + self.reap() + return [row.get(field, "") for field in FIELDS] + + def capture(self, pid, footprint, stamp): + """`footprint PID` into the directory. + + Only when footprint is CAPTURE_STEP above the last capture (or 0). + """ + if ( + footprint < self.captured_bytes + CAPTURE_STEP + or len(self.captures) >= CAPTURES + or not os.access(FOOTPRINT, os.X_OK) + ): + return + self.captured_bytes = footprint + with open(self.directory / f"footprint-{stamp}-{pid}.txt", "w") as handle: + self.captures.append( + ( + time.monotonic(), + subprocess.Popen( + [FOOTPRINT, str(pid)], + stdin=subprocess.DEVNULL, + stdout=handle, + stderr=subprocess.STDOUT, + ), + ) + ) + + def reap(self): + for started, child in self.captures: + if child.poll() is None and time.monotonic() - started > CAPTURE_SECONDS: + child.kill() + + +def run(directory, interval): + sampler = Sampler(directory) + with open(directory / SAMPLES, "a", newline="") as handle: + writer = csv.writer(handle) + while True: + try: + writer.writerow(sampler.sample()) + handle.flush() + except ( + Exception + ): # Report-only: a failed sample is skipped; the loop goes on. + pass + time.sleep(interval) + + +def start(directory, interval): + directory.mkdir(parents=True, exist_ok=True) + with open(directory / SAMPLES, "w", newline="") as handle: + csv.writer(handle).writerow(FIELDS) + try: + machine = output("sysctl", "-n", "hw.ncpu", "hw.memsize").split() + (directory / MACHINE).write_text(f"{machine[0]} {machine[1]}\n") + except (OSError, IndexError, subprocess.SubprocessError): + pass + child = subprocess.Popen( + [ + sys.executable, + os.path.abspath(__file__), + "run", + str(directory), + "--interval", + str(interval), + ], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + (directory / PID).write_text(f"{child.pid}\n") + github_env = os.environ.get("GITHUB_ENV") + if github_env: + with open(github_env, "a") as handle: + handle.write(f"{ENVIRONMENT}={directory.resolve()}\n") + print( + f"Resource sampler: pid {child.pid}, every {interval} s, " + f"into {directory / SAMPLES}" + ) + + +def mark(event, label, pid=None): + """Note that selection `label` starts or ends under process pid. + + pid defaults to the caller. Nothing outside a sampled job. + """ + directory = os.environ.get(ENVIRONMENT) + if not directory: + return + if event not in ("start", "end"): + raise ValueError(f"mark takes start or end, got {event!r}") + with open(Path(directory) / MARKS, "a", newline="") as handle: + csv.writer(handle).writerow( + [ + f"{time.time():.3f}", + event, + label, + os.getppid() if pid is None else int(pid), + ] + ) + + +def percentile(values, fraction): + ordered = sorted(values) + return ordered[min(len(ordered) - 1, int(fraction * len(ordered)))] + + +def number(value): + return int(value) if value not in (None, "") else None + + +def gib(value): + return "n/a" if value is None else f"{value / GIB:.2f}" + + +def utc(stamp): + return time.strftime("%H:%M:%S", time.gmtime(float(stamp))) + + +def selections_at(path, moment): + """The labels of the marks file that had started and not ended at moment.""" + spans = {} + for stamp, event, label, pid in read_marks(path): + span = spans.setdefault((label, pid), [None, None]) + span[0 if event == "start" else 1] = stamp + return sorted( + label + for (label, _), (began, ended) in spans.items() + if began is not None and began <= moment and (ended is None or ended >= moment) + ) + + +def scaled_seconds(rows, cpus): + """Sampled seconds if busy vCPUs above `cpus` had run on `cpus`. + + Each interval is stretched by busy / cpus. + """ + total = 0.0 + for before, after in zip(rows, rows[1:]): + total += (int(after["time"]) - int(before["time"])) * max( + 1.0, float(after["busy_vcpus"]) / cpus + ) + return total + + +def top_processes(rows): + """The TOP processes by lifetime footprint peak. + + [pid, command, peak bytes, selection, time]. + """ + best = {} + for row in rows: + for pid, command, _, peak, label in json.loads( + row.get("top_footprints") or "[]" + ): + known = best.get(pid) + if known is None or peak > known[2]: + best[pid] = [ + pid, + command, + peak, + label or (known[3] if known else ""), + row["time"], + ] + elif label and not known[3]: + known[3] = label + return sorted(best.values(), key=lambda process: process[2], reverse=True)[:TOP] + + +def footprint_captures(directory): + """[(file, its header and IOAccelerator lines)] of the `footprint` captures.""" + captured = [] + for path in sorted(directory.glob("footprint-*.txt")): + lines = [ + line.strip() + for line in path.read_text(errors="replace").splitlines() + if line.strip() + ] + kept = [ + line for line in lines if "Footprint" in line or "IOAccelerator" in line + ][:4] or lines[:1] + captured.append((path.name, kept)) + return captured + + +def summary(directory): + """The report's Markdown lines; also writes summary.json.""" + with open(directory / SAMPLES, newline="") as handle: + rows = list(csv.DictReader(handle)) + if not rows: + return ["Resource sampler: no samples."] + facts = { + "samples": len(rows), + "seconds": int(rows[-1]["time"]) - int(rows[0]["time"]), + "peaks": {}, + } + lines = [] + machine = directory / MACHINE + cpus = None + if machine.is_file(): + cpus, memsize = (int(value) for value in machine.read_text().split()) + facts["machine"] = {"vcpus": cpus, "memory_bytes": memsize} + lines.append(f"Machine: {cpus} vCPUs, {memsize / GIB:.1f} GiB.") + for key, _ in CLASSES + (("footprint_bytes", "footprints"),): + known = [row for row in rows if number(row.get(key)) is not None] + peak = max(known, key=lambda row: number(row[key]), default=None) + facts["peaks"][key] = ( + None + if peak is None + else {"bytes": number(peak[key]), "time": int(peak["time"])} + ) + + def peak_bytes(key): + return None if facts["peaks"][key] is None else facts["peaks"][key]["bytes"] + + busy = [float(row["busy_vcpus"]) for row in rows] + facts["pressure"] = max(int(row["pressure"]) for row in rows) + facts["busy_vcpus"] = { + "mean": sum(busy) / len(busy), + "p95": percentile(busy, 0.95), + "max": max(busy), + } + lines += [ + "| Samples | " + + " | ".join(f"{name} (GiB)" for _, name in CLASSES) + + " | Worst pressure | Busy vCPUs mean | p95 | max |", + "|---" * (len(CLASSES) + 5) + "|", + f"| {len(rows)} over {facts['seconds']} s | " + + " | ".join(gib(peak_bytes(key)) for key, _ in CLASSES) + + f" | {facts['pressure']} | {facts['busy_vcpus']['mean']:.2f} | " + f"{facts['busy_vcpus']['p95']:.2f} | " + f"{facts['busy_vcpus']['max']:.2f} |", + "", + "Each class peaks at its own time. Used = app + wired + compressed " + "(`vm_stat`); app holds Metal buffers; the file cache is reclaimable.", + ] + if facts["peaks"]["used_bytes"]: + moment = facts["peaks"]["used_bytes"]["time"] + running = selections_at(directory / MARKS, moment) + facts["selections_at_peak_used"] = running + lines.append( + f"Peak used at {utc(moment)} UTC" + + (f", during: {', '.join(running)}." if running else ".") + ) + top = top_processes(rows) + facts["top_processes"] = [ + { + "pid": pid, + "command": command, + "peak_footprint_bytes": footprint, + "selection": label, + "time": int(stamp), + } + for pid, command, footprint, label, stamp in top + ] + if top: + lines += [ + "", + "| Process | PID | Peak footprint (GiB) | Selection | Seen at (UTC) |", + "|---|---|---|---|---|", + ] + lines += [ + f"| `{command}` | {pid} | {gib(footprint)} | {label or '-'} " + f"| {utc(stamp)} |" + for pid, command, footprint, label, stamp in top + ] + lines.append( + "Footprints: `proc_pid_rusage` lifetime peak (includes " + "IOAccelerator/Metal memory), processes of this user only; their sum " + f"peaked at {gib(peak_bytes('footprint_bytes'))} GiB." + ) + largest = max(rows, key=lambda row: int(row["top_rss_bytes"])) + lines.append( + "Largest RSS (`ps`, earlier runs' figure): " + f"{gib(int(largest['top_rss_bytes']))} GiB " + f"(`{largest['top_command']}`)." + ) + if cpus: + facts["scaled_seconds"] = { + str(n): scaled_seconds(rows, n) for n in SCALED_VCPUS if n < cpus + } + if facts["scaled_seconds"]: + lines.append( + f"Sampled {facts['seconds']} s; at " + + ", at ".join( + f"{n} vCPUs about {seconds:.0f} s" + for n, seconds in facts["scaled_seconds"].items() + ) + + " (each interval stretched by busy vCPUs / vCPUs where busy " + "exceeds them)." + ) + captures = footprint_captures(directory) + facts["footprint_tool"] = "present" if os.access(FOOTPRINT, os.X_OK) else "absent" + facts["footprint_captures"] = [ + {"file": name, "lines": kept} for name, kept in captures + ] + lines.append( + f"`{FOOTPRINT}`: {facts['footprint_tool']}, {len(captures)} captures " + "in the samples artifact." + ) + lines += [ + f"- `{name}`: " + "; ".join(f"`{line}`" for line in kept) + for name, kept in captures + ] + (directory / SUMMARY).write_text(json.dumps(facts, indent=2, sort_keys=True) + "\n") + return lines + + +def report(directory): + pid = directory / PID + if pid.is_file(): + try: + os.kill(int(pid.read_text()), signal.SIGTERM) + except (OSError, ValueError): + pass + lines = ["### Resource samples (report-only)", "", *summary(directory)] + print("\n".join(lines)) + step_summary = os.environ.get("GITHUB_STEP_SUMMARY") + if step_summary: + with open(step_summary, "a") as handle: + handle.write("\n".join(lines) + "\n\n") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + for name in ("start", "run", "report"): + command = commands.add_parser(name) + command.add_argument("directory", type=Path) + if name != "report": + command.add_argument("--interval", type=float, default=5.0) + marking = commands.add_parser("mark") + marking.add_argument("event") + marking.add_argument("label") + marking.add_argument("pid", nargs="?") + args = parser.parse_args(argv) + try: + if args.command == "start": + start(args.directory, args.interval) + elif args.command == "run": + run(args.directory, args.interval) + elif args.command == "mark": + mark(args.event, args.label, args.pid) + else: + report(args.directory) + except Exception as error: # Report-only: never fail the job. + print(f"::warning title=Resource sampler::{type(error).__name__}: {error}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test-ci-resource-sampler.py b/.github/scripts/test-ci-resource-sampler.py new file mode 100755 index 0000000000..fc890c16a4 --- /dev/null +++ b/.github/scripts/test-ci-resource-sampler.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +"""Offline checks of the report-only resource sampler. + +They check parsing, attribution, the summary, and that it never fails. + +The native readers (`proc_pid_rusage`, `host_statistics`) and a whole sample +run only on macOS; the CI jobs' own samples are their check. +""" + +import contextlib +import csv +import importlib.util +import io +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "scripts/ci-resource-sampler.py" +SPEC = importlib.util.spec_from_file_location("ci_resource_sampler", SCRIPT) +sampler = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(sampler) +GIB = sampler.GIB + +# macOS 27 `vm_stat` output, shortened. +VM_STAT = """Mach Virtual Memory Statistics: (page size of 16384 bytes) +Pages free: 100000. +Pages active: 200000. +Pages inactive: 150000. +Pages speculative: 5000. +Pages wired down: 50000. +Pages purgeable: 2000. +"Translation faults": 9999999. +File-backed pages: 120000. +Anonymous pages: 230000. +Pages occupied by compressor: 10000. +""" +PS = """ 1 0 0.0 512 /sbin/launchd + 100 1 12.5 204800 /usr/bin/swift-frontend + 200 150 250.0 4194304 /private/tmp/w/.build/debug/swiftpm-testing-helper + 150 1 0.0 512 /Applications/Xcode 27.app/usr/bin/my tool + garbage +""" +FOOTPRINT_TEXT = """\ +====================================================================== +swiftpm-testing-helper [200]: 64-bit Footprint: 9 GB (16384 bytes per page) +====================================================================== + + Dirty Clean Reclaimable Regions Category + 6 GB 0 B 0 B 12 IOAccelerator (graphics) + 1 GB 0 B 0 B 800 MALLOC_LARGE +""" + + +def write_rows(directory, rows): + with open(directory / sampler.SAMPLES, "w", newline="") as handle: + writer = csv.DictWriter(handle, sampler.FIELDS) + writer.writeheader() + writer.writerows(rows) + + +def row( + stamp, used, app, wired, cache, compressed, swap, pressure, busy, footprint, top +): + return { + "time": stamp, + "used_bytes": used * GIB, + "app_bytes": app * GIB, + "wired_bytes": wired * GIB, + "file_bytes": cache * GIB, + "compressed_bytes": compressed * GIB, + "swap_bytes": swap * GIB, + "pressure": pressure, + "busy_vcpus": busy, + "footprint_bytes": "" if footprint is None else footprint * GIB, + "top_rss_bytes": GIB, + "top_command": "swiftpm-testing-helper", + "top_footprints": json.dumps(top) if top else "", + } + + +class ParsingTests(unittest.TestCase): + def test_memory_counts_each_class_as_activity_monitor_does(self): + classes = sampler.memory(VM_STAT) + page = 16384 + self.assertEqual( + classes, + { + "used_bytes": (228000 + 50000 + 10000) * page, + "app_bytes": 228000 * page, + "wired_bytes": 50000 * page, + "file_bytes": 122000 * page, + "compressed_bytes": 10000 * page, + }, + ) + with self.assertRaises(KeyError): + sampler.memory(VM_STAT.replace("Anonymous pages", "Anonymous")) + + def test_swap_used_reads_each_unit(self): + self.assertEqual( + sampler.swap_used( + "total = 2048.00M used = 1536.50M free = 511.50M (encrypted)" + ), + int(1536.5 * 2**20), + ) + self.assertEqual( + sampler.swap_used("total = 4.00G used = 1.50G free = 2.50G"), + int(1.5 * GIB), + ) + self.assertEqual( + sampler.swap_used("total = 0.00M used = 0.00M free = 0.00M (encrypted)"), + 0, + ) + with self.assertRaises(AttributeError): + sampler.swap_used("no swap") + + def test_processes_keep_pid_parent_cpu_rss_and_the_command_name(self): + listed = sampler.processes(PS) + self.assertEqual(listed[1], (100, 1, 12.5, 204800 * 1024, "swift-frontend")) + self.assertEqual(listed[2][4], "swiftpm-testing-helper") + self.assertEqual(listed[3][4], "my tool") + self.assertEqual(len(listed), 4) + + def test_busy_vcpus_from_tick_deltas_survive_a_counter_wrap(self): + self.assertAlmostEqual(sampler.busy_vcpus((100, 1000), (400, 1600), 12), 6.0) + self.assertAlmostEqual( + sampler.busy_vcpus((2**32 - 100, 2**32 - 50), (200, 550), 12), 6.0 + ) + self.assertIsNone(sampler.busy_vcpus((5, 9), (5, 9), 12)) + + def test_native_readers_refuse_outside_macos(self): + if sys.platform == "darwin": + self.skipTest("the native readers exist here") + with self.assertRaises(OSError): + sampler.footprints([1]) + self.assertIsNone(sampler.Sampler(Path(".")).read_ticks()) + + +class AttributionTests(unittest.TestCase): + def test_active_marks_and_the_nearest_marked_ancestor_name_the_selection(self): + with tempfile.TemporaryDirectory() as work: + marks = Path(work) / sampler.MARKS + self.assertEqual(sampler.active_marks(marks), {}) + marks.write_text( + "1.0,start,1-of-6,150\n2.0,start,2-of-6,160\n3.0,end,1-of-6,150\n" + "4.0,start,parallel,150\n5.0,end,1-of-6,160\nbroken\n" + "6.0,start,x,pid\n7.0,start,y,1.5\n" + "partial,start,z,170\n" + ) + active = sampler.active_marks(marks) + # An end ends only the same label under the same pid; a row with a bad + # time or pid is skipped. + self.assertEqual(active, {150: "parallel", 160: "2-of-6"}) + parents = {300: 200, 200: 160, 160: 1, 1: 0, 7: 8, 8: 7} + self.assertEqual(sampler.selection_of(300, parents, active), "2-of-6") + self.assertEqual(sampler.selection_of(150, parents, active), "parallel") + self.assertEqual(sampler.selection_of(999, parents, active), "") + self.assertEqual(sampler.selection_of(7, parents, active), "") + + def test_mark_writes_only_in_a_sampled_job_and_defaults_to_its_caller(self): + with tempfile.TemporaryDirectory() as work: + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop(sampler.ENVIRONMENT, None) + sampler.mark("start", "1-of-6") + self.assertFalse((Path(work) / sampler.MARKS).exists()) + with mock.patch.dict(os.environ, {sampler.ENVIRONMENT: work}): + sampler.mark("start", "1-of-6") + sampler.mark("end", "1-of-6", 4242) + with self.assertRaises(ValueError): + sampler.mark("begin", "1-of-6", 1) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + self.assertEqual(sampler.main(["mark", "begin", "1-of-6"]), 0) + self.assertIn( + "::warning title=Resource sampler::ValueError", printed.getvalue() + ) + rows = list( + csv.reader((Path(work) / sampler.MARKS).read_text().splitlines()) + ) + self.assertEqual( + [row[1:] for row in rows], + [["start", "1-of-6", str(os.getppid())], ["end", "1-of-6", "4242"]], + ) + + +class CaptureTests(unittest.TestCase): + def test_footprint_runs_on_each_new_high_and_at_most_twice(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/echo")) + capturing = sampler.Sampler(directory) + capturing.capture(200, GIB, "100") # Under the first step. + capturing.capture(200, 3 * GIB, "105") + capturing.capture(200, 4 * GIB, "110") # Not 2 GiB above the last capture. + capturing.capture(201, 5 * GIB, "115") + capturing.capture(202, 9 * GIB, "120") # Two captures already. + for _, child in capturing.captures: + child.wait(timeout=10) + self.assertEqual( + sorted(path.name for path in directory.glob("footprint-*")), + ["footprint-105-200.txt", "footprint-115-201.txt"], + ) + self.assertEqual((directory / "footprint-115-201.txt").read_text(), "201\n") + + def test_a_footprint_that_outlives_its_time_is_killed(self): + with tempfile.TemporaryDirectory() as work: + self.enterContext(mock.patch.object(sampler, "FOOTPRINT", "/bin/sleep")) + self.enterContext(mock.patch.object(sampler, "CAPTURE_SECONDS", -1)) + capturing = sampler.Sampler(Path(work)) + capturing.capture(30, 3 * GIB, "100") + capturing.reap() + _, child = capturing.captures[0] + self.assertLess(child.wait(timeout=10), 0) + + def test_no_capture_without_the_tool(self): + with tempfile.TemporaryDirectory() as work: + self.enterContext( + mock.patch.object(sampler, "FOOTPRINT", str(Path(work) / "absent")) + ) + capturing = sampler.Sampler(Path(work)) + capturing.capture(200, 9 * GIB, "100") + self.assertEqual(capturing.captures, []) + + +class SummaryTests(unittest.TestCase): + def test_summary_reports_each_class_the_top_processes_and_the_selection_at_the_peak( + self, + ): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + write_rows( + directory, + [ + row( + "100", + 6, + 4, + 1, + 3, + 1, + 0, + 1, + 2.0, + 3, + [ + [200, "swiftpm-testing-helper", 2 * GIB, 3 * GIB, "2-of-6"], + [100, "swift-frontend", GIB, GIB, ""], + ], + ), + row( + "105", + 10, + 5, + 4, + 2, + 1, + 1, + 2, + 24.0, + 9, + [ + [200, "swiftpm-testing-helper", 8 * GIB, 9 * GIB, ""], + [300, "xctest", GIB, GIB, "3-of-6"], + ], + ), + row("110", 8, 3, 4, 5, 1, 0, 1, 6.0, None, None), + ], + ) + (directory / sampler.MACHINE).write_text(f"12 {32 * GIB}\n") + (directory / sampler.MARKS).write_text( + "101.0,start,2-of-6,150\n102.0,start,3-of-6,160\n" + "104.0,end,3-of-6,160\n108.0,end,2-of-6,150\n" + "partial,start,3-of-6,170\n" + ) + (directory / "footprint-105-200.txt").write_text(FOOTPRINT_TEXT) + (directory / "footprint-110-300.txt").write_text( + "footprint: insufficient privileges\n" + ) + self.enterContext( + mock.patch.object(sampler, "FOOTPRINT", str(directory / "absent")) + ) + lines = sampler.summary(directory) + facts = json.loads((directory / sampler.SUMMARY).read_text()) + self.assertEqual(lines[0], "Machine: 12 vCPUs, 32.0 GiB.") + self.assertEqual( + lines[3], + "| 3 over 10 s | 10.00 | 5.00 | 4.00 | 5.00 | 1.00 | 1.00 | 2 | 10.67 " + "| 24.00 | 24.00 |", + ) + self.assertIn("Peak used at 00:01:45 UTC, during: 2-of-6.", lines) + self.assertIn( + "| `swiftpm-testing-helper` | 200 | 9.00 | 2-of-6 | 00:01:45 |", lines + ) + self.assertIn("| `swift-frontend` | 100 | 1.00 | - | 00:01:40 |", lines) + self.assertIn("| `xctest` | 300 | 1.00 | 3-of-6 | 00:01:45 |", lines) + self.assertTrue(any("their sum peaked at 9.00 GiB" in line for line in lines)) + self.assertIn( + f"`{directory / 'absent'}`: absent, 2 captures in the samples artifact.", + lines, + ) + self.assertIn( + "- `footprint-105-200.txt`: `swiftpm-testing-helper [200]: 64-bit " + "Footprint: 9 GB (16384 bytes per page)`; `6 GB 0 B 0 B " + " 12 IOAccelerator (graphics)`", + lines, + ) + self.assertIn( + "- `footprint-110-300.txt`: `footprint: insufficient privileges`", lines + ) + self.assertEqual(facts["peaks"]["file_bytes"], {"bytes": 5 * GIB, "time": 110}) + self.assertEqual( + facts["peaks"]["footprint_bytes"], {"bytes": 9 * GIB, "time": 105} + ) + self.assertEqual(facts["selections_at_peak_used"], ["2-of-6"]) + self.assertEqual(facts["scaled_seconds"], {"4": 37.5, "8": 20.0}) + self.assertEqual(facts["busy_vcpus"]["p95"], 24.0) + self.assertEqual( + [process["pid"] for process in facts["top_processes"]], [200, 100, 300] + ) + + def test_summary_without_footprints_marks_or_machine_still_reports(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) + write_rows( + directory, + [ + row("100", 6, 4, 1, 3, 1, 0, 1, 2.0, None, None), + row("105", 7, 4, 2, 3, 1, 0, 1, 1.0, None, None), + ], + ) + lines = sampler.summary(directory) + facts = json.loads((directory / sampler.SUMMARY).read_text()) + self.assertIn("Peak used at 00:01:45 UTC.", lines) + self.assertFalse(any(line.startswith("| Process") for line in lines)) + self.assertIsNone(facts["peaks"]["footprint_bytes"]) + self.assertNotIn("scaled_seconds", facts) + + +class LifecycleTests(unittest.TestCase): + def test_report_never_fails_and_writes_the_step_summary(self): + with tempfile.TemporaryDirectory() as work: + summary = Path(work) / "summary" + self.enterContext( + mock.patch.dict(os.environ, {"GITHUB_STEP_SUMMARY": str(summary)}) + ) + printed = io.StringIO() + with contextlib.redirect_stdout(printed): + # No samples directory at all: a warning, never a failure. + self.assertEqual( + sampler.main(["report", str(Path(work) / "absent")]), 0 + ) + self.assertIn("::warning title=Resource sampler::", printed.getvalue()) + directory = Path(work) / "empty" + directory.mkdir() + (directory / sampler.SAMPLES).write_text(",".join(sampler.FIELDS) + "\n") + (directory / sampler.PID).write_text("not a pid\n") + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(sampler.main(["report", str(directory)]), 0) + self.assertIn("Resource sampler: no samples.", summary.read_text()) + + def test_start_runs_in_the_background_until_report_stops_it(self): + with tempfile.TemporaryDirectory() as work: + directory = Path(work) / "samples" + github_env = Path(work) / "github-env" + started = subprocess.run( + [ + sys.executable, + str(SCRIPT), + "start", + str(directory), + "--interval", + "0.05", + ], + capture_output=True, + text=True, + timeout=30, + env={**os.environ, "GITHUB_ENV": str(github_env)}, + ) + self.assertEqual(started.returncode, 0, started.stdout + started.stderr) + # Later steps find the directory for their marks. + self.assertEqual( + github_env.read_text(), f"{sampler.ENVIRONMENT}={directory.resolve()}\n" + ) + pid = int((directory / sampler.PID).read_text()) + os.kill(pid, 0) + with contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(sampler.main(["report", str(directory)]), 0) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.05) + else: + self.fail(f"sampler {pid} still runs after the report") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test-runner-sizes.py b/.github/scripts/test-runner-sizes.py new file mode 100755 index 0000000000..802ad54f3e --- /dev/null +++ b/.github/scripts/test-runner-sizes.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Every macOS job that runs on Darkbloom names a signed VM size. + +A Darkbloom macOS job without a size gets the size that the repository's +approval pins. Each macOS job here names its own size instead: in its runner +label (`darkbloom-macos-arm64-4x16`), or, for a lane of +`darkbloom-route.yml`, in the lane's size column. This test fails when: + +- a job asks for a Darkbloom Mac without a size, or with a size that the + image pipeline does not sign (4x16, 4x24, 8x16 and 12x32); +- a Linux route lane names a size (the route refuses one); +- a job's size is not the size that SIZES gives it, or SIZES names a job + that no workflow has (so a size changes only on purpose); +- `.github/actionlint.yaml` does not list a used label, or still lists the + label without a size. + +FORKDIFF.md (Job sizes) gives each size and the data behind it. + +Run: python3 .github/scripts/test-runner-sizes.py +""" + +import re +import unittest +from pathlib import Path + +GITHUB = Path(__file__).resolve().parent.parent +WORKFLOWS = GITHUB / "workflows" +ACTIONLINT = GITHUB / "actionlint.yaml" +SIGNED = {"4x16", "4x24", "8x16", "12x32"} +MACOS = "darkbloom-macos-arm64" +# (workflow, job) for a job, (workflow, "lane ") for a route lane: its size. +SIZES = { + ("fork-tests.yml", "build-wheel"): "4x16", + ("fork-tests.yml", "build-cpp"): "4x16", + ("fork-tests.yml", "python-gpu"): "4x24", + ("fork-tests.yml", "python-cpu"): "12x32", + ("fork-tests.yml", "metal-build-and-test"): "4x16", +} + +JOB = re.compile(r"(?m)^ ([A-Za-z0-9_-]+):[ \t]*(?:#.*)?\n") +RUNS_ON = re.compile(r"(?m)^ runs-on:(.*)$") +MACOS_LABELS = re.compile( + r"\[self-hosted, macOS, ARM64, " + MACOS + r"-([0-9]+x[0-9]+)\]" +) +ROUTE = " uses: ./.github/workflows/darkbloom-route.yml" +LANES = re.compile(r"(?m)^ lanes: \|\n((?: .*\n|[ \t]*\n)*)") +EXPRESSION = re.compile(r"\$\{\{.*?\}\}") + + +def jobs(text): + """Return {job id: text} of a workflow's `jobs:` mapping (two-space job keys).""" + text = "\n" + text + if "\njobs:\n" not in text: + return {} + parts = JOB.split(text.split("\njobs:\n", 1)[1]) + return dict(zip(parts[1::2], parts[2::2])) + + +def lane_lines(job): + """Return the fields of each line of a route job's `lanes:` block. + + A `${{ }}` expression counts as one field. + """ + match = LANES.search(job) + if not match: + return [] + return [ + EXPRESSION.sub("EXPRESSION", line).split() + for line in match.group(1).splitlines() + if line.strip() + ] + + +def macos_sizes(workflows): + """Return ({(workflow, job or "lane "): size}, [errors]). + + `workflows` is {workflow file name: text}. + """ + sizes, errors = {}, [] + for workflow, text in sorted(workflows.items()): + for name, job in jobs(text).items(): + where = f"{workflow}: job {name}" + if ROUTE in job: + for fields in lane_lines(job): + lane, profile = fields[0], fields[1] if len(fields) > 1 else "" + size = fields[4] if len(fields) > 4 else None + if profile == "macos_arm64": + if size not in SIGNED: + errors.append(f"{where}: macOS lane {lane}: no signed size") + sizes[(workflow, f"lane {lane}")] = size + elif size is not None: + errors.append(f"{where}: lane {lane} is not macOS: no size") + runs_on = RUNS_ON.findall(job) + if not runs_on: + continue + value = runs_on[0].split(" #", 1)[0].strip() + if len(runs_on) > 1 or not value: + errors.append(f"{where}: write runs-on once, on one line") + continue + if MACOS not in value: + continue + match = MACOS_LABELS.fullmatch(value) + if not match: + errors.append( + f"{where}: runs-on {value} names no size; use [self-hosted, " + f"macOS, ARM64, {MACOS}-], a size of {sorted(SIGNED)}" + ) + continue + if match.group(1) not in SIGNED: + errors.append(f"{where}: size {match.group(1)} is not signed") + sizes[(workflow, name)] = match.group(1) + return sizes, errors + + +def actionlint_labels(): + text = ACTIONLINT.read_text() + return set(re.findall(r"(?m)^ - ([A-Za-z0-9._-]+)\s*$", text)) + + +class RunnerSizes(unittest.TestCase): + def setUp(self): + self.workflows = { + path.name: path.read_text() for path in sorted(WORKFLOWS.glob("*.yml")) + } + + def test_every_macos_job_names_its_signed_size(self): + sizes, errors = macos_sizes(self.workflows) + self.assertEqual(errors, []) + self.assertLessEqual(set(SIZES.values()), SIGNED) + self.assertEqual(sizes, SIZES) + + def test_actionlint_lists_the_sized_labels_only(self): + labels = actionlint_labels() + for size in sorted(set(SIZES.values())): + self.assertIn(f"{MACOS}-{size}", labels) + self.assertNotIn(MACOS, labels) + + def test_an_unsized_or_unsigned_job_fails(self): + # The check must block, not only pass: each of these is refused. + job = "jobs:\n a:\n runs-on: [self-hosted, macOS, ARM64, {}]\n" + bare = job.format(MACOS) + unsigned = job.format(f"{MACOS}-6x12") + block = f"jobs:\n a:\n runs-on:\n - self-hosted\n - {MACOS}\n" + lane = ( + "jobs:\n route:\n" + " uses: ./.github/workflows/darkbloom-route.yml\n" + " with:\n lanes: |\n" + " mac macos_arm64 xcode-27 ${{ inputs.mac && 1 || 0 }}\n" + " lin linux_arm64 ubuntu-24.04 1 4x16\n" + ) + for text in (bare, unsigned, block): + with self.subTest(text=text): + self.assertNotEqual(macos_sizes({"x.yml": text})[1], []) + self.assertEqual(len(macos_sizes({"x.yml": lane})[1]), 2) + sized = job.format(f"{MACOS}-4x16") + self.assertEqual(macos_sizes({"x.yml": sized}), ({("x.yml", "a"): "4x16"}, [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 86dbbab431..9152f611c9 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -45,6 +45,11 @@ jobs: key: pre-commit-3|${{ runner.os }}|${{ runner.arch }}|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }} - name: Run pre-commit run: pre-commit run --show-diff-on-failure --color=always --all-files + - name: Test the runner sizes and the resource sampler + # Fails when a macOS job names no signed VM size (FORKDIFF.md, Job sizes). + run: | + python3 .github/scripts/test-runner-sizes.py + python3 .github/scripts/test-ci-resource-sampler.py linux_sanitizer_build_and_test: name: Linux Sanitizer Tests (${{ matrix.sanitizer }}) diff --git a/.github/workflows/fork-tests.yml b/.github/workflows/fork-tests.yml index 279f94e5cc..1fce1030e5 100644 --- a/.github/workflows/fork-tests.yml +++ b/.github/workflows/fork-tests.yml @@ -49,7 +49,7 @@ env: jobs: build-wheel: - runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64] + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] timeout-minutes: 45 env: # The runners have macOS 26 or later. Version 26.2 is the lowest @@ -58,6 +58,11 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Check the Python shard map run: python3 .github/scripts/fork-tests/python_shards.py check @@ -94,14 +99,24 @@ jobs: retention-days: 3 overwrite: true + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + build-cpp: - runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64] + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] timeout-minutes: 45 env: MACOSX_DEPLOYMENT_TARGET: '26.2' steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - uses: ./.github/actions/fork-build-cache id: cache with: @@ -218,9 +233,14 @@ jobs: retention-days: 3 overwrite: true + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + python-gpu: needs: build-wheel - runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64] + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x24] timeout-minutes: 30 strategy: fail-fast: false @@ -236,6 +256,11 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - uses: ./.github/actions/setup with: toolkit: metal @@ -328,10 +353,15 @@ jobs: retention-days: 3 overwrite: true + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + python-cpu: # Run the CPU code of ops that also have a Metal implementation. needs: build-wheel - runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64] + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-12x32] timeout-minutes: 30 strategy: fail-fast: false @@ -350,6 +380,11 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - uses: ./.github/actions/setup with: toolkit: metal @@ -404,14 +439,24 @@ jobs: retention-days: 3 overwrite: true + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true + metal-build-and-test: needs: [build-wheel, build-cpp, python-gpu, python-cpu] if: ${{ !cancelled() }} - runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64] + runs-on: [self-hosted, macOS, ARM64, darkbloom-macos-arm64-4x16] timeout-minutes: 20 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Start the resource sampler + # Report-only (.github/scripts/ci-resource-sampler.py): every 5 s it + # samples memory and busy vCPUs. It never fails the job. + run: python3 .github/scripts/ci-resource-sampler.py start "$RUNNER_TEMP/resource-samples" + - name: Download the lists of tests that ran uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -582,3 +627,8 @@ jobs: echo "::error::Jobs that did not succeed: $bad" exit 1 fi + + - name: Report the resource samples + # Prints the peaks that size this job (FORKDIFF.md, Job sizes). Report-only. + if: ${{ always() }} + run: python3 .github/scripts/ci-resource-sampler.py report "$RUNNER_TEMP/resource-samples" || true diff --git a/FORKDIFF.md b/FORKDIFF.md index b4fefc827f..4cf57c0adf 100644 --- a/FORKDIFF.md +++ b/FORKDIFF.md @@ -22,7 +22,7 @@ as a run artifact, `forkdiff-page`) and exits with a notice instead of failing. The Linux lint job, ASAN/UBSAN tests, fork-diff check and page renderer use only Darkbloom Linux ARM64 runners. All eight Mac jobs in `fork-tests.yml` use only -Darkbloom macOS ARM64 runners with the approved 12-core, 32-GiB profile. +Darkbloom macOS ARM64 runners. Each names its VM size ([Job sizes](#job-sizes)). They keep their original steps, tests and job timeouts. The sanitizer jobs use the qualified image's compilers and dependencies, with a tool preflight in place of installing packages through sudo, and are capped @@ -47,6 +47,45 @@ fails before it creates a deployment (the packaged artifact is not listed yet), it waits 20 seconds and tries once more. The disabled native CodeQL workflow keeps its separate routing and activation rules. +### Job sizes + +Each Darkbloom macOS job names its VM size in its runner label, for example +`darkbloom-macos-arm64-4x16` (4 vCPUs, 16 GiB). A job without a size gets the +size that the approval pins (12 vCPUs, 32 GiB). The image pipeline signs +4x16, 4x24, 8x16 and 12x32. A job gets the smallest signed size that has 30% +headroom over its measured memory peak. A job that took less than 10 minutes +must stay under 10 minutes. + +The peak of a job is the larger of two sampler figures: used memory (app + +wired + compressed) and the sum of the lifetime peak footprints of the +runner user's processes. The second matters where memory is compressed: +used memory counts compressed pages at their compressed size. The idle VM +uses about 6 GiB. Pull request runs 44750715218 and 44754340762 measured +every job. + +| Job | Size | Wall time on 12 vCPUs (runs 43368507444 to 43569480732) | Hosted 3 vCPUs, 7 GiB | Measured (size: wall time, peak) | +|---|---|---|---|---| +| `build-wheel` | 4x16 | 153 to 354 s | 575 s (run 43120201853, `macos-26`) | 4x16: 230 and 242 s, 10.65 GiB | +| `build-cpp` | 4x16 | 277 to 620 s; p90 about 480 s. The slow runs spend up to 190 s in the build cache action. | 940 s, of which the compile is 632 s (run 43120201853) | 8x16: 302 s, 10.42 GiB; 4x16: 374 s, 10.56 GiB | +| `python-gpu` (2 shards) | 4x24 | 171 to 541 s | 297 to 635 s (run 43531506709, `xcode-27`) | 4x16: 182 to 307 s. Shard 1 used 11.65 GiB with 4.1 GiB compressed; its processes' footprints sum to 13.21 GiB. 16 GiB is less than 1.3 times that. | +| `python-cpu` (3 shards) | 12x32 | 152 to 444 s | 279 to 546 s | 4x16: 190 to 258 s, 13.20 GiB used with 7.1 GiB compressed, memory pressure at warning. 4x24: 163 to 273 s, 19.26 GiB used (footprints 17.89 GiB). 24 GiB is less than 1.3 times 19.26 GiB, and 12x32 is the next signed size with more memory. | +| `metal-build-and-test` | 4x16 | 34 to 190 s | 20 to 23 s | 4x16: 36 and 38 s, 6.07 GiB | + +`test_init_reduce_large_output` needs a 4 GiB Metal buffer on the GPU and a +`memory_size` of 16 GiB on the CPU. The GPU shards (a Metal buffer can have +half of the VM's memory) and the CPU shards give both, so the test still +runs. Runs 44750715218 and 44754340762 ran it on both. + +Every macOS job runs `.github/scripts/ci-resource-sampler.py`, a copy of the +sampler of Layr-Labs/d-inference (wrapped to this repository's ruff rules), from +its checkout on. Its last step, +"Report the resource samples", prints the memory peak of each class, the +three largest processes, the busy vCPUs and the sampled time scaled to 4 and +8 vCPUs. Use these numbers to change a size. Check Lint runs +`.github/scripts/test-runner-sizes.py`. It fails when a macOS job names no +size, a size that is not signed, or a size other than the one its table +gives. + ## The gate A fork-diff page is only useful while it is true, and two things make it go diff --git a/fork.yaml b/fork.yaml index f246122d58..144d59b1cb 100644 --- a/fork.yaml +++ b/fork.yaml @@ -756,8 +756,14 @@ def: its arguments, the metal compiler version and the SDK build. The ccache key holds the clang version, and ccache checks the compiler content of each object. - All eight Mac jobs in `fork-tests.yml` use native macOS ARM64 labels and - the approved 12-core, 32-GiB profile. They wait for compatible capacity + All eight Mac jobs in `fork-tests.yml` use native macOS ARM64 labels. Each + label names the job's VM size: the `python-cpu` shards ask for 12 vCPUs and + 32 GiB (`darkbloom-macos-arm64-12x32`), the `python-gpu` shards for 4 vCPUs and + 24 GiB, and the other jobs for 4 vCPUs and 16 GiB. + `FORKDIFF.md` (Job sizes) gives the data. Each Mac job runs the report-only + `.github/scripts/ci-resource-sampler.py`, which prints its memory and vCPU + peaks, and `.github/scripts/test-runner-sizes.py` (in Check Lint) fails when a + Mac job names no signed size. They wait for compatible capacity without a hosted fallback. The Linux lint, ASAN/UBSAN, fork-diff check and Pages renderer also use native-only labels. The sanitizer jobs use the qualified compiler image and a tool preflight, retaining their @@ -792,7 +798,8 @@ def: #4437, which needs 2^32 output elements (more than one 32-bit grid dimension), and bool outputs of one byte each give 4 GiB. David ruled on 2026-10-23 to keep this skip and not to use a larger runner. A Darkbloom Sandbox caps a Metal buffer at half its memory - (16 GiB of the approved 32 GiB), so the test runs there. When a Python test entry fails, the job prints the end of + (12 GiB of the 24 GiB of the GPU shards), and the CPU shards have a `memory_size` of 32 GiB, + so the test runs there on the GPU and on the CPU. When a Python test entry fails, the job prints the end of its log at once. Upstream tests that run only a GPU path (forced fused SDPA, global-scale `qqmm` and `gather_qmm`) check on the CPU pass that the documented error is raised. globs: @@ -814,6 +821,9 @@ def: - ".github/scripts/codeql_artifacts.py" - ".github/scripts/codeql_artifacts_test.py" - ".github/scripts/update-bypass-list.js" + - ".github/scripts/ci-resource-sampler.py" + - ".github/scripts/test-ci-resource-sampler.py" + - ".github/scripts/test-runner-sizes.py" - "scripts/check_forkdiff.py" - "FORKDIFF.md" - "docs/ci-codeql-native.md"