diff --git a/changelog.d/stage-process-tree-resource-use.added.md b/changelog.d/stage-process-tree-resource-use.added.md new file mode 100644 index 0000000000..ef84bbbab2 --- /dev/null +++ b/changelog.d/stage-process-tree-resource-use.added.md @@ -0,0 +1 @@ +The US release and local-area tools record each telemetry stage's peak memory footprint and CPU time over their whole process tree (the tool, its worker-pool processes, child interpreters and the emitter) on the event that ends the stage, every 60 seconds while it runs, and in both manifests' `stage_resource_use` block. diff --git a/conftest.py b/conftest.py index 43402ce1ab..365e084ed7 100644 --- a/conftest.py +++ b/conftest.py @@ -123,8 +123,17 @@ def start(_cls, **kwargs): run = telemetry_emitter.TelemetryRun( **{name: value for name, value in kwargs.items() if name in fields} ) + stage_resources = None + if kwargs.get("record_stage_resources"): + from microcosm.build.stage_resource_use import StageResourceRecorder + + # The real readings of this process's tree, without the + # background thread: a test drives each stage change itself. + stage_resources = StageResourceRecorder(run_id=run.run_id) emitter = FakeTelemetryEmitter( - run, close_service_on_finish=kwargs.get("close_service_on_finish", True) + run, + close_service_on_finish=kwargs.get("close_service_on_finish", True), + stage_resources=stage_resources, ) emitters.append(emitter) return emitter diff --git a/docs/us-release-build-rule.md b/docs/us-release-build-rule.md index 682f0d12d2..051349090a 100644 --- a/docs/us-release-build-rule.md +++ b/docs/us-release-build-rule.md @@ -224,6 +224,31 @@ A US national build and its certification are two steps (microcosm#1585 item certification. - **Timing.** Both manifests' `timing` blocks carry `build_seconds` and `certify_seconds`; `total_build_seconds` is their sum. +- **Each stage's memory and CPU time.** The build run and certification each + record, for every telemetry stage, the memory footprint of the tool's + process and all its descendants (worker-pool processes, child interpreters + and the emitter), read every 0.5 seconds: the largest total + (`tree_peak_footprint_bytes`), the tool's own process's largest + (`main_process_peak_footprint_bytes`) and the largest any one descendant + reached (`largest_child_peak_footprint_bytes`). They also record the tree's + CPU time during the stage (`tree_cpu_user_seconds`, + `tree_cpu_system_seconds`), the number of footprint readings + (`footprint_readings`) and the stage's elapsed time (`wall_seconds`). The + event that ends each stage carries these figures, and a running stage sends + them so far every 60 seconds. The tool ends each stage itself to attach + them, so the emitter records every stage end's `stage_span.closed_by` as + null (the build ended the stage) rather than naming what ended it. The build + record keeps the build run's stages, + and both manifests' `stage_resource_use` block lists the build run's stages + and then certification's. The build run's last stage (`write_calibration_npz`, + open while the record is written) and certification's `manifests` stage end + after what they write, so their figures are in telemetry only. The + local-area tool (`tools/build_us_acs_local_release.py`) records its stages + the same way, keeps them in its checkpoint's `stage_resource_use.json`, and + `package` writes them to both manifests. They are run metadata, like + `timing`: no data output and no digest of one changes with them. + `microcosm.build.stage_resource_use` says how each figure is read on macOS + and Linux. - **Drivers.** Route A (`tools/route_a/route_a.sh`) stops after the build with `ROUTE_A_BUILT.json`; `route_a.sh --certify` on the same `RUN_ROOT` certifies that build at the tier `ROUTE_A_CERTIFY_TIER` chooses (`certified` or diff --git a/packages/microcosm-build/src/microcosm/build/program_telemetry.py b/packages/microcosm-build/src/microcosm/build/program_telemetry.py index 563e3163a9..5cacbf351e 100644 --- a/packages/microcosm-build/src/microcosm/build/program_telemetry.py +++ b/packages/microcosm-build/src/microcosm/build/program_telemetry.py @@ -122,11 +122,15 @@ def program_telemetry( country_code: str = "US", run_kind: str = "build", environ: Mapping[str, str] | None = None, + record_stage_resources: bool = False, ) -> Iterator[LocalTelemetryEmitter]: """Start this program's emitter, and record its outcome on the way out. Yields the adapter, unavailable when the emitter could not be used and - telemetry is not required; every call on it is then a no-op. + telemetry is not required; every call on it is then a no-op. With + ``record_stage_resources`` the adapter records each stage's memory + footprint and CPU time (:mod:`microcosm.build.stage_resource_use`), also + without an emitter. ``TelemetryRequiredError`` from the adapter, and ``ValueError`` for a run ID the collector would refuse, propagate before the body runs. A SIGTERM in the body ends it with ``SystemExit(143)`` after the @@ -140,6 +144,7 @@ def program_telemetry( pipeline=pipeline, candidate_id=candidate_id, run_kind=run_kind, + record_stage_resources=record_stage_resources, ) try: with raise_on_sigterm(): diff --git a/packages/microcosm-build/src/microcosm/build/stage_resource_use.py b/packages/microcosm-build/src/microcosm/build/stage_resource_use.py new file mode 100644 index 0000000000..84872780d9 --- /dev/null +++ b/packages/microcosm-build/src/microcosm/build/stage_resource_use.py @@ -0,0 +1,683 @@ +"""Each telemetry stage's memory footprint and CPU time over the build's process tree. + +The release and local-area tools record, for every stage of their telemetry +run, how much memory and CPU time the build process and every process +descended from it used. The telemetry adapter +(:class:`microcosm.build.telemetry_emitter.LocalTelemetryEmitter`) sends the +figures as flat details on the event that ends the stage, and on a +``progress`` event for the stage every :data:`REPORT_INTERVAL_SECONDS` while it +runs; the tools write the finished stages' figures to their manifests. The +figures, named the same everywhere: + +- ``tree_peak_footprint_bytes``: the largest total, at any one reading, of the + footprint of the build process and all its descendants; +- ``main_process_peak_footprint_bytes``: the build process's own largest + footprint; +- ``largest_child_peak_footprint_bytes``: the largest footprint any single + descendant reached, ``None`` when no descendant was read; +- ``tree_cpu_user_seconds`` and ``tree_cpu_system_seconds``: the tree's CPU + time at the stage's end (or now, for a report) minus at its start, never + below 0; +- ``footprint_readings``: how many readings the three peaks come from; the + peaks are ``None`` when there were none; +- ``wall_seconds``: the stage's elapsed time. + +A process's footprint is the memory it holds whether or not it is in RAM, the +reading the worker pool's memory caps take +(:func:`microcosm.build.worker_pool.process_memory_bytes`): ``phys_footprint`` +on macOS, which counts compressed pages, and ``VmRSS + VmSwap`` on Linux. The +tree is read at each stage's start and end and every +:data:`READING_INTERVAL_SECONDS` between them, by a background thread; a spike +shorter than the interval can fall between two readings. + +The tree's CPU total is this process's own (``getrusage(RUSAGE_SELF)``, every +thread), plus the children it has waited for, with the descendants they +waited for (``getrusage(RUSAGE_CHILDREN)``), plus the CPU time so far of each +descendant still running: on Linux its ``utime`` and ``stime`` and the +``cutime`` and ``cstime`` of the children it waited for +(``/proc//stat``); on macOS its own ``ri_user_time`` and +``ri_system_time`` (``proc_pid_rusage``, in Mach time units). macOS reports no +running process's waited-for children, so the CPU time of a grandchild that +exits while its parent still runs is counted only once that parent exits and +is waited for, in the stage in which that happens. A process waited for +while a total is read, after ``RUSAGE_CHILDREN`` and before its own reading, +is missing from that total: missing from a stage's start total, all its CPU +time counts in that stage; missing from its end total, its time in the stage +counts in the next. + +The descendants include the telemetry emitter, which the build starts as its +child, and the processes of every worker pool. The module needs a Unix +system (it reads ``resource``). Footprints and running descendants are read +on macOS and Linux; on another Unix system no footprint is read and the CPU +total is this process's and its waited-for children's only. +""" + +from __future__ import annotations + +import ctypes +import os +import resource +import sys +import threading +import time +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Final + +from microcosm.build.worker_pool import process_memory_bytes + +__all__ = [ + "FIGURE_NAMES", + "MEMORY_MEASURE", + "READING_INTERVAL_SECONDS", + "REPORT_INTERVAL_SECONDS", + "StageResourceRecorder", + "TreeFootprints", + "descendant_pids", + "linux_descendant_pids", + "linux_process_cpu_seconds", + "process_cpu_seconds", + "read_tree_footprints", + "stage_resource_use_block", + "tree_cpu_seconds", +] + +#: Seconds between two readings of the tree's footprint: the worker pool's +#: memory-cap interval. +READING_INTERVAL_SECONDS: Final = 0.5 +#: Seconds between two ``progress`` events for a stage that is still running. +REPORT_INTERVAL_SECONDS: Final = 60.0 +#: The memory each process's figure counts, as the manifests name it. +MEMORY_MEASURE: Final = "footprint" +#: The figures of one stage, in the order they are sent. +FIGURE_NAMES: Final = ( + "tree_peak_footprint_bytes", + "main_process_peak_footprint_bytes", + "largest_child_peak_footprint_bytes", + "tree_cpu_user_seconds", + "tree_cpu_system_seconds", + "footprint_readings", + "wall_seconds", +) +_SECONDS_DIGITS: Final = 3 +_PROC: Final = Path("/proc") + + +# --------------------------------------------------------------------------- +# Reading the process tree +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class TreeFootprints: + """One reading: the main process's footprint and each descendant's. + + ``main_process_bytes`` is ``None`` when the main process's footprint could + not be read; ``child_bytes`` holds the footprints that could. + """ + + main_process_bytes: int | None + child_bytes: tuple[int, ...] + + @property + def readable(self) -> bool: + """Whether anything was read.""" + return self.main_process_bytes is not None or bool(self.child_bytes) + + @property + def tree_bytes(self) -> int: + """The footprints read, added up.""" + return (self.main_process_bytes or 0) + sum(self.child_bytes) + + @property + def largest_child_bytes(self) -> int | None: + """The largest descendant's footprint, ``None`` with none read.""" + return max(self.child_bytes) if self.child_bytes else None + + +def linux_descendant_pids(pid: int, *, proc_root: Path = _PROC) -> list[int]: + """Every descendant of ``pid`` on Linux, children before their children. + + Each thread's ``/proc//task//children`` lists the children it + started. A kernel built without those files leaves the parent of every + process in its ``stat`` instead, so then every process's ``stat`` is read. + """ + if _linux_children_from_files(pid, proc_root) is None: + parents = _linux_parents(proc_root) + return _descendants(pid, lambda parent: parents.get(parent, ())) + return _descendants( + pid, lambda parent: _linux_children_from_files(parent, proc_root) or () + ) + + +def _linux_children_from_files(pid: int, proc_root: Path) -> list[int] | None: + """``pid``'s children from its threads' ``children`` files. + + ``None`` when ``pid`` runs but none of its threads has the file; an empty + list when it has exited. + """ + task = proc_root / str(pid) / "task" + try: + threads = os.listdir(task) + except OSError: + return [] + children: list[int] = [] + found = False + for thread in threads: + try: + text = (task / thread / "children").read_text(encoding="ascii") + except OSError: + continue + found = True + children.extend(int(word) for word in text.split()) + return children if found else None + + +def _linux_stat_fields(pid: int, proc_root: Path) -> list[str] | None: + """The fields of ``/proc//stat`` after the command name, or ``None``. + + The command name is in parentheses and may itself hold spaces and + parentheses, so the fields start after the last ``)``: the state, then + the parent's ID. + """ + try: + text = (proc_root / str(pid) / "stat").read_text( + encoding="ascii", errors="replace" + ) + except OSError: + return None + _, separator, rest = text.rpartition(")") + return rest.split() if separator else None + + +def _linux_parents(proc_root: Path) -> dict[int, list[int]]: + """Every process's children, from the parent each ``stat`` names.""" + children: dict[int, list[int]] = {} + try: + names = os.listdir(proc_root) + except OSError: + return children + for name in names: + if not name.isdigit(): + continue + fields = _linux_stat_fields(int(name), proc_root) + if fields is None or len(fields) < 2: + continue + children.setdefault(int(fields[1]), []).append(int(name)) + return children + + +def linux_process_cpu_seconds( + pid: int, + *, + proc_root: Path = _PROC, + ticks_per_second: int | None = None, +) -> tuple[float, float] | None: + """A Linux process's user and system CPU seconds, with its waited-for children. + + ``utime + cutime`` and ``stime + cstime`` from ``/proc//stat``, in + clock ticks; ``None`` once the process has gone. + """ + fields = _linux_stat_fields(pid, proc_root) + if fields is None or len(fields) < 15: + return None + ticks = ticks_per_second or os.sysconf("SC_CLK_TCK") + utime, stime, cutime, cstime = (int(value) for value in fields[11:15]) + return (utime + cutime) / ticks, (stime + cstime) / ticks + + +class _RusageInfoV0(ctypes.Structure): + # struct rusage_info_v0, on macOS. + _fields_ = [ + ("ri_uuid", ctypes.c_uint8 * 16), + ("ri_user_time", ctypes.c_uint64), + ("ri_system_time", ctypes.c_uint64), + ("ri_pkg_idle_wkups", ctypes.c_uint64), + ("ri_interrupt_wkups", ctypes.c_uint64), + ("ri_pageins", ctypes.c_uint64), + ("ri_wired_size", ctypes.c_uint64), + ("ri_resident_size", ctypes.c_uint64), + ("ri_phys_footprint", ctypes.c_uint64), + ("ri_proc_start_abstime", ctypes.c_uint64), + ("ri_proc_exit_abstime", ctypes.c_uint64), + ] + + +class _TimebaseInfo(ctypes.Structure): + # struct mach_timebase_info, . + _fields_ = [("numer", ctypes.c_uint32), ("denom", ctypes.c_uint32)] + + +_RUSAGE_INFO_V0: Final = 0 +#: The most child IDs one ``proc_listchildpids`` call is given room for. +_MAXIMUM_CHILDREN: Final = 1 << 16 + + +@dataclass(frozen=True) +class _Darwin: + """``libproc`` and the seconds in one Mach time unit, loaded once.""" + + libproc: ctypes.CDLL + seconds_per_unit: float + + +_DARWIN: _Darwin | None = None +_DARWIN_LOCK = threading.Lock() + + +def _darwin() -> _Darwin: + global _DARWIN + with _DARWIN_LOCK: + if _DARWIN is None: + libproc = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True) + libproc.proc_listchildpids.argtypes = [ + ctypes.c_int, + ctypes.c_void_p, + ctypes.c_int, + ] + libproc.proc_listchildpids.restype = ctypes.c_int + libproc.proc_pid_rusage.argtypes = [ + ctypes.c_int, + ctypes.c_int, + ctypes.POINTER(_RusageInfoV0), + ] + libproc.proc_pid_rusage.restype = ctypes.c_int + system = ctypes.CDLL("/usr/lib/libSystem.B.dylib") + timebase = _TimebaseInfo() + system.mach_timebase_info(ctypes.byref(timebase)) + _DARWIN = _Darwin(libproc, timebase.numer / timebase.denom / 1e9) + return _DARWIN + + +def _darwin_child_pids(pid: int) -> list[int]: + """``pid``'s children on macOS (``proc_listchildpids``, which returns a count).""" + darwin = _darwin() + capacity = 256 + while True: + buffer = (ctypes.c_int * capacity)() + count = darwin.libproc.proc_listchildpids(pid, buffer, ctypes.sizeof(buffer)) + if count < 0: + return [] + if count < capacity or capacity >= _MAXIMUM_CHILDREN: + listed = min(count, capacity) + return [buffer[index] for index in range(listed) if buffer[index] > 0] + capacity *= 2 + + +def _darwin_process_cpu_seconds(pid: int) -> tuple[float, float] | None: + """A macOS process's own user and system CPU seconds (``proc_pid_rusage``).""" + darwin = _darwin() + info = _RusageInfoV0() + if darwin.libproc.proc_pid_rusage(pid, _RUSAGE_INFO_V0, ctypes.byref(info)) != 0: + return None + return ( + info.ri_user_time * darwin.seconds_per_unit, + info.ri_system_time * darwin.seconds_per_unit, + ) + + +def _descendants(pid: int, children_of: Callable[[int], Iterable[int]]) -> list[int]: + """``pid``'s descendants, breadth first; each process ID once.""" + found: list[int] = [] + seen = {pid} + waiting = [pid] + while waiting: + parent = waiting.pop(0) + for child in children_of(parent): + if child not in seen: + seen.add(child) + found.append(child) + waiting.append(child) + return found + + +def descendant_pids(pid: int) -> list[int]: + """Every process descended from ``pid`` on this machine, on macOS and Linux.""" + if sys.platform == "darwin": + return _descendants(pid, _darwin_child_pids) + if sys.platform.startswith("linux"): + return linux_descendant_pids(pid) + return [] + + +def process_cpu_seconds(pid: int) -> tuple[float, float] | None: + """A running process's user and system CPU seconds, ``None`` once it has gone. + + On Linux they include the children it waited for; macOS doesn't report + those. + """ + if sys.platform == "darwin": + return _darwin_process_cpu_seconds(pid) + if sys.platform.startswith("linux"): + return linux_process_cpu_seconds(pid) + return None + + +def read_tree_footprints( + pid: int | None = None, + *, + descendants_of: Callable[[int], Sequence[int]] = descendant_pids, + memory_of: Callable[[int], int | None] = process_memory_bytes, +) -> TreeFootprints: + """The footprint of ``pid`` (this process by default) and its descendants.""" + main = os.getpid() if pid is None else pid + children = tuple( + footprint + for footprint in (memory_of(child) for child in descendants_of(main)) + if footprint is not None + ) + return TreeFootprints(main_process_bytes=memory_of(main), child_bytes=children) + + +def tree_cpu_seconds() -> tuple[float, float]: + """This process tree's user and system CPU seconds so far. + + This process's own, plus the children it waited for with theirs, plus + each running descendant's (see the module's description). + """ + own = resource.getrusage(resource.RUSAGE_SELF) + waited = resource.getrusage(resource.RUSAGE_CHILDREN) + user = own.ru_utime + waited.ru_utime + system = own.ru_stime + waited.ru_stime + for descendant in descendant_pids(os.getpid()): + running = process_cpu_seconds(descendant) + if running is not None: + user += running[0] + system += running[1] + return user, system + + +# --------------------------------------------------------------------------- +# Recording each stage +# --------------------------------------------------------------------------- + + +@dataclass +class _OpenStage: + stage_id: str + serial: int + started_at: float + cpu_at_start: tuple[float, float] + next_report_at: float + tree_peak: int | None = None + main_process_peak: int | None = None + largest_child_peak: int | None = None + readings: int = 0 + + def add(self, reading: TreeFootprints) -> None: + if not reading.readable: + return + self.readings += 1 + self.tree_peak = _larger(self.tree_peak, reading.tree_bytes) + self.main_process_peak = _larger( + self.main_process_peak, reading.main_process_bytes + ) + self.largest_child_peak = _larger( + self.largest_child_peak, reading.largest_child_bytes + ) + + def figures(self, cpu: tuple[float, float], now: float) -> dict[str, Any]: + return { + "tree_peak_footprint_bytes": self.tree_peak, + "main_process_peak_footprint_bytes": self.main_process_peak, + "largest_child_peak_footprint_bytes": self.largest_child_peak, + "tree_cpu_user_seconds": _seconds(cpu[0] - self.cpu_at_start[0]), + "tree_cpu_system_seconds": _seconds(cpu[1] - self.cpu_at_start[1]), + "footprint_readings": self.readings, + "wall_seconds": _seconds(now - self.started_at), + } + + +def _larger(current: int | None, reading: int | None) -> int | None: + if reading is None: + return current + return reading if current is None else max(current, reading) + + +def _seconds(value: float) -> float: + return round(max(0.0, value), _SECONDS_DIGITS) + + +class StageResourceRecorder: + """One telemetry run's stages: their peaks, CPU time and elapsed time. + + The telemetry adapter starts and ends each stage as the run's stages + change; one stage is open at a time. :meth:`start_background_readings` + starts a thread that reads the tree every ``reading_interval_seconds`` + and, every ``report_interval_seconds`` after a stage started, hands its + figures so far to ``report``. Each ended stage becomes an entry of + :meth:`completed_stages`, ``{"run_id", "stage_id", "status"}`` and the + figures, and is handed to each stage-end listener. + + A stage's serial number tells one opening of a stage from another, so a + report read for a stage that has since ended is recognised. + ``read_footprints``, ``read_cpu`` and ``clock`` are the machine's readers + and ``time.perf_counter`` unless a test gives its own. + """ + + def __init__( + self, + *, + run_id: str, + read_footprints: Callable[[], TreeFootprints] = read_tree_footprints, + read_cpu: Callable[[], tuple[float, float]] = tree_cpu_seconds, + clock: Callable[[], float] = time.perf_counter, + reading_interval_seconds: float = READING_INTERVAL_SECONDS, + report_interval_seconds: float = REPORT_INTERVAL_SECONDS, + ) -> None: + self.run_id = run_id + self._read_footprints = read_footprints + self._read_cpu = read_cpu + self._clock = clock + self._reading_interval = reading_interval_seconds + self._report_interval = report_interval_seconds + self._lock = threading.Lock() + self._stage: _OpenStage | None = None + self._serial = 0 + self._completed: list[dict[str, Any]] = [] + self._listeners: list[Callable[[dict[str, Any]], None]] = [] + self._finished = False + self._stop = threading.Event() + self._thread: threading.Thread | None = None + self._report: Callable[[str, int, dict[str, Any]], None] | None = None + self._warned = False + + # -- the open stage ---------------------------------------------------- + + @property + def current_stage(self) -> str | None: + """The open stage's ID, or ``None``.""" + with self._lock: + return None if self._stage is None else self._stage.stage_id + + @property + def current_serial(self) -> int | None: + """The open stage's serial number, or ``None``.""" + with self._lock: + return None if self._stage is None else self._stage.serial + + def is_current(self, serial: int | None) -> bool: + """Whether the stage with serial number ``serial`` is still open.""" + with self._lock: + return self._stage is not None and self._stage.serial == serial + + def start_stage(self, stage_id: str) -> None: + """Open ``stage_id``, reading the tree's footprint and CPU total. + + The caller ends the open stage first. Once recording has finished, + no stage opens. + """ + if self._finished: + return + cpu = self._read_cpu() + reading = self._read_footprints() + now = self._clock() + with self._lock: + self._serial += 1 + stage = _OpenStage( + stage_id=stage_id, + serial=self._serial, + started_at=now, + cpu_at_start=cpu, + next_report_at=now + self._report_interval, + ) + stage.add(reading) + self._stage = stage + + def end_stage(self, status: str) -> dict[str, Any] | None: + """End the open stage with ``status``: its figures, or ``None`` with none open. + + The stage's entry is added to :meth:`completed_stages` and handed to + each stage-end listener. + """ + with self._lock: + stage = self._stage + if stage is None: + return None + reading = self._read_footprints() + cpu = self._read_cpu() + now = self._clock() + with self._lock: + if self._stage is not stage: + return None + stage.add(reading) + figures = stage.figures(cpu, now) + entry = { + "run_id": self.run_id, + "stage_id": stage.stage_id, + "status": status, + **figures, + } + self._completed.append(entry) + self._stage = None + listeners = list(self._listeners) + for listener in listeners: + try: + listener(dict(entry)) + except Exception as error: # bookkeeping must never stop the build + print( + f"warning: the entry of stage {stage.stage_id!r} could not be " + f"kept ({type(error).__name__}: {error}); the build goes on.", + file=sys.stderr, + ) + return figures + + def figures_so_far(self, serial: int | None) -> dict[str, Any] | None: + """The figures of the stage with ``serial`` up to now, if still open.""" + cpu = self._read_cpu() + now = self._clock() + with self._lock: + stage = self._stage + if stage is None or stage.serial != serial: + return None + return stage.figures(cpu, now) + + def take_reading(self) -> None: + """Read the tree's footprint into the open stage's peaks.""" + with self._lock: + stage = self._stage + if stage is None: + return + reading = self._read_footprints() + with self._lock: + if self._stage is stage: + stage.add(reading) + + def due_report(self) -> tuple[str, int] | None: + """The open stage's ID and serial number when a report is due. + + A report is due every ``report_interval_seconds`` after the stage + started; asking takes the report, so the next is due an interval + later. + """ + now = self._clock() + with self._lock: + stage = self._stage + if stage is None or now < stage.next_report_at: + return None + while stage.next_report_at <= now: + stage.next_report_at += self._report_interval + return stage.stage_id, stage.serial + + # -- finished stages --------------------------------------------------- + + def completed_stages(self) -> list[dict[str, Any]]: + """Each ended stage's entry, in the order the stages ended.""" + with self._lock: + return [dict(entry) for entry in self._completed] + + def add_stage_end_listener( + self, listener: Callable[[dict[str, Any]], None] + ) -> None: + """Hand ``listener`` each stage's entry as the stage ends.""" + with self._lock: + self._listeners.append(listener) + + def finish(self) -> None: + """Open no stage from now on: the run has ended.""" + self._finished = True + + # -- the background thread -------------------------------------------- + + @property + def reading_thread_alive(self) -> bool: + """Whether the background thread runs.""" + return self._thread is not None and self._thread.is_alive() + + def start_background_readings( + self, *, report: Callable[[str, int, dict[str, Any]], None] | None = None + ) -> None: + """Start the thread that reads the tree and hands ``report`` each report. + + ``report`` receives the stage's ID, its serial number and its figures + so far. An exception from a reading or from ``report`` is printed once + and the thread goes on. + """ + if self._thread is not None: + return + self._report = report + self._thread = threading.Thread( + target=self._run, name="stage-resource-use", daemon=True + ) + self._thread.start() + + def stop(self, timeout: float = 5.0) -> None: + """Finish recording and stop the background thread.""" + self.finish() + self._stop.set() + thread = self._thread + if thread is not None and thread is not threading.current_thread(): + thread.join(timeout) + + def _run(self) -> None: + while not self._stop.wait(self._reading_interval): + try: + self._read_and_report() + except Exception as error: # a reading must never stop the build + if not self._warned: + self._warned = True + print( + "warning: a stage's memory and CPU reading failed " + f"({type(error).__name__}: {error}); the build goes on.", + file=sys.stderr, + ) + + def _read_and_report(self) -> None: + self.take_reading() + due = self.due_report() + if due is None or self._report is None: + return + stage_id, serial = due + figures = self.figures_so_far(serial) + if figures is not None: + self._report(stage_id, serial, figures) + + +def stage_resource_use_block(entries: Iterable[Mapping[str, Any]]) -> dict[str, Any]: + """The manifests' ``stage_resource_use`` block for ``entries``.""" + return { + "memory_measure": MEMORY_MEASURE, + "reading_interval_seconds": READING_INTERVAL_SECONDS, + "stages": [dict(entry) for entry in entries], + } diff --git a/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py b/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py index 6a788414b1..cf1a7704d1 100644 --- a/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py +++ b/packages/microcosm-build/src/microcosm/build/telemetry_emitter.py @@ -40,6 +40,19 @@ (which runs ``microcosm-emitter version``), because the emitter's telemetry module records the run's start as soon as the emitter starts, before its ``hello`` answer can name its release. + +A build that asks for it (``record_stage_resources``) has the adapter record +each stage's memory footprint and CPU time over the build's process tree +(:mod:`microcosm.build.stage_resource_use`). The adapter then ends every stage +itself before the next one starts, or before the run's outcome, so that the +event ending the stage carries the stage's figures; the emitter would +otherwise end it without them. The emitter then records every such end's +``stage_span.closed_by`` as null, its value for a stage the build ended, +where it would have named what ended the stage (``next_stage_started``, +``run_completed``, ``run_failed`` and so on). A failing stage's end carries the +failure's text and details, as the emitter's own end of it would. The figures +are recorded whether or not an emitter runs, so the build's manifests have +them either way. """ from __future__ import annotations @@ -48,7 +61,8 @@ import os import re import sys -from collections.abc import Mapping, Sequence +import threading +from collections.abc import Callable, Mapping, Sequence from importlib import resources as importlib_resources from pathlib import Path from typing import Any, Literal, Protocol @@ -81,6 +95,7 @@ ) from microcosm.build.collector_submissions import CollectorReceipts +from microcosm.build.stage_resource_use import StageResourceRecorder from microcosm.build.telemetry_identity import runtime_identity __all__ = [ @@ -649,6 +664,12 @@ class LocalTelemetryEmitter: Recording the run's outcome (``complete``, ``fail`` or ``block``) shuts the emitter down unless ``close_service_on_finish`` is false; a build that still hands work over afterwards passes false and calls ``close``. + + ``stage_resources``, when given, records each stage's memory footprint and + CPU time (see the module's description): every stage change, calibration's + first epoch and the run's outcome end the open stage with its figures. The + adapter sends one request at a time, so a stage's report from the + recorder's thread never reaches the emitter after the stage has ended. """ def __init__( @@ -657,11 +678,14 @@ def __init__( run: TelemetryRun, client: EmitterClient | None, close_service_on_finish: bool = True, + stage_resources: StageResourceRecorder | None = None, ) -> None: self.run = run self.client = client + self.stage_resources = stage_resources self._close_service_on_finish = close_service_on_finish self._closed = False + self._requests = threading.RLock() @classmethod def start( @@ -678,6 +702,7 @@ def start( startup_timeout_seconds: float = STARTUP_TIMEOUT_SECONDS, spool_path: Path | str | None = None, close_service_on_finish: bool = True, + record_stage_resources: bool = False, ) -> LocalTelemetryEmitter: """Start the installed emitter; a failure leaves an unavailable adapter. @@ -693,6 +718,10 @@ def start( is refused too. Whether the emitter later authenticates to the collector is not visible here: the interface has no call that reports it. Any value other than ``1``, ``0`` or unset raises ``ValueError``. + + With ``record_stage_resources`` the adapter records each stage's + memory footprint and CPU time, and its recorder's thread starts, also + when the emitter could not be used. """ required = _telemetry_required() run = TelemetryRun( @@ -719,7 +748,7 @@ def start( print(SETUP_WARNING.format(error_type=setup_error), file=sys.stderr) return cls( run=run, client=None, close_service_on_finish=close_service_on_finish - ) + )._recording_stage_resources(record_stage_resources) client = _start_emitter( required=required, telemetry=TelemetrySettings( @@ -734,7 +763,16 @@ def start( ) return cls( run=run, client=client, close_service_on_finish=close_service_on_finish - ) + )._recording_stage_resources(record_stage_resources) + + def _recording_stage_resources(self, record: bool) -> LocalTelemetryEmitter: + """Give this adapter a recorder whose thread runs, when ``record``.""" + if record: + self.stage_resources = StageResourceRecorder(run_id=self.run.run_id) + self.stage_resources.start_background_readings( + report=self._report_stage_progress + ) + return self @property def available(self) -> bool: @@ -753,14 +791,15 @@ def emit( message: str | None = None, details: Mapping[str, Any] | None = None, ) -> None: - if (telemetry := self._telemetry()) is not None: - telemetry.emit( - event_type=event_type, - status=status, - stage_id=stage_id, - message=message, - details=details, - ) + with self._requests: + if (telemetry := self._telemetry()) is not None: + telemetry.emit( + event_type=event_type, + status=status, + stage_id=stage_id, + message=message, + details=details, + ) def stage( self, @@ -770,8 +809,9 @@ def stage( message: str | None = None, **details: Any, ) -> None: - if (telemetry := self._telemetry()) is not None: - telemetry.stage(stage_id, status=status, message=message, **details) + with self._requests: + if (telemetry := self._telemetry()) is not None: + telemetry.stage(stage_id, status=status, message=message, **details) def transition_stage( self, @@ -781,10 +821,34 @@ def transition_stage( message: str | None = None, **details: Any, ) -> None: - if (telemetry := self._telemetry()) is not None: - telemetry.transition_stage( - stage_id, status=status, message=message, **details - ) + """Change or end the run's current stage, as the emitter's rules say. + + ``running`` or ``started`` makes ``stage_id`` current; ``completed``, + ``passed`` or ``failed`` ends it when it is current; any other status + is progress. Recording stage resources, the adapter first ends a + current stage other than ``stage_id`` itself, with its figures, as the + emitter would end it, and attaches the figures to the build's own end + of the current stage. + """ + with self._requests: + recorder = self.stage_resources + if recorder is not None: + current = recorder.current_stage + if current is not None and current != stage_id: + self._end_recorded_stage("completed") + elif current == stage_id and status in _STAGE_END_STATUSES: + figures = self._recorded_stage_end(_STAGE_END_STATUSES[status]) + details = {**figures, **details} + if (telemetry := self._telemetry()) is not None: + telemetry.transition_stage( + stage_id, status=status, message=message, **details + ) + if ( + recorder is not None + and status in _STAGE_START_STATUSES + and recorder.current_stage != stage_id + ): + self._record(lambda: recorder.start_stage(stage_id)) def progress( self, @@ -801,18 +865,36 @@ def progress( ``outer`` is the counter one level above, such as the reform pass a scoring batch belongs to; the emitter sends it only when given. """ - if (telemetry := self._telemetry()) is not None: - telemetry.progress( - stage_id, done=done, total=total, unit=unit, outer=outer, **details - ) + with self._requests: + if (telemetry := self._telemetry()) is not None: + telemetry.progress( + stage_id, done=done, total=total, unit=unit, outer=outer, **details + ) def calibration_progress(self, event: Mapping[str, Any]) -> None: - if (telemetry := self._telemetry()) is not None: - telemetry.calibration_progress(event) + with self._requests: + if (telemetry := self._telemetry()) is not None: + telemetry.calibration_progress(event) def transition_calibration_progress(self, event: Mapping[str, Any]) -> None: - if (telemetry := self._telemetry()) is not None: - telemetry.transition_calibration_progress(event) + """Send a calibration epoch, the first of which makes calibrating current. + + Recording stage resources, the stage current before the first epoch + ends with its figures and ``calibrating`` opens. + """ + with self._requests: + recorder = self.stage_resources + opens = ( + recorder is not None + and event.get("kind") == _CALIBRATION_EPOCH_KIND + and recorder.current_stage != _CALIBRATING_STAGE + ) + if opens: + self._end_recorded_stage("completed") + if (telemetry := self._telemetry()) is not None: + telemetry.transition_calibration_progress(event) + if opens: + self._record(lambda: recorder.start_stage(_CALIBRATING_STAGE)) def fail( self, @@ -823,13 +905,40 @@ def fail( error_code: str | None = None, ) -> None: try: - if (telemetry := self._telemetry()) is not None: - telemetry.fail( - error, - failed_during=failed_during, - failure_class=failure_class, - error_code=error_code, + with self._requests: + # The failure's text and details, which the emitter attaches + # to the stage it ends when the run fails. + current = ( + None + if self.stage_resources is None + else self.stage_resources.current_stage ) + try: + self._end_recorded_stage( + "failed", + message=_error_text(error), + details={ + "error_type": type(error).__name__, + "failure_class": failure_class, + "failed_during": failed_during or current, + **( + {"error_code": error_code} + if error_code is not None + else {} + ), + }, + ) + finally: + # An interrupt while the stage ends must not cost the run + # its failure; the emitter then names the failing stage + # itself, whether or not the stage's end went out. + if (telemetry := self._telemetry()) is not None: + telemetry.fail( + error, + failed_during=failed_during, + failure_class=failure_class, + error_code=error_code, + ) finally: self._finish() @@ -843,29 +952,108 @@ def block( ) -> None: """Record that the build's validation checks refused its candidate.""" try: - if (telemetry := self._telemetry()) is not None: - telemetry.refuse( - phase=phase, - refusing_check_ids=list(blocking_gate_ids), - refusing_check_count=blocking_failure_count, - check_statuses=gate_statuses, - ) + with self._requests: + # The emitter ends the stage of a refused run as completed. + self._end_recorded_stage("completed") + if (telemetry := self._telemetry()) is not None: + telemetry.refuse( + phase=phase, + refusing_check_ids=list(blocking_gate_ids), + refusing_check_count=blocking_failure_count, + check_statuses=gate_statuses, + ) finally: self._finish() def complete(self) -> None: try: - if (telemetry := self._telemetry()) is not None: - telemetry.complete() + with self._requests: + self._end_recorded_stage("completed") + if (telemetry := self._telemetry()) is not None: + telemetry.complete() finally: self._finish() + def completed_stage_resource_use(self) -> list[dict[str, Any]]: + """Each ended stage's memory and CPU entry; none unless recording.""" + if self.stage_resources is None: + return [] + return self.stage_resources.completed_stages() + + def _record(self, action: Callable[[], Any]) -> Any: + """Run a recorder ``action``; an error in it warns and never stops the build.""" + try: + return action() + except Exception as error: + print( + "warning: a stage's memory and CPU use could not be recorded " + f"({type(error).__name__}: {error}); the build goes on.", + file=sys.stderr, + ) + return None + + def _recorded_stage_end(self, status: str) -> dict[str, Any]: + """End the recorder's open stage: its figures, or none.""" + recorder = self.stage_resources + if recorder is None: + return {} + return self._record(lambda: recorder.end_stage(status)) or {} + + def _end_recorded_stage( + self, + status: str, + *, + message: str | None = None, + details: Mapping[str, Any] | None = None, + ) -> None: + """End the open stage with ``status``, sending its figures and ``details``. + + The caller holds the request lock. Nothing is sent without a + recorder or an open stage. + """ + recorder = self.stage_resources + stage_id = None if recorder is None else recorder.current_stage + if stage_id is None: + return + figures = self._recorded_stage_end(status) + if (telemetry := self._telemetry()) is not None: + telemetry.transition_stage( + stage_id, status=status, message=message, **figures, **(details or {}) + ) + + def _report_stage_progress( + self, stage_id: str, serial: int, figures: Mapping[str, Any] + ) -> None: + """Send a running stage's figures so far, if it is still the open stage. + + The recorder's thread calls this; under the request lock, a stage that + ended while the figures were read is never reported, since a report + for a stage that is not current would end the stage that is. + """ + with self._requests: + recorder = self.stage_resources + if recorder is None or not recorder.is_current(serial): + return + if (telemetry := self._telemetry()) is not None: + telemetry.transition_stage(stage_id, status="progress", **figures) + def _finish(self) -> None: + self._stop_recording() if self._close_service_on_finish: self.close() + def _stop_recording(self) -> None: + """Open no more stages and stop the recorder's thread. + + Called without the request lock held: the thread may be waiting for + it to send a report. + """ + if self.stage_resources is not None: + self.stage_resources.stop() + def close(self) -> None: """Ask the emitter to finish its hand-overs and stop; repeats do nothing.""" + self._stop_recording() if self._closed: return self._closed = True @@ -873,6 +1061,30 @@ def close(self) -> None: self.client.close() +def _error_text(error: BaseException) -> str | None: + """``error``'s text as the interface sends a failure's, ``None`` if ``str`` raises.""" + try: + return str(error) + except Exception: + return None + + +#: How the emitter reads a transition's status: these end the current stage, +#: with the status its end records. +_STAGE_END_STATUSES = { + "completed": "completed", + "passed": "completed", + "failed": "failed", +} +#: These make the stage named current. +_STAGE_START_STATUSES = frozenset({"running", "started"}) +#: The stage the emitter moves to at calibration's first epoch, and the kind +#: of event that is (the emitter's ``STAGE_CALIBRATING`` and +#: ``CALIBRATION_EVENT_KIND``). +_CALIBRATING_STAGE = "calibrating" +_CALIBRATION_EPOCH_KIND = "calibration_epoch" + + #: Whether the emitters a build starts submit described staged bundles, #: release publications, promotions and withdrawals to the collector. On #: since emitter 0.15.0 (2026-11-13), whose default leaves them off, and for diff --git a/packages/microcosm-build/tests/engine_free/shared/test_stage_resource_use.py b/packages/microcosm-build/tests/engine_free/shared/test_stage_resource_use.py new file mode 100644 index 0000000000..ed959d6203 --- /dev/null +++ b/packages/microcosm-build/tests/engine_free/shared/test_stage_resource_use.py @@ -0,0 +1,801 @@ +"""Each telemetry stage's memory footprint and CPU time over the build's process tree. + +``microcosm.build.stage_resource_use`` reads the footprint of the build process +and every descendant, keeps each stage's peaks, and computes the tree's CPU +time during the stage. The telemetry adapter attaches the figures to the event +that ends each stage, and to a ``progress`` event while a long stage runs. +These tests drive the recorder with readings and a clock they choose, and the +adapter with the in-memory emitter; one test reads this process's own tree. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +import threading +import time +from pathlib import Path + +import pytest + +from microcosm.build import program_telemetry +from microcosm.build import stage_resource_use as resource_use +from microcosm.build.stage_resource_use import StageResourceRecorder, TreeFootprints +from microcosm.build.telemetry_emitter import LocalTelemetryEmitter, TelemetryRun +from test_support.microcosm_build.telemetry import FakeTelemetryEmitter + +FIGURE_NAMES = ( + "tree_peak_footprint_bytes", + "main_process_peak_footprint_bytes", + "largest_child_peak_footprint_bytes", + "tree_cpu_user_seconds", + "tree_cpu_system_seconds", + "footprint_readings", + "wall_seconds", +) + + +class ChosenReadings: + """Footprint and CPU readings, and a clock, that a test sets as it goes.""" + + def __init__(self) -> None: + self.footprints = TreeFootprints(main_process_bytes=100, child_bytes=()) + self.cpu = (1.0, 0.5) + self.now = 10.0 + + def read_footprints(self) -> TreeFootprints: + return self.footprints + + def read_cpu(self) -> tuple[float, float]: + return self.cpu + + def clock(self) -> float: + return self.now + + +def _recorder(readings: ChosenReadings, **options) -> StageResourceRecorder: + return StageResourceRecorder( + run_id="run-1", + read_footprints=readings.read_footprints, + read_cpu=readings.read_cpu, + clock=readings.clock, + **options, + ) + + +def _emitter_with(recorder: StageResourceRecorder | None) -> FakeTelemetryEmitter: + return FakeTelemetryEmitter( + TelemetryRun("run-1", "US", "us_fiscal_refresh"), stage_resources=recorder + ) + + +def _stage_events(emitter) -> list[tuple[str, str]]: + return [ + (event["stage_id"], event["status"]) + for event in emitter.events + if event["event_type"] == "stage" + ] + + +def _event(emitter, stage_id: str, status: str) -> dict: + [event] = [ + event + for event in emitter.events + if event["event_type"] == "stage" + and event["stage_id"] == stage_id + and event["status"] == status + ] + return event + + +# --------------------------------------------------------------------------- +# The recorder +# --------------------------------------------------------------------------- + + +def test_a_stage_records_its_peaks_cpu_time_and_elapsed_time() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + + recorder.start_stage("calibrate") + readings.footprints = TreeFootprints(main_process_bytes=300, child_bytes=(50, 70)) + recorder.take_reading() + readings.footprints = TreeFootprints(main_process_bytes=200, child_bytes=(400,)) + recorder.take_reading() + readings.footprints = TreeFootprints(main_process_bytes=150, child_bytes=()) + readings.cpu = (4.25, 1.5) + readings.now = 12.5 + figures = recorder.end_stage("completed") + + assert figures == { + # 200 + 400 is the largest total at one reading; 300 + 50 + 70 is not. + "tree_peak_footprint_bytes": 600, + "main_process_peak_footprint_bytes": 300, + "largest_child_peak_footprint_bytes": 400, + "tree_cpu_user_seconds": 3.25, + "tree_cpu_system_seconds": 1.0, + # The start reading, the two between, and the end reading. + "footprint_readings": 4, + "wall_seconds": 2.5, + } + assert recorder.current_stage is None + assert recorder.completed_stages() == [ + {"run_id": "run-1", "stage_id": "calibrate", "status": "completed", **figures} + ] + + +def test_a_stage_without_descendants_has_no_largest_child() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + + recorder.start_stage("qa") + figures = recorder.end_stage("failed") + + assert figures["largest_child_peak_footprint_bytes"] is None + assert figures["tree_peak_footprint_bytes"] == 100 + assert recorder.completed_stages()[0]["status"] == "failed" + + +def test_a_reading_that_failed_is_not_counted() -> None: + readings = ChosenReadings() + readings.footprints = TreeFootprints(main_process_bytes=None, child_bytes=()) + recorder = _recorder(readings) + + recorder.start_stage("finalize") + figures = recorder.end_stage("completed") + + assert figures["footprint_readings"] == 0 + assert figures["tree_peak_footprint_bytes"] is None + assert figures["main_process_peak_footprint_bytes"] is None + + +def test_cpu_time_that_appears_to_fall_is_recorded_as_none_used() -> None: + """On macOS a grandchild's CPU can leave the running total until its + parent is waited for; a stage never records negative CPU time.""" + readings = ChosenReadings() + recorder = _recorder(readings) + + recorder.start_stage("materialize") + readings.cpu = (0.75, 0.25) + figures = recorder.end_stage("completed") + + assert figures["tree_cpu_user_seconds"] == 0.0 + assert figures["tree_cpu_system_seconds"] == 0.0 + + +def test_figures_so_far_leave_the_stage_open() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + recorder.start_stage("calibrating") + serial = recorder.current_serial + + readings.cpu = (2.0, 0.5) + readings.now = 70.0 + so_far = recorder.figures_so_far(serial) + + assert so_far["tree_cpu_user_seconds"] == 1.0 + assert so_far["wall_seconds"] == 60.0 + assert recorder.current_stage == "calibrating" + assert recorder.completed_stages() == [] + + +def test_figures_so_far_for_a_stage_that_ended_are_none() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + recorder.start_stage("qa") + serial = recorder.current_serial + recorder.end_stage("completed") + recorder.start_stage("qa") + + # The same stage ID again is another stage: its serial differs. + assert recorder.figures_so_far(serial) is None + assert not recorder.is_current(serial) + assert recorder.is_current(recorder.current_serial) + + +def test_a_report_is_due_each_report_interval_after_the_stage_starts() -> None: + readings = ChosenReadings() + recorder = _recorder(readings, report_interval_seconds=60.0) + recorder.start_stage("calibrating") + serial = recorder.current_serial + + readings.now = 69.0 + assert recorder.due_report() is None + readings.now = 70.0 + assert recorder.due_report() == ("calibrating", serial) + assert recorder.due_report() is None + readings.now = 130.0 + assert recorder.due_report() == ("calibrating", serial) + + +def test_a_stage_end_listener_receives_each_completed_entry() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + received = [] + recorder.add_stage_end_listener(received.append) + + recorder.start_stage("materialize") + recorder.end_stage("completed") + + assert received == recorder.completed_stages() + + +def test_a_failing_stage_end_listener_leaves_the_figures_in_place(capsys) -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + + def refuse(entry) -> None: + raise OSError("checkpoint disk full") + + recorder.add_stage_end_listener(refuse) + recorder.start_stage("materialize") + figures = recorder.end_stage("completed") + + assert figures is not None and set(figures) == set(FIGURE_NAMES) + assert recorder.completed_stages()[0]["stage_id"] == "materialize" + assert "checkpoint disk full" in capsys.readouterr().err + + +def test_no_stage_starts_once_recording_finished() -> None: + readings = ChosenReadings() + recorder = _recorder(readings) + recorder.finish() + + recorder.start_stage("package") + + assert recorder.current_stage is None + assert recorder.end_stage("completed") is None + + +def test_the_background_thread_reads_and_reports_the_open_stage() -> None: + readings = ChosenReadings() + reported = [] + reported_once = threading.Event() + + def report(stage_id, serial, figures) -> None: + reported.append((stage_id, figures)) + reported_once.set() + + recorder = StageResourceRecorder( + run_id="run-1", + read_footprints=readings.read_footprints, + read_cpu=readings.read_cpu, + reading_interval_seconds=0.01, + report_interval_seconds=0.05, + ) + recorder.start_stage("calibrating") + readings.footprints = TreeFootprints(main_process_bytes=100, child_bytes=(900,)) + recorder.start_background_readings(report=report) + try: + assert reported_once.wait(timeout=5) + finally: + recorder.stop() + + stage_id, figures = reported[0] + assert stage_id == "calibrating" + assert figures["tree_peak_footprint_bytes"] == 1000 + assert figures["footprint_readings"] >= 2 + assert set(figures) == set(FIGURE_NAMES) + assert recorder.current_stage == "calibrating" + + +def test_the_manifest_block_names_the_measure_and_the_interval() -> None: + entries = [{"run_id": "run-1", "stage_id": "qa", "status": "completed"}] + + block = resource_use.stage_resource_use_block(entries) + + assert block == { + "memory_measure": "footprint", + "reading_interval_seconds": 0.5, + "stages": entries, + } + assert block["stages"] is not entries + + +# --------------------------------------------------------------------------- +# The telemetry adapter +# --------------------------------------------------------------------------- + + +def test_a_stage_change_ends_the_previous_stage_with_its_figures() -> None: + readings = ChosenReadings() + emitter = _emitter_with(_recorder(readings)) + + emitter.transition_stage("preflight") + readings.footprints = TreeFootprints(main_process_bytes=500, child_bytes=(20,)) + emitter.transition_stage("target_registry", n_targets=3) + + assert _stage_events(emitter) == [ + ("preflight", "started"), + ("preflight", "completed"), + ("target_registry", "started"), + ] + ended = _event(emitter, "preflight", "completed")["details"] + assert set(ended) == set(FIGURE_NAMES) + assert ended["tree_peak_footprint_bytes"] == 520 + assert _event(emitter, "target_registry", "started")["details"] == {"n_targets": 3} + assert emitter.stage_resources.current_stage == "target_registry" + + +def test_ending_the_current_stage_attaches_its_figures_to_the_build_s_details() -> None: + readings = ChosenReadings() + emitter = _emitter_with(_recorder(readings)) + + emitter.transition_stage("weeks_unemployed_input") + emitter.transition_stage( + "weeks_unemployed_input", status="failed", failures=["signal collapsed"] + ) + + ended = _event(emitter, "weeks_unemployed_input", "failed")["details"] + assert ended["failures"] == ["signal collapsed"] + assert set(FIGURE_NAMES) <= set(ended) + assert emitter.stage_resources.current_stage is None + assert emitter.stage_resources.completed_stages()[0]["status"] == "failed" + + +def test_passed_ends_the_current_stage_as_completed() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("qa") + emitter.transition_stage("qa", status="passed") + + assert emitter.stage_resources.completed_stages()[0]["status"] == "completed" + + +def test_a_marker_for_another_stage_ends_the_current_stage_first() -> None: + """A failed gate marker names a stage that never started; the stage that + was running ends first, with its figures, as the emitter would end it.""" + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("load_base_frame") + emitter.transition_stage("input_gate", status="failed", failures=["x"]) + + assert _stage_events(emitter) == [ + ("load_base_frame", "started"), + ("load_base_frame", "completed"), + ("input_gate", "failed"), + ] + assert set(FIGURE_NAMES) <= set( + _event(emitter, "load_base_frame", "completed")["details"] + ) + assert _event(emitter, "input_gate", "failed")["details"] == {"failures": ["x"]} + assert emitter.stage_resources.current_stage is None + + +def test_starting_the_current_stage_again_keeps_it_open() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("calibrate") + serial = emitter.stage_resources.current_serial + emitter.transition_stage("calibrate", message="still calibrating") + + assert _stage_events(emitter) == [ + ("calibrate", "started"), + ("calibrate", "progress"), + ] + assert emitter.stage_resources.is_current(serial) + + +def test_the_first_calibration_epoch_ends_the_previous_stage() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + epoch = {"kind": "calibration_epoch", "epoch": 0} + + emitter.transition_stage("target_compilation") + emitter.transition_calibration_progress(epoch) + emitter.transition_calibration_progress({**epoch, "epoch": 1}) + emitter.transition_stage("export") + + assert _stage_events(emitter) == [ + ("target_compilation", "started"), + ("target_compilation", "completed"), + ("calibrating", "started"), + ("calibrating", "completed"), + ("export", "started"), + ] + assert set(FIGURE_NAMES) <= set( + _event(emitter, "target_compilation", "completed")["details"] + ) + assert set(FIGURE_NAMES) <= set( + _event(emitter, "calibrating", "completed")["details"] + ) + + +def test_completion_ends_the_open_stage_with_its_figures() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("package") + emitter.complete() + + assert set(FIGURE_NAMES) <= set(_event(emitter, "package", "completed")["details"]) + assert [entry["stage_id"] for entry in emitter.completed_stage_resource_use()] == [ + "package" + ] + + +def test_failure_ends_the_open_stage_as_failed_and_names_it() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("calibrate") + emitter.fail(RuntimeError("solver diverged")) + + ended = _event(emitter, "calibrate", "failed") + assert set(FIGURE_NAMES) <= set(ended["details"]) + # The failure's text and details, which the emitter carries to the stage + # it ends when the run fails, stay on the failing stage's end. + assert ended["message"] == "solver diverged" + assert { + key: ended["details"][key] + for key in ("error_type", "failure_class", "failed_during") + } == { + "error_type": "RuntimeError", + "failure_class": "build_failure", + "failed_during": "calibrate", + } + [run_failure] = [ + event + for event in emitter.events + if event["event_type"] == "run" and event["status"] == "failed" + ] + assert run_failure["details"]["failed_during"] == "calibrate" + assert emitter.completed_stage_resource_use()[0]["status"] == "failed" + + +def test_a_failure_s_given_stage_class_and_code_reach_the_failing_stage() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("reform_coverage_smoke") + emitter.fail( + SystemExit(143), + failed_during="post_export", + failure_class="terminated", + error_code="SIGTERM", + ) + + ended = _event(emitter, "reform_coverage_smoke", "failed") + assert ended["message"] == "143" + assert { + key: ended["details"].get(key) + for key in ("error_type", "failure_class", "failed_during", "error_code") + } == { + "error_type": "SystemExit", + "failure_class": "terminated", + "failed_during": "post_export", + "error_code": "SIGTERM", + } + + +def test_an_interrupt_while_the_failing_stage_ends_still_records_the_failure() -> None: + """A SIGTERM or Ctrl-C during the stage's end must not cost the run its + failure: the emitter would otherwise record only an unexpected exit.""" + readings = ChosenReadings() + interrupt = threading.Event() + + def read_cpu() -> tuple[float, float]: + if interrupt.is_set(): + raise KeyboardInterrupt + return readings.read_cpu() + + emitter = _emitter_with( + StageResourceRecorder( + run_id="run-1", + read_footprints=readings.read_footprints, + read_cpu=read_cpu, + clock=readings.clock, + ) + ) + emitter.transition_stage("calibrate") + + interrupt.set() + with pytest.raises(KeyboardInterrupt): + emitter.fail(RuntimeError("solver diverged")) + + [run_failure] = [ + event + for event in emitter.events + if event["event_type"] == "run" and event["status"] == "failed" + ] + assert run_failure["details"]["failed_during"] == "calibrate" + + +def test_a_refusal_ends_the_open_stage_as_completed() -> None: + emitter = _emitter_with(_recorder(ChosenReadings())) + + emitter.transition_stage("release_gates") + emitter.block(phase="release_gates", blocking_gate_ids=["a"]) + + assert set(FIGURE_NAMES) <= set( + _event(emitter, "release_gates", "completed")["details"] + ) + + +def test_a_progress_report_reaches_only_the_stage_it_was_read_for() -> None: + readings = ChosenReadings() + emitter = _emitter_with(_recorder(readings)) + emitter.transition_stage("calibrating") + serial = emitter.stage_resources.current_serial + figures = emitter.stage_resources.figures_so_far(serial) + + emitter._report_stage_progress("calibrating", serial, figures) + emitter.transition_stage("export") + # A report read before the stage ended, sent after it: nothing is sent, + # so it cannot end the stage that runs now. + emitter._report_stage_progress("calibrating", serial, figures) + + assert _stage_events(emitter) == [ + ("calibrating", "started"), + ("calibrating", "progress"), + ("calibrating", "completed"), + ("export", "started"), + ] + assert _event(emitter, "calibrating", "progress")["details"] == figures + + +def test_the_reading_thread_reports_the_open_stage_and_never_one_that_ended() -> None: + readings = ChosenReadings() + recorder = StageResourceRecorder( + run_id="run-1", + read_footprints=readings.read_footprints, + read_cpu=readings.read_cpu, + reading_interval_seconds=0.01, + report_interval_seconds=0.03, + ) + emitter = _emitter_with(recorder) + emitter.transition_stage("calibrating") + recorder.start_background_readings(report=emitter._report_stage_progress) + try: + deadline = time.monotonic() + 5 + while ("calibrating", "progress") not in _stage_events(emitter): + assert time.monotonic() < deadline, "no report within 5 seconds" + time.sleep(0.01) + emitter.transition_stage("export") + # Several report intervals while export runs. + time.sleep(0.15) + finally: + recorder.stop() + + events = _stage_events(emitter) + calibrating_ended = events.index(("calibrating", "completed")) + assert ("calibrating", "progress") in events[:calibrating_ended] + assert all(stage != "calibrating" for stage, _ in events[calibrating_ended + 1 :]) + assert ("export", "completed") not in events + assert recorder.current_stage == "export" + + +def test_figures_are_recorded_when_no_emitter_runs() -> None: + """A build without telemetry still writes the figures to its manifests.""" + emitter = LocalTelemetryEmitter( + run=TelemetryRun("run-1", "US", "us_acs_local_release"), + client=None, + stage_resources=_recorder(ChosenReadings()), + ) + + emitter.transition_stage("materialize") + emitter.transition_stage("calibrate") + emitter.complete() + + assert [ + (entry["stage_id"], entry["status"]) + for entry in emitter.completed_stage_resource_use() + ] == [("materialize", "completed"), ("calibrate", "completed")] + + +def test_an_adapter_without_a_recorder_sends_what_it_did_before() -> None: + emitter = _emitter_with(None) + + emitter.transition_stage("preflight") + emitter.transition_stage("target_registry") + emitter.complete() + + assert _event(emitter, "preflight", "completed")["details"] == {} + assert emitter.completed_stage_resource_use() == [] + + +def test_the_adapter_starts_the_recorder_s_thread_and_stops_it_at_the_outcome( + monkeypatch, tmp_path +) -> None: + """The adapter's own start, with an emitter that cannot be prepared.""" + from microcosm.build import telemetry_emitter + from test_support.microcosm_build.telemetry import ADAPTER_START + + monkeypatch.setattr(LocalTelemetryEmitter, "start", classmethod(ADAPTER_START)) + + def unavailable_identity(): + raise OSError("no identity here") + + monkeypatch.setattr(telemetry_emitter, "runtime_identity", unavailable_identity) + + emitter = LocalTelemetryEmitter.start( + run_id="run-1", + country_code="US", + pipeline="us_acs_local_release", + record_stage_resources=True, + ) + recorder = emitter.stage_resources + assert emitter.client is None + assert recorder is not None and recorder.reading_thread_alive + emitter.transition_stage("materialize") + emitter.complete() + + assert not recorder.reading_thread_alive + assert emitter.completed_stage_resource_use()[0]["stage_id"] == "materialize" + + +def test_the_adapter_records_nothing_unless_asked(monkeypatch) -> None: + from microcosm.build import telemetry_emitter + from test_support.microcosm_build.telemetry import ADAPTER_START + + monkeypatch.setattr(LocalTelemetryEmitter, "start", classmethod(ADAPTER_START)) + + def unavailable_identity(): + raise OSError("no identity here") + + monkeypatch.setattr(telemetry_emitter, "runtime_identity", unavailable_identity) + + emitter = LocalTelemetryEmitter.start( + run_id="run-1", country_code="US", pipeline="us_puf_support_base" + ) + + assert emitter.stage_resources is None + + +def test_a_build_program_asks_its_adapter_to_record_stage_resources( + fake_telemetry_emitters, +) -> None: + with program_telemetry.program_telemetry( + pipeline="us_acs_local_release", record_stage_resources=True + ) as emitter: + emitter.transition_stage("materialize") + + assert emitter.stage_resources is not None + assert emitter.completed_stage_resource_use()[0]["stage_id"] == "materialize" + + +def test_a_build_program_records_nothing_unless_asked(fake_telemetry_emitters) -> None: + with program_telemetry.program_telemetry(pipeline="us_puf_support_base") as emitter: + emitter.transition_stage("prepare") + + assert emitter.stage_resources is None + + +# --------------------------------------------------------------------------- +# Reading the process tree +# --------------------------------------------------------------------------- + + +def _fake_linux_process( + proc_root: Path, + pid: int, + *, + parent: int, + times: tuple[int, int, int, int] = (0, 0, 0, 0), + children_by_thread: dict[int, list[int]] | None = None, +) -> None: + """One process's ``stat`` and, if given, its threads' ``children`` files.""" + directory = proc_root / str(pid) + (directory / "task").mkdir(parents=True) + utime, stime, cutime, cstime = times + fields = [ + "S", + str(parent), + *["0"] * 9, + str(utime), + str(stime), + str(cutime), + str(cstime), + *["0"] * 5, + ] + # A command name with spaces and a ")" is why the fields are read after + # the last ")". + (directory / "stat").write_text(f"{pid} (python (w) x) " + " ".join(fields)) + for thread, children in (children_by_thread or {}).items(): + (directory / "task" / str(thread)).mkdir() + (directory / "task" / str(thread) / "children").write_text( + " ".join(map(str, children)) + (" " if children else "") + ) + + +def test_linux_descendants_come_from_every_thread_s_children_file( + tmp_path, +) -> None: + proc_root = tmp_path / "proc" + _fake_linux_process( + proc_root, 10, parent=1, children_by_thread={10: [11], 12: [13]} + ) + _fake_linux_process(proc_root, 11, parent=10, children_by_thread={11: [14]}) + _fake_linux_process(proc_root, 13, parent=10, children_by_thread={13: []}) + _fake_linux_process(proc_root, 14, parent=11, children_by_thread={14: []}) + _fake_linux_process(proc_root, 99, parent=1, children_by_thread={99: []}) + + assert sorted(resource_use.linux_descendant_pids(10, proc_root=proc_root)) == [ + 11, + 13, + 14, + ] + + +def test_linux_descendants_come_from_every_process_s_parent_without_children_files( + tmp_path, +) -> None: + """A kernel built without ``children`` files: every ``stat`` names its parent.""" + proc_root = tmp_path / "proc" + for pid, parent in ((10, 1), (11, 10), (13, 10), (14, 11), (99, 1)): + _fake_linux_process(proc_root, pid, parent=parent) + (proc_root / "self").mkdir() + + assert sorted(resource_use.linux_descendant_pids(10, proc_root=proc_root)) == [ + 11, + 13, + 14, + ] + + +def test_linux_process_cpu_counts_the_children_it_waited_for(tmp_path) -> None: + proc_root = tmp_path / "proc" + _fake_linux_process(proc_root, 11, parent=10, times=(300, 100, 50, 25)) + + user, system = resource_use.linux_process_cpu_seconds( + 11, proc_root=proc_root, ticks_per_second=100 + ) + + assert (user, system) == (3.5, 1.25) + + +def test_linux_process_cpu_of_a_process_gone_is_none(tmp_path) -> None: + assert ( + resource_use.linux_process_cpu_seconds( + 11, proc_root=tmp_path / "proc", ticks_per_second=100 + ) + is None + ) + + +def test_tree_footprints_sum_the_main_process_and_its_descendants() -> None: + footprints = resource_use.read_tree_footprints( + pid=10, + descendants_of=lambda pid: [11, 12, 13], + memory_of={10: 1000, 11: 200, 12: None, 13: 300}.get, + ) + + assert footprints == TreeFootprints(main_process_bytes=1000, child_bytes=(200, 300)) + assert footprints.tree_bytes == 1500 + assert footprints.largest_child_bytes == 300 + + +@pytest.mark.skipif( + not (sys.platform == "darwin" or sys.platform.startswith("linux")), + reason="the tree is read on macOS and Linux only", +) +def test_this_process_s_tree_includes_a_running_child_and_its_cpu_time() -> None: + """The real readers, on this machine: a child that used CPU time is in + the tree while it runs, and its CPU time stays in the total after it + exits and is waited for.""" + script = ( + "import sys, time\n" + "end = time.process_time() + 0.3\n" + "while time.process_time() < end:\n" + " pass\n" + "sys.stdout.write('spun\\n'); sys.stdout.flush()\n" + "time.sleep(60)\n" + ) + before_user, before_system = resource_use.tree_cpu_seconds() + child = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE) + try: + assert child.stdout.readline() == b"spun\n" + assert child.pid in resource_use.descendant_pids(os.getpid()) + footprints = resource_use.read_tree_footprints() + assert footprints.main_process_bytes > 0 + assert footprints.largest_child_bytes > 0 + running_user, running_system = resource_use.tree_cpu_seconds() + running = (running_user + running_system) - (before_user + before_system) + # The child spun for 0.3 s after starting; a wrong time-unit + # conversion would make this many times larger or smaller. + assert 0.25 <= running < 5.0 + finally: + child.kill() + child.wait() + after_user, after_system = resource_use.tree_cpu_seconds() + + assert child.pid not in resource_use.descendant_pids(os.getpid()) + after = (after_user + after_system) - (before_user + before_system) + assert 0.25 <= after < 5.0 diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py index 66762b84fc..7b2a3ce75e 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_acs_local_release_tool.py @@ -8710,3 +8710,201 @@ def test_finalize_loads_every_stored_congressional_district_plan(tmp_path) -> No path, module._finalize_columns(), module._finalize_column_prefixes() ) assert "congressional_district_geoid__cd118" in loaded.table("household") + + +# --------------------------------------------------------------------------- +# Each stage's memory footprint and CPU time (microcosm.build.stage_resource_use) +# --------------------------------------------------------------------------- + +#: The checkpoint file each stage's resource use is kept in until ``package`` +#: writes it to the manifests; stages may run in separate invocations. +_STAGE_RESOURCE_USE_FILE = "stage_resource_use.json" +_LOCAL_STAGE_FIGURES = ( + "tree_peak_footprint_bytes", + "main_process_peak_footprint_bytes", + "largest_child_peak_footprint_bytes", + "tree_cpu_user_seconds", + "tree_cpu_system_seconds", + "footprint_readings", + "wall_seconds", +) + + +def _local_stage_entry(stage_id: str, run_id: str = "earlier-run") -> dict: + return { + "run_id": run_id, + "stage_id": stage_id, + "status": "completed", + **{name: 1 for name in _LOCAL_STAGE_FIGURES}, + } + + +def _run_local_main_with_stubbed_stages(module, monkeypatch, checkpoint, stages): + """Run ``main`` for ``stages`` with each stage's work replaced by nothing.""" + import contextlib + + args = SimpleNamespace(stages=list(stages), checkpoint_dir=checkpoint) + monkeypatch.setattr(module, "_parse_args", lambda argv: args) + for name in ( + "do_materialize", + "do_calibrate", + "do_qa", + "do_finalize", + "do_package", + ): + monkeypatch.setattr(module, name, lambda stage_args: None) + monkeypatch.setattr( + module, + "_local_gate_shadow_stage", + lambda stage_args, stage: contextlib.nullcontext(), + ) + return module.main([]) + + +def test_each_stage_s_resource_use_reaches_its_end_event_and_the_checkpoint( + tmp_path: Path, monkeypatch, fake_telemetry_emitters +) -> None: + module = _load_tool_module() + checkpoint = tmp_path / "ckpt" + + assert ( + _run_local_main_with_stubbed_stages( + module, monkeypatch, checkpoint, ["materialize", "calibrate"] + ) + == 0 + ) + + [emitter] = fake_telemetry_emitters + ended = { + event["stage_id"]: event["details"] + for event in emitter.events + if event["event_type"] == "stage" and event["status"] == "completed" + } + assert set(ended) == {"materialize", "calibrate"} + for details in ended.values(): + assert set(_LOCAL_STAGE_FIGURES) <= set(details) + entries = json.loads((checkpoint / _STAGE_RESOURCE_USE_FILE).read_text()) + assert [(entry["stage_id"], entry["status"]) for entry in entries] == [ + ("materialize", "completed"), + ("calibrate", "completed"), + ] + assert {entry["run_id"] for entry in entries} == {emitter.run.run_id} + + +def test_a_stage_run_again_replaces_its_entry_and_those_of_later_stages( + tmp_path: Path, monkeypatch, fake_telemetry_emitters +) -> None: + """The checkpoint describes the stages that made its current files: a stage + run again replaces them, and the files of every stage after it.""" + module = _load_tool_module() + checkpoint = tmp_path / "ckpt" + checkpoint.mkdir() + (checkpoint / _STAGE_RESOURCE_USE_FILE).write_text( + json.dumps( + [ + _local_stage_entry("materialize"), + _local_stage_entry("calibrate"), + _local_stage_entry("qa"), + ] + ) + ) + + _run_local_main_with_stubbed_stages(module, monkeypatch, checkpoint, ["calibrate"]) + + [emitter] = fake_telemetry_emitters + entries = json.loads((checkpoint / _STAGE_RESOURCE_USE_FILE).read_text()) + assert [(entry["stage_id"], entry["run_id"]) for entry in entries] == [ + ("materialize", "earlier-run"), + ("calibrate", emitter.run.run_id), + ] + + +def test_package_records_each_stage_s_resource_use_in_both_manifests( + tmp_path: Path, monkeypatch +) -> None: + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + entries = [_local_stage_entry(stage) for stage in ("materialize", "calibrate")] + (args.checkpoint_dir / _STAGE_RESOURCE_USE_FILE).write_text(json.dumps(entries)) + + result = module.do_package(args) + + release_dir = Path(result["release_dir"]) + expected = { + "memory_measure": "footprint", + "reading_interval_seconds": 0.5, + "stages": entries, + } + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + release_manifest = json.loads((release_dir / "release_manifest.json").read_text()) + assert build_manifest.get("stage_resource_use") == expected + # The build-folder layout moves the build object's fields to the release + # manifest's top level (microcosm#1570), as it moves the others. + assert release_manifest.get("stage_resource_use") == expected + + +def test_package_without_recorded_stages_records_an_empty_list( + tmp_path: Path, monkeypatch +) -> None: + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + + result = module.do_package(args) + + build_manifest = json.loads( + (Path(result["release_dir"]) / "build_manifest.json").read_text() + ) + assert build_manifest.get("stage_resource_use", {}).get("stages") == [] + + +def test_a_malformed_checkpoint_entry_file_stops_no_stage( + tmp_path: Path, monkeypatch, fake_telemetry_emitters, capsys +) -> None: + """The entries are run metadata: a file that can't be read warns, and the + stage runs and records its entry afresh.""" + module = _load_tool_module() + checkpoint = tmp_path / "ckpt" + checkpoint.mkdir() + (checkpoint / _STAGE_RESOURCE_USE_FILE).write_text("{not json") + + assert ( + _run_local_main_with_stubbed_stages( + module, monkeypatch, checkpoint, ["materialize"] + ) + == 0 + ) + + entries = json.loads((checkpoint / _STAGE_RESOURCE_USE_FILE).read_text()) + assert [entry["stage_id"] for entry in entries] == ["materialize"] + assert _STAGE_RESOURCE_USE_FILE in capsys.readouterr().err + + +def test_package_with_a_malformed_entry_file_records_no_stages( + tmp_path: Path, monkeypatch, capsys +) -> None: + module = _load_tool_module() + args = _package_evidence_args( + module, + tmp_path, + monkeypatch, + hours_report={"passed": True, "failures": [], "detail": {}}, + ) + (args.checkpoint_dir / _STAGE_RESOURCE_USE_FILE).write_text("[1, 2") + + result = module.do_package(args) + + build_manifest = json.loads( + (Path(result["release_dir"]) / "build_manifest.json").read_text() + ) + assert build_manifest["stage_resource_use"]["stages"] == [] + assert _STAGE_RESOURCE_USE_FILE in capsys.readouterr().err diff --git a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py index 9a5735514b..b4b651c074 100644 --- a/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py +++ b/packages/microcosm-build/tests/engine_free/us/test_us_fiscal_refresh_builder.py @@ -21027,11 +21027,14 @@ def _build_record_fixture( terminal_gate_failures=(), staging=None, staging_settings=None, + stage_resource_use=None, ) -> tuple[Path, dict]: """A minimal finished build: the files certification reads, and its record. Its gate evidence is two of the build's files; the build wrote no ESI premium evidence, and the smoke's is certification's to write. + ``stage_resource_use``, when given, is what the build run recorded of its + stages' memory and CPU use. """ release_root = tmp_path / "build" @@ -21133,6 +21136,11 @@ def _build_record_fixture( "no_staging": True, "repo_id": None, }, + **( + {"stage_resource_use": stage_resource_use} + if stage_resource_use is not None + else {} + ), ) path = builder._write_us_build_record(release_root, payload) return path, payload @@ -21156,6 +21164,9 @@ def complete(self) -> None: def fail(self, error) -> None: self.events.append(("fail", error)) + def completed_stage_resource_use(self) -> list[dict]: + return [] + def _stub_certify_telemetry(builder, monkeypatch) -> dict[str, object]: """Start no emitter, and hand certification a recording progress handle.""" @@ -21397,6 +21408,8 @@ def dirty(*, excluding): "candidate_id": "populace-us-2024-test-build", "release_id": "populace-us-2024-test-build", "run_kind": "certification", + # Certification records each stage's memory and CPU time. + "record_stage_resources": True, } assert seen_telemetry["progress_run_id"] == "populace-us-2024-test-build-certify" assert seen_telemetry["progress_build"] == "populace-us-2024-test-build" @@ -22604,3 +22617,184 @@ def fail(self, error, **details): ) assert calls == [("stage", "preflight"), ("failed", "SystemExit")] assert not out.exists() + + +# --------------------------------------------------------------------------- +# Each stage's memory footprint and CPU time (microcosm.build.stage_resource_use) +# --------------------------------------------------------------------------- + +_BUILD_STAGE_ENTRY = { + "run_id": "us-fiscal-refresh-build-1", + "stage_id": "preflight", + "status": "completed", + "tree_peak_footprint_bytes": 2_000, + "main_process_peak_footprint_bytes": 1_500, + "largest_child_peak_footprint_bytes": 500, + "tree_cpu_user_seconds": 3.0, + "tree_cpu_system_seconds": 0.5, + "footprint_readings": 4, + "wall_seconds": 2.25, +} +_CERTIFICATION_STAGE_ENTRY = { + **_BUILD_STAGE_ENTRY, + "run_id": "us-fiscal-refresh-build-1-certify", + "stage_id": "reform_coverage_smoke", +} + + +def test_both_runs_of_the_release_tool_record_each_stage_s_resource_use() -> None: + import ast + + builder = _load_builder_module() + calls = [ + *_calls_named( + _builder_function(builder, "_main"), "start_local_telemetry_emitter_service" + ), + *_calls_named( + _builder_function(builder, "_certify_main_with_close_out"), + "start_local_telemetry_emitter_service", + ), + ] + + assert len(calls) == 2 + for call in calls: + keywords = {kw.arg: ast.unparse(kw.value) for kw in call.keywords} + assert keywords.get("record_stage_resources") == "True" + + +def test_the_build_hands_its_completed_stages_to_its_record() -> None: + import ast + + builder = _load_builder_module() + [call] = _calls_named(_builder_function(builder, "_main"), "_us_build_record") + keywords = {kw.arg: ast.unparse(kw.value) for kw in call.keywords} + + assert ( + keywords.get("stage_resource_use") + == "_ACTIVE_EMITTER.completed_stage_resource_use()" + ) + + +def test_the_build_record_carries_the_build_run_s_stage_resource_use( + tmp_path: Path, +) -> None: + builder = _load_builder_module() + path, payload = _build_record_fixture( + builder, tmp_path, stage_resource_use=[_BUILD_STAGE_ENTRY] + ) + + assert payload.get("stage_resource_use") == [_BUILD_STAGE_ENTRY] + record = builder._read_us_build_record(path) + assert record.stage_resource_use == [_BUILD_STAGE_ENTRY] + + +def test_a_record_written_before_stage_resource_use_was_recorded_has_none( + tmp_path: Path, +) -> None: + builder = _load_builder_module() + path, _ = _build_record_fixture(builder, tmp_path) + payload = json.loads(path.read_text()) + payload.pop("stage_resource_use", None) + builder._write_us_build_record(path.parent, payload) + + record = builder._read_us_build_record(path) + + assert record.stage_resource_use == [] + + +def test_certification_lists_the_build_s_stages_then_its_own(tmp_path: Path) -> None: + import ast + + builder = _load_builder_module() + path, _ = _build_record_fixture( + builder, tmp_path, stage_resource_use=[_BUILD_STAGE_ENTRY] + ) + record = builder._read_us_build_record(path) + telemetry = SimpleNamespace( + completed_stage_resource_use=lambda: [_CERTIFICATION_STAGE_ENTRY] + ) + + block = builder._certified_stage_resource_use(record, telemetry) + + assert block == { + "memory_measure": "footprint", + "reading_interval_seconds": 0.5, + "stages": [_BUILD_STAGE_ENTRY, _CERTIFICATION_STAGE_ENTRY], + } + assert builder._certified_stage_resource_use(record, None)["stages"] == [ + _BUILD_STAGE_ENTRY + ] + keywords = { + kw.arg: ast.unparse(kw.value) for kw in _manifest_call(builder).keywords + } + assert ( + keywords.get("stage_resource_use") + == "_certified_stage_resource_use(record, telemetry)" + ) + + +def test_both_manifests_record_each_stage_s_resource_use(monkeypatch, tmp_path) -> None: + builder = _load_builder_module() + release_id = "populace-us-2024-stage-resource-use" + release_dir = tmp_path / "release" / release_id + release_dir.mkdir(parents=True) + artifact_root = tmp_path / "artifacts" + artifact_root.mkdir() + (artifact_root / builder.DATASET_FILENAME).write_bytes(b"h5") + (artifact_root / builder.CALIBRATION_FILENAME).write_bytes(b"npz") + (release_dir / "us_source_coverage.json").write_text("{}") + (release_dir / "us_ssi_take_up.json").write_text("{}") + monkeypatch.setattr( + builder, + "_runtime_versions", + lambda: { + "python": "3.14.0", + "microcosm-data": "0.1.0", + "policyengine-core": "3.32.5", + "policyengine-us": "2.2.1", + }, + ) + monkeypatch.setattr(builder, "_git_output", lambda *args: "a" * 40) + block = { + "memory_measure": "footprint", + "reading_interval_seconds": 0.5, + "stages": [_BUILD_STAGE_ENTRY, _CERTIFICATION_STAGE_ENTRY], + } + + builder._build_manifests( + diagnostics_outcome=SimpleNamespace( + status="failed", + expected_schema_version=8, + error_code="validation_error", + message="Target hierarchy is incomplete.", + ), + stage_resource_use=block, + **_minimal_manifest_kwargs(builder, release_id, release_dir, artifact_root), + ) + + build_manifest = json.loads((release_dir / "build_manifest.json").read_text()) + release_manifest = json.loads((release_dir / "release_manifest.json").read_text()) + assert build_manifest.get("stage_resource_use") == block + assert release_manifest["build"].get("stage_resource_use") == block + + +def test_build_progress_hands_over_its_emitter_s_completed_stages() -> None: + from microcosm.build.stage_resource_use import StageResourceRecorder + from microcosm.build.telemetry_emitter import TelemetryRun + from test_support.microcosm_build.telemetry import FakeTelemetryEmitter + + builder = _load_builder_module() + emitter = FakeTelemetryEmitter( + TelemetryRun("rel-1", "US", "us_fiscal_refresh"), + stage_resources=StageResourceRecorder(run_id="rel-1"), + ) + progress = builder._BuildProgress( + run_id="rel-1", emitter=emitter, staging_bundle=None + ) + + progress.stage("target_registry") + progress.stage("load_base_frame") + + assert [entry["stage_id"] for entry in progress.completed_stage_resource_use()] == [ + "target_registry" + ] diff --git a/test_support/microcosm_build/telemetry.py b/test_support/microcosm_build/telemetry.py index c5c6e518fa..7ed2909170 100644 --- a/test_support/microcosm_build/telemetry.py +++ b/test_support/microcosm_build/telemetry.py @@ -22,11 +22,14 @@ import sys from collections.abc import Callable, Mapping, Sequence -from typing import Any +from typing import TYPE_CHECKING, Any from microcosm.build.telemetry_emitter import LocalTelemetryEmitter, TelemetryRun from test_support.microcosm_build.emitter import FakeEmitterClient +if TYPE_CHECKING: + from microcosm.build.stage_resource_use import StageResourceRecorder + BUILD_COMPLETED_MESSAGE = "Microcosm build completed." BUILD_BLOCKED_MESSAGE = "Validation checks refused the candidate at {phase}." #: How the service reads a transition's status. @@ -237,12 +240,14 @@ def __init__( *, close_service_on_finish: bool = True, client: FakeEmitterClient | None = None, + stage_resources: StageResourceRecorder | None = None, ) -> None: super().__init__( run=run, client=client if client is not None else client_factory(), close_service_on_finish=close_service_on_finish, ) + self.stage_resources = stage_resources @property def events(self) -> list[dict[str, Any]]: diff --git a/tools/build_us_acs_local_release.py b/tools/build_us_acs_local_release.py index 346aa4f8c0..c2a4953a7e 100644 --- a/tools/build_us_acs_local_release.py +++ b/tools/build_us_acs_local_release.py @@ -103,6 +103,10 @@ Telemetry: after parsing its arguments the tool starts the emitter (``microcosm.build.program_telemetry``, pipeline ``us_acs_local_release``), records each stage it runs and then completion, or failure with the error. +The event that ends each stage carries the stage's memory footprint and CPU +time over the tool's process tree (``microcosm.build.stage_resource_use``), +which the checkpoint's ``stage_resource_use.json`` keeps until ``package`` +writes them to both manifests. With ``MICROCOSM_TELEMETRY_REQUIRED=1``, which the Modal stage runner sets, an emitter that cannot be used stops the tool before any stage. The runner also names the telemetry run (``MICROCOSM_TELEMETRY_RUN_ID``); run by hand, the tool @@ -143,6 +147,7 @@ set_build_thread_environment(capped_default_count=release_default_thread_count()) import argparse +import functools import gc import hashlib import json @@ -161,6 +166,7 @@ from microcosm.build import host_resources from microcosm.build.gate_battery import EvidenceContext from microcosm.build.program_telemetry import program_telemetry +from microcosm.build.stage_resource_use import stage_resource_use_block from microcosm.build.us_runtime import target_loss_weights as loss_weighting from microcosm.build.us_runtime.acs_inputs import acs_self_employment_identity_gate from microcosm.build.us_runtime.acs_local_hours import acs_local_hours_signal_gate @@ -8532,6 +8538,9 @@ def _version(package: str) -> str: # Both manifests are written in the tagged shape and rewritten into the # build-folder layout below, by rewrite_release_dir. + stage_resource_use = stage_resource_use_block( + _stage_resource_entries(args.checkpoint_dir) + ) build_manifest = { "build_id": build_id, "build_sha": code["sha"], @@ -8545,6 +8554,9 @@ def _version(package: str) -> str: "policyengine_us": _version("policyengine-us"), "python": sys.version.split()[0], }, + # Each stage's memory footprint and CPU time, run metadata: the + # stages that ended before this one (microcosm.build.stage_resource_use). + "stage_resource_use": stage_resource_use, "dataset": { "kind": "acs_local_area_multispine", "staging_h5_sha256": (staging_summary.get("output", {}) or {}).get( @@ -8727,6 +8739,7 @@ def _artifact(path_name: str, kind: str, local: Path) -> dict: "name": "policyengine-us", "version": _version("policyengine-us"), }, + "stage_resource_use": stage_resource_use, }, "calibration_diagnostics": diagnostics_status, "artifacts": artifacts, @@ -9155,6 +9168,72 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: #: The telemetry pipeline this tool reports under. TELEMETRY_PIPELINE = "us_acs_local_release" +#: The checkpoint file that keeps each ended stage's memory footprint and CPU +#: time (microcosm.build.stage_resource_use) until ``package`` writes them to +#: the manifests: the stages may run in separate invocations. +STAGE_RESOURCE_USE_FILENAME = "stage_resource_use.json" +#: The stages in the order they run. +_STAGES_IN_ORDER = ("materialize", "calibrate", "qa", "finalize", "package") + + +def _stage_resource_entries(checkpoint_dir: Path) -> list[dict]: + """The checkpoint's stage entries, in the order the stages ended. + + They are run metadata: a file that can't be read, or holds anything but + a list of entries, warns and counts as none, and no stage stops for it. + """ + path = checkpoint_dir / STAGE_RESOURCE_USE_FILENAME + if not path.is_file(): + return [] + try: + entries = json.loads(path.read_text()) + except (OSError, ValueError) as error: + entries = error + if isinstance(entries, list) and all(isinstance(entry, dict) for entry in entries): + return entries + print( + f"warning: {path} holds no list of stage entries " + f"({type(entries).__name__}: {entries}); the stages ended before this " + "run are not recorded.", + file=sys.stderr, + ) + return [] + + +def _write_stage_resource_entries(checkpoint_dir: Path, entries: list[dict]) -> None: + path = checkpoint_dir / STAGE_RESOURCE_USE_FILENAME + staged = path.with_name(f".{path.name}.tmp") + staged.write_text(json.dumps(entries, indent=1)) + staged.replace(path) + + +def _add_stage_resource_entry(checkpoint_dir: Path, entry: dict) -> None: + """Keep an ended stage's entry in the checkpoint.""" + _write_stage_resource_entries( + checkpoint_dir, [*_stage_resource_entries(checkpoint_dir), entry] + ) + + +def _start_local_stage(telemetry, args, stage: str) -> None: + """Start ``stage`` in the telemetry run. + + The checkpoint describes the stages that made its current files, so the + entries of ``stage`` and of every stage after it, which this run replaces, + are dropped first. + """ + replaced = set(_STAGES_IN_ORDER[_STAGES_IN_ORDER.index(stage) :]) + entries = _stage_resource_entries(args.checkpoint_dir) + kept = [entry for entry in entries if entry.get("stage_id") not in replaced] + if kept != entries: + try: + _write_stage_resource_entries(args.checkpoint_dir, kept) + except OSError as error: + print( + f"warning: {STAGE_RESOURCE_USE_FILENAME} could not be rewritten " + f"({type(error).__name__}: {error}); the stage runs.", + file=sys.stderr, + ) + telemetry.transition_stage(stage) #: This tool's scope of us/gates.json, evaluated in shadow beside today's @@ -9303,30 +9382,36 @@ def _legacy_district_ess_verdict(entry: dict) -> LegacyVerdict: def main(argv: list[str] | None = None) -> int: args = _parse_args(argv) host_resources.report_resource_budget(args) - with program_telemetry(pipeline=TELEMETRY_PIPELINE) as telemetry: + with program_telemetry( + pipeline=TELEMETRY_PIPELINE, record_stage_resources=True + ) as telemetry: args.checkpoint_dir.mkdir(parents=True, exist_ok=True) + if telemetry.stage_resources is not None: + telemetry.stage_resources.add_stage_end_listener( + functools.partial(_add_stage_resource_entry, args.checkpoint_dir) + ) sampler = RssSampler() sampler.start() started = time.time() try: if "materialize" in args.stages: - telemetry.transition_stage("materialize") + _start_local_stage(telemetry, args, "materialize") with _local_gate_shadow_stage(args, "materialize"): do_materialize(args) if "calibrate" in args.stages: - telemetry.transition_stage("calibrate") + _start_local_stage(telemetry, args, "calibrate") with _local_gate_shadow_stage(args, "calibrate"): do_calibrate(args) if "qa" in args.stages: - telemetry.transition_stage("qa") + _start_local_stage(telemetry, args, "qa") with _local_gate_shadow_stage(args, "qa"): do_qa(args) if "finalize" in args.stages: - telemetry.transition_stage("finalize") + _start_local_stage(telemetry, args, "finalize") with _local_gate_shadow_stage(args, "finalize"): do_finalize(args) if "package" in args.stages: - telemetry.transition_stage("package") + _start_local_stage(telemetry, args, "package") with _local_gate_shadow_stage(args, "package"): do_package(args) finally: diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index be43044aaa..a035358606 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -118,6 +118,7 @@ from microcosm.build.ledger_artifact import load_ledger_consumer_artifact from microcosm.build.run_outcome import classify_failure from microcosm.build.source_runtime import SourceRuntimeConfig, run_source_stage +from microcosm.build.stage_resource_use import stage_resource_use_block from microcosm.build.staging_storage import confirm_and_report_final_commit from microcosm.build.staging_v2 import ( EMITTER_MAX_FILE_BYTES, @@ -13504,6 +13505,7 @@ def _build_manifests( built_at: str | None = None, runtime_versions: Mapping[str, str] | None = None, certification: Mapping[str, object] | None = None, + stage_resource_use: Mapping[str, object] | None = None, ) -> None: dataset_path = artifact_root / dataset_filename calibration_path = artifact_root / calibration_filename @@ -13650,6 +13652,13 @@ def _build_manifests( **({"certification": dict(certification)} if certification is not None else {}), "runtime": runtime, "timing": timing_payload, + # Each stage's memory footprint and CPU time: run metadata, like + # timing (microcosm.build.stage_resource_use). + **( + {"stage_resource_use": dict(stage_resource_use)} + if stage_resource_use is not None + else {} + ), "ledger_artifact": dict(ledger_artifact) if ledger_artifact else None, **( {"exact_k_ladder": dict(exact_k_ladder)} @@ -13911,6 +13920,11 @@ def _build_manifests( "version": runtime["policyengine-us"], }, "timing": timing_payload, + **( + {"stage_resource_use": dict(stage_resource_use)} + if stage_resource_use is not None + else {} + ), "ledger_artifact": dict(ledger_artifact) if ledger_artifact else None, **( {"exact_k_ladder": dict(exact_k_ladder)} @@ -15136,6 +15150,10 @@ def complete(self) -> None: confirm_and_report_final_commit(self.staging_bundle, self.emitter) self.emitter.complete() + def completed_stage_resource_use(self) -> list[dict[str, object]]: + """Each stage this run has ended: its memory footprint and CPU time.""" + return self.emitter.completed_stage_resource_use() + #: The progress coordinator for the build in flight, so the entry point can #: report failure without threading another handle back through the call stack. @@ -16233,6 +16251,7 @@ def _us_build_record( timing: Mapping[str, object], staging: Mapping[str, object], staging_settings: Mapping[str, object], + stage_resource_use: Sequence[Mapping[str, object]] = (), ) -> dict[str, object]: """What certification needs of a finished build, as strict JSON. @@ -16366,6 +16385,9 @@ def relative(path: Path) -> str: "snap_state": snap_state_take_up_diagnostics, }, "timing": dict(timing), + # Each stage the build run ended: its memory footprint and CPU time + # (microcosm.build.stage_resource_use), for the manifests. + "stage_resource_use": [dict(entry) for entry in stage_resource_use], "staging": dict(staging), # Where the build staged, so certification stages there too. "staging_settings": dict(staging_settings), @@ -16440,6 +16462,10 @@ def __init__(self, payload: Mapping[str, Any], *, release_root: Path) -> None: ) self.n_households = int(payload["n_households"]) self.timing = dict(payload["timing"]) + # A record written before stages' resource use was recorded has none. + self.stage_resource_use = [ + dict(entry) for entry in payload.get("stage_resource_use", []) + ] self.staging = dict(payload["staging"]) self.staging_settings = dict(payload["staging_settings"]) self.manifest_inputs = dict(payload["manifest"]) @@ -17141,6 +17167,7 @@ def _certify_main_with_close_out(argv: Sequence[str] | None) -> None: candidate_id=record.build, release_id=certification.build, run_kind="certification", + record_stage_resources=True, ) telemetry: _BuildProgress | None = None try: @@ -17777,6 +17804,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: candidate_id=args.release_id, release_id=args.release_id if not is_dry_run else None, run_kind="dry_run" if is_dry_run else "release", + record_stage_resources=True, ) _ACTIVE_EMITTER.transition_stage( "preflight", @@ -21657,6 +21685,7 @@ def _main(argv: Sequence[str] | None = None) -> int | None: "no_staging": bool(args.no_staging), "repo_id": args.staging_repo_id or None, }, + stage_resource_use=_ACTIVE_EMITTER.completed_stage_resource_use(), ), ) # The record pins the H5 now, so the build is complete. @@ -21738,6 +21767,22 @@ def _record_certification_failures( return path +def _certified_stage_resource_use( + record: _USBuildRecord, telemetry: _BuildProgress | None +) -> dict[str, object]: + """The manifests' ``stage_resource_use``: the build run's stages, then + certification's. + + Certification writes the manifests in its ``manifests`` stage, so that + stage and any after it are not in them; the telemetry events that end + them carry their figures. + """ + certification_stages = ( + telemetry.completed_stage_resource_use() if telemetry is not None else [] + ) + return stage_resource_use_block([*record.stage_resource_use, *certification_stages]) + + def _certify_us_build( record: _USBuildRecord, *, @@ -22261,6 +22306,7 @@ def _certify_us_build( built_at=record.built_at, runtime_versions=record.runtime, certification=certification.manifest_block(record), + stage_resource_use=_certified_stage_resource_use(record, telemetry), ) # Both manifests name the release and this build, in the build-folder # layout, before telemetry attaches them; the directory must then pass