diff --git a/CHANGELOG.md b/CHANGELOG.md index 127be75..2c914fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,68 @@ ## Unreleased +**A worker that dies stops the aggregate stage at once, naming the +leaves in flight and how the workers ended.** The leaves ran on a +`multiprocessing.Pool` that renewed each worker after 16 leaves, and a +worker that died outright, killed by a signal such as the kernel's for +memory or ending as its setup raised, left the pool waiting for ever for +the leaf it held. The leaves now run on a `ProcessPoolExecutor` under +the platform's own start method, fork on Linux, in waves of 16 leaves a +worker with new workers for each wave, and no more leaves are handed out +than there are workers. A death raises with the leaves in flight and the +workers' exit codes, and no statistics are written. Leaf files already +written are kept, and the leaves manifest is left incomplete. Any other +error that stops the run, such as a leaf written with other columns, now +waits for the leaves in flight to finish, where the pool killed them. +The reduce stage said a dead worker was most likely killed for memory, +whatever ended it. It now gives the exit codes, and speaks of the memory +budget only when a worker was killed by SIGKILL. A worker whose setup +raised exits with code 0 and logs the traceback, and is said to. The +waves cost half a second to a second on the leaf benchmark, 384 leaves +at an eighth of the size on 8 workers under spawn on macOS. Over two +runs of it, the wall time not spent on leaves, the wall less the leaves' +own seconds over the workers, was 3.5 to 5.1 s with the pool and 4.4 to +6.2 s in waves, on walls of 23 to 69 s that moved more than that from +run to run. Fork on Linux was not measured. + +`window_means` takes the rows of each window once, looks for an +infinite value without copying the rows of the windows, and builds the +frame of the group keys once, where it did all three for every window. +On the benchmark leaf of 4.26 million rows it takes 11% less as the +pipeline calls it, and up to 29% less with the level labels on the +frame. No number moves. Every call the test suite and the benchmarks +make gives what the former code gave, to the bit, with the same row +order and dtypes, and every refusal the same text. + +**The first block of a reduce is measured, and a run sized by the +estimate is refused when the measurement is more than twice it.** The +blocks are sized from an estimate of the bytes a kept row takes, 240 and +40 for each dimension of a leaf, calibrated once on the resident memory +of a worker on one machine. The first block is now built alone in a +worker of its own and measured as the growth of the worker's peak +resident memory over the block, from the peak once the worker has set +itself up, so that what a worker holds for every block is left out. The +manifest records the estimate, the measurement and the setup peak side +by side under `reduce.block_size`. A first block that keeps 100,000 rows +or more and takes more than twice the estimate stops the run before any +other block, with nothing written, and one that keeps fewer is recorded +and not judged. Twice is a tolerance on a measure with known noise, not +a correction of the estimate. One synthetic first block, measured in one +fresh worker after another, read from a fifth of the estimate to nine +tenths of it, and memory sampled through the block peaked where the +measure did, so the spread is in what the block holds resident and not +in the reading. The manifest records the factor beside the measure. On +one worker the block runs in the process that planned the run, whose +peak cannot be put down to it, and a worker whose peak did not rise, as +a forked one can when the block weighs less than what it inherited, says +nothing of the block either. Neither has a measurement or a judgement, +and the manifest says why, and which start method the workers had. The +peak a worker logs is read in bytes on macOS and kibibytes on Linux, +where Linux's was taken as thousands of bytes. New: +`[reduce.pandas] targets_per_block` declares the size of a block in +place of `memory_gb`. It warns, and the manifest records the size as +declared. + **A histclim file with rows its leaf does not have is refused, naming the first row and the regions or years the file alone has.** The two are one projection under two climates, so a row in one alone means the diff --git a/README.md b/README.md index cca78a3..1d1d11c 100644 --- a/README.md +++ b/README.md @@ -623,7 +623,37 @@ n_workers = 16 # run.n_workers unless set ``` `--dry-run` prints the blocks and the number of file opens that -budget gives. Before any work the leaves are checked against their +budget gives. The blocks are sized from an estimate of the bytes a +kept row takes, calibrated on resident memory. The first block is built +alone in a worker of its own, and measured as the growth of that +worker's peak resident memory over the block, from the peak once the +worker has set itself up. The manifest records the estimate and the +measurement side by side under `reduce.block_size`, and the setup peak, +which every worker holds before its first block. A first block that +keeps 100,000 rows or more and takes more than twice the estimate stops +the run, with nothing written, since its blocks could take more than +the budget. Twice, and not once, because the measure is noisy. The same +block, measured in one fresh worker after another, can read from a +fifth of the estimate to nearly all of it. On one worker the blocks +run in the process that planned the run, whose peak includes what it +did before. A forked worker starts from what it inherited, and a block +lighter than that leaves its peak where it was. In both cases the +manifest says there is no measurement and why, and the run is not +judged. + +Someone who has measured their own runs can declare the size of a +block instead, in targets, a whole number of the leaves' row groups: + +```toml +[reduce.pandas] +targets_per_block = 4096 # in place of memory_gb +``` + +A declared size warns, since it overrides the estimate, and the +manifest records it as declared, with the first block's measurement +beside it and not judged. + +Before any work the leaves are checked against their manifest: what aggregated them has to be what the config says, field by field, and every file has to be there with its size. A path is not part of that. If the weights or the tree have moved, the run says so diff --git a/benchmarks/README.md b/benchmarks/README.md index 48e61a8..27280c5 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -75,7 +75,12 @@ time the parts, so a rename there has to be followed here. `test_bench_leaf.py` takes one leaf through `apply_weights` and `window_means` with the labels attached at three different points, and runs a process pool twice over the same leaves: once with 1.4 tasks a -worker and once with every task halved. +worker and once with every task halved. It also runs three waves of +leaves, one a task, through the pool the aggregate stage used, which +renewed each worker after 16 leaves, and through the waves of new +workers that replaced it. The time a leaf takes moves from run to run by +more than the two differ, so it prints the wall time not spent on +leaves beside the wall. It prints the skipped regions and the missing targets once; the pool workers mute the warning the library logs for every leaf. diff --git a/benchmarks/test_bench_leaf.py b/benchmarks/test_bench_leaf.py index dcb7c21..c3c5e97 100644 --- a/benchmarks/test_bench_leaf.py +++ b/benchmarks/test_bench_leaf.py @@ -1,5 +1,6 @@ -"""One leaf through `apply_weights` and `window_means`, and a process -pool run with a coarse and a fine task split. +"""One leaf through `apply_weights` and `window_means`, a process pool +run with a coarse and a fine task split, and the aggregate stage's pool +against the waves that replaced it. The pool runs the same leaves twice, once with about 1.4 tasks a worker and once with every task halved, at whatever worker count the machine @@ -29,7 +30,9 @@ report, source_leaf, ) +from cil_regionalization.pipelines.montecarlo import LEAVES_PER_WORKER from cil_regionalization.stats import window_means +from cil_regionalization.workers import run_in_waves pytestmark = pytest.mark.benchmark @@ -122,3 +125,83 @@ def test_finer_tasks_give_the_same_leaves(): f" {2 * n_coarse} tasks of {half} leaves: {fine_s:.1f} s " f"({fine_s / coarse_s:.0%} of the coarse run)" ) + + +_WORKER: dict = {} + + +def _load_weights() -> None: + """The initializer of both pools. The weights load once a worker, as + the pipeline's do.""" + logging.getLogger("cil_regionalization.validate").setLevel(logging.ERROR) + _WORKER["art"] = artifact(POOL_SCALE) + + +def _one_leaf(seed: int) -> tuple[int, int, float, float]: + """The leaf's row count and sum, and the seconds it took in the + worker.""" + start = time.perf_counter() + reduced = window_means(apply(_WORKER["art"], source_leaf(POOL_SCALE, seed)), **_KW) + return seed, len(reduced), float(reduced["pct"].sum()), time.perf_counter() - start + + +def _recycled_pool(seeds: list[int]) -> list: + """What the aggregate stage ran before the waves.""" + with mp.Pool( + processes=POOL_WORKERS, + initializer=_load_weights, + maxtasksperchild=LEAVES_PER_WORKER, + ) as pool: + return sorted(pool.imap_unordered(_one_leaf, seeds, chunksize=1)) + + +def _waves(seeds: list[int]) -> list: + got: list = [] + run_in_waves( + _one_leaf, + seeds, + n_workers=POOL_WORKERS, + per_worker=LEAVES_PER_WORKER, + initializer=_load_weights, + initargs=(), + on_result=got.append, + name=str, + what="benchmark", + ) + return sorted(got) + + +def test_waves_give_what_the_recycled_pool_gave(): + """Three waves of leaves, one a task, under the platform's start + method, each run twice and alternating. The time a leaf takes moves + from one run to the next on a laptop by more than the pools differ, + so what is compared is the wall time not spent on leaves, the wall + less the leaves' own seconds over the workers.""" + seeds = list(range(3 * POOL_WORKERS * LEAVES_PER_WORKER)) + runs: dict[str, list[tuple[float, float]]] = {"pool": [], "waves": []} + results = {} + for _ in range(2): + for key, run in (("pool", _recycled_pool), ("waves", _waves)): + start = time.perf_counter() + got = run(seeds) + wall = time.perf_counter() - start + runs[key].append((wall, wall - sum(r[3] for r in got) / POOL_WORKERS)) + results[key] = [r[:3] for r in got] + assert results["waves"] == results["pool"] + + report( + f"{len(seeds)} leaves at 1/{POOL_SCALE} size on {POOL_WORKERS} " + f"workers, {LEAVES_PER_WORKER} a worker, " + f"{mp.get_start_method()} start" + ) + for key, label in ( + ("pool", "pool renewing each worker after its leaves"), + ("waves", "waves of new workers"), + ): + report( + f" {label + ':':<44} wall " + + ", ".join(f"{wall:.1f}" for wall, _ in runs[key]) + + " s, not on leaves " + + ", ".join(f"{other:.1f}" for _, other in runs[key]) + + " s" + ) diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index 5378d21..0b9ff78 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -93,7 +93,6 @@ import hashlib import itertools import json -import multiprocessing as mp import os import sys import warnings @@ -141,11 +140,16 @@ members_that_join, read_gmst, ) +from cil_regionalization.workers import WorkerDied, run_in_waves VariableKind = Literal["extensive", "intensive", "ratio"] # in a cell of tree.exclude, every value of the level EVERY_VALUE = "*" +# The leaves a worker takes on average before new workers start, in +# waves of n_workers times this many. A worker's resident memory grows +# with the leaves it has processed, so the workers are renewed. +LEAVES_PER_WORKER = 16 Stage = Literal["all", "aggregate", "reduce"] @@ -585,6 +589,11 @@ class PipelineOutputConfig(_Strict): class RunConfig(_Strict): + """``n_workers`` processes aggregate the leaves in waves, each wave on + new workers, since a worker's resident memory grows with the leaves + it has taken. A worker that dies stops the run, naming the leaves in + flight and saying how the workers ended.""" + n_workers: int = Field(default=1, ge=1) @@ -1016,25 +1025,42 @@ def collect(outcome: dict) -> None: # The artifact loads once per worker (initializer), not once per # task: shipping it in every task pickle made long-lived workers # churn through thousands of unpickled copies, and their resident - # memory grew with leaves processed. maxtasksperchild recycles - # workers to bound what churn remains; chunksize=1 so recycling - # counts actual leaves. imap_unordered streams results so memory - # can be logged as the run accumulates. + # memory grew with leaves processed. New workers for every wave of + # LEAVES_PER_WORKER leaves a worker bound what churn remains. A + # worker that dies stops the run, where a multiprocessing.Pool + # waited for ever for the leaf it held. worker_peak = 0.0 - with mp.Pool( - processes=cfg.run.n_workers, - initializer=_init_worker, - initargs=initargs, - maxtasksperchild=16, - ) as pool: - for outcome in pool.imap_unordered(_process_leaf, tasks, chunksize=1): - collect(outcome) - worker_peak = max(worker_peak, outcome.get("worker_peak_gb") or 0.0) - if len(outcomes) % 250 == 0 or len(outcomes) == len(tasks): - _log_memory( - f"leaves {len(outcomes)}/{len(tasks)}, " - f"max worker peak {worker_peak:.1f}G" - ) + + def take(outcome: dict) -> None: + nonlocal worker_peak + collect(outcome) + worker_peak = max(worker_peak, outcome.get("worker_peak_gb") or 0.0) + if len(outcomes) % 250 == 0 or len(outcomes) == len(tasks): + _log_memory( + f"leaves {len(outcomes)}/{len(tasks)}, " + f"max worker peak {worker_peak:.1f}G" + ) + + try: + run_in_waves( + _process_leaf, + tasks, + n_workers=cfg.run.n_workers, + per_worker=LEAVES_PER_WORKER, + initializer=_init_worker, + initargs=initargs, + on_result=take, + name=lambda task: "/".join(task[0].values), + what="pipeline", + ) + except WorkerDied as error: + kept = ( + " The leaf files written so far are kept, and the leaves " + "manifest is left incomplete." + if leaves_document is not None + else "" + ) + raise WorkerDied(f"{error} No statistics were written.{kept}") from None _log_memory("all leaves collected") failures = [o for o in outcomes if o["error"] is not None] diff --git a/cil_regionalization/reduce/base.py b/cil_regionalization/reduce/base.py index 72f39b9..39d2fb3 100644 --- a/cil_regionalization/reduce/base.py +++ b/cil_regionalization/reduce/base.py @@ -14,7 +14,7 @@ from typing import Literal, Optional import pandas as pd -from pydantic import Field +from pydantic import Field, model_validator from cil_regionalization.config import _Strict @@ -27,12 +27,27 @@ class PandasReduceOptions(_Strict): """Options of the pandas backend. ``memory_gb`` is the memory all - its workers may hold together and has no default. ``n_workers`` - defaults to ``run.n_workers``.""" + its workers may hold together, which the blocks are sized from, and + ``targets_per_block`` declares their size instead. One of the two is + needed and neither has a default. ``n_workers`` defaults to + ``run.n_workers``.""" memory_gb: Optional[float] = Field(default=None, gt=0) + # A whole number of the leaves' row groups. For an expert who has + # measured a run, and the manifest records it as declared. + targets_per_block: Optional[int] = Field(default=None, ge=1) n_workers: Optional[int] = Field(default=None, ge=1) + @model_validator(mode="after") + def _one_way_to_size_the_blocks(self) -> "PandasReduceOptions": + if self.memory_gb is not None and self.targets_per_block is not None: + raise ValueError( + "[reduce.pandas] takes memory_gb, which the blocks are sized " + "from, or targets_per_block, which declares their size, not " + "both" + ) + return self + class ReduceConfig(_Strict): kind: Literal["pandas"] = "pandas" diff --git a/cil_regionalization/reduce/pandas_blocks.py b/cil_regionalization/reduce/pandas_blocks.py index a2fa202..2cee5d6 100644 --- a/cil_regionalization/reduce/pandas_blocks.py +++ b/cil_regionalization/reduce/pandas_blocks.py @@ -2,9 +2,20 @@ a time. A block is a run of consecutive row groups, sized so that a worker is -planned to hold no more than its share of ``memory_gb``. A worker reads -its block from every leaf file and pools it with -`stats.pooled_statistics`, so the numbers are those of `stats`. +planned to hold no more than its share of ``memory_gb``, or of the size +``targets_per_block`` declares. A worker reads its block from every leaf +file and pools it with `stats.pooled_statistics`, so the numbers are +those of `stats`. + +The size of a block rests on an estimate of the bytes a kept row takes, +calibrated on resident memory. The first block is built alone, in a +worker of its own, and measured as the growth of that worker's peak +resident memory, and the manifest records the estimate and the +measurement side by side. A run sized by the estimate is refused when +the measurement of a block large enough to judge is more than twice the +estimate. In a single process that has already done other work the peak +cannot be put down to the block, so there is no measurement and no +judgement. """ # `stats.pooled_statistics` needs every member of a target at once and @@ -13,6 +24,7 @@ from __future__ import annotations +import multiprocessing import os import sys import warnings @@ -37,6 +49,7 @@ pooled_statistics, window_means, ) +from cil_regionalization.workers import WorkerDied, shut_down_broken # What a block is planned to take for a row it keeps, and for each # dimension that row has of its own. They come from the resident memory @@ -50,6 +63,38 @@ # it had to be costs opens. BYTES_PER_ROW = 240 BYTES_PER_DIMENSION = 40 +# The kept rows a first block needs for its measurement to be judged. +# Below it the fixed cost of pooling a block outweighs what its rows +# take, and the measurement is recorded and not judged. +JUDGED_ROWS = 100_000 +# A first block is refused when it takes more than this many times the +# estimate a kept row. It is a tolerance on a measure with known noise, +# not a correction of the estimate. One synthetic first block, measured +# in one fresh worker after another, read from a fifth of the estimate +# to nine tenths of it. Memory sampled through the block peaked where +# the measure did, so the spread is in what the block holds resident and +# not in the reading. Twice refuses a block far heavier than the +# estimate and not that spread. The manifest records the measure of +# every run, so runs on real data can tighten it. +REFUSED_ABOVE = 2 +# The unit ru_maxrss counts in, bytes on macOS and kibibytes on Linux. +# On a platform not listed the peak is not read, rather than guessed. +_RU_MAXRSS_UNIT = {"darwin": 1, "linux": 1024} +# Why a first block run in the process that planned the run has no +# measurement. +_SHARED_PEAK = ( + "the first block ran in the process that planned the run, whose peak " + "resident memory includes what it did before, so the block's share of " + "the peak cannot be told" +) +# Why a worker whose peak did not rise has none either. A forked worker +# starts from what it inherited, and a block lighter than that leaves +# the peak where it was. +_FLAT_PEAK = ( + "the worker's peak resident memory did not rise above the peak it " + "started from, so the block weighed less than what the worker inherited " + "and the peak says nothing of it" +) def bytes_per_row(request: ReduceRequest) -> int: @@ -110,6 +155,22 @@ def choose_blocks( return blocks +def fixed_blocks(rows_per_group, groups_per_block: int) -> list[tuple[int, int]]: + """Consecutive row groups in blocks of ``groups_per_block``, as + (first, stop) pairs. The empty groups before the first that holds + rows are left out, as in `choose_blocks`, and the last block may be + shorter.""" + rows = np.asarray(rows_per_group, dtype=np.float64) + held = np.flatnonzero(rows > 0) + if not len(held): + return [] + start, end = int(held[0]), len(rows) + return [ + (first, min(first + groups_per_block, end)) + for first in range(start, end, groups_per_block) + ] + + class _TooSmall(ValueError): def __init__(self, largest_group: float) -> None: super().__init__(largest_group) @@ -123,19 +184,43 @@ def __init__(self, options: PandasReduceOptions | None = None) -> None: self.options = options or PandasReduceOptions() def check_options(self) -> None: - if self.options.memory_gb is None: + if self.options.memory_gb is None and self.options.targets_per_block is None: raise ValueError( "reducing leaves by blocks needs a memory budget. Set " "[reduce.pandas] memory_gb to what all the workers may " - "hold together." + "hold together, or declare the size of a block in " + "targets_per_block." ) def _plan(self, request: ReduceRequest) -> dict: self.check_options() n_workers = self.options.n_workers or request.n_workers - per_worker = self.options.memory_gb * 1e9 / n_workers share = kept_share(request) row_bytes = bytes_per_row(request) + kept = np.asarray(request.rows_per_group, dtype=np.float64) * share + declared = self.options.targets_per_block + if declared is not None: + per_group = request.footer["targets_per_group"] + if declared % per_group: + raise ValueError( + f"[reduce.pandas] targets_per_block = {declared} is not a " + f"whole number of the leaves' row groups, which hold " + f"{per_group} targets each" + ) + blocks = fixed_blocks(request.rows_per_group, declared // per_group) + return { + "by": "declared", + "blocks": blocks, + "n_workers": max(1, min(n_workers, len(blocks))), + "per_worker_gb": None, + "share": share, + "row_bytes": row_bytes, + "rows_in_largest_block": int( + max((kept[a:b].sum() for a, b in blocks), default=0) + ), + "groups_in_largest_block": max((b - a for a, b in blocks), default=0), + } + per_worker = self.options.memory_gb * 1e9 / n_workers try: blocks = choose_blocks(request.rows_per_group, share, per_worker, row_bytes) except _TooSmall as error: @@ -148,8 +233,8 @@ def _plan(self, request: ReduceRequest) -> dict: f"smallest budget that runs with {n_workers} workers is " f"{needed:.3g} GB." ) from None - kept = np.asarray(request.rows_per_group, dtype=np.float64) * share return { + "by": "estimate", "blocks": blocks, "n_workers": max(1, min(n_workers, len(blocks))), "per_worker_gb": per_worker / 1e9, @@ -165,11 +250,45 @@ def describe(self, request: ReduceRequest) -> dict: plan = self._plan(request) per_group = request.footer["targets_per_group"] n_blocks, n_leaves = len(plan["blocks"]), len(request.leaves) + declared = plan["by"] == "declared" + if declared: + budget = ( + f"reduce: pandas, blocks of {self.options.targets_per_block} " + f"targets as declared, over {plan['n_workers']} workers" + ) + sized = ( + " sized as declared, not from memory_gb. The first block is " + "measured, and the measurement is recorded and not judged." + ) + else: + budget = ( + f"reduce: pandas, {self.options.memory_gb:g} GB over " + f"{plan['n_workers']} workers, " + f"{plan['per_worker_gb']:.3g} GB a worker" + ) + sized = ( + f" sized at {plan['row_bytes']} bytes a row, " + + ( + f"{BYTES_PER_ROW} and {BYTES_PER_DIMENSION} for each " + f"dimension of a leaf, " + if request.dimensions + else "" + ) + + f"with " + f"{plan['share']:.4g} of a group's rows kept" + f"{', each with its year' if request.time_reduction != 'window_mean' else ''}. " + f"The rows of a " + f"group are known summed over the leaves, so this takes " + f"every leaf to spread its rows over the groups alike. The " + f"first block is measured in a worker of its own, and the run " + f"is refused if it takes more than {REFUSED_ABOVE} times that." + ) return { "kind": self.kind, "engine": collect_package_versions(("pandas", "numpy", "pyarrow")), "options": { "memory_gb": self.options.memory_gb, + "targets_per_block": self.options.targets_per_block, "n_workers": plan["n_workers"], }, "blocks": n_blocks, @@ -181,38 +300,43 @@ def describe(self, request: ReduceRequest) -> dict: "bytes_per_row": plan["row_bytes"], "kept_share": plan["share"], "text": [ - f"reduce: pandas, {self.options.memory_gb:g} GB over " - f"{plan['n_workers']} workers, " - f"{plan['per_worker_gb']:.3g} GB a worker", + budget, f" {n_blocks} blocks of up to " f"{plan['groups_in_largest_block'] * per_group} targets and " f"{plan['rows_in_largest_block']:,} rows", f" {n_blocks} opens a leaf, {n_blocks * n_leaves:,} in all", - f" sized at {plan['row_bytes']} bytes a row, " - + ( - f"{BYTES_PER_ROW} and {BYTES_PER_DIMENSION} for each " - f"dimension of a leaf, " - if request.dimensions - else "" - ) - + f"with " - f"{plan['share']:.4g} of a group's rows kept" - f"{', each with its year' if request.time_reduction != 'window_mean' else ''}. " - f"The rows of a " - f"group are known summed over the leaves, so this takes " - f"every leaf to spread its rows over the groups alike.", + sized, ], } def run(self, request: ReduceRequest) -> tuple[pd.DataFrame, dict]: plan = self._plan(request) - results = _run_blocks(request, plan["blocks"], plan["n_workers"]) + if plan["by"] == "declared": + warnings.warn( + f"[reduce.pandas] targets_per_block = " + f"{self.options.targets_per_block} declares the size of a " + f"block, so the blocks are not sized from a memory budget, " + f"and the measurement of the first block is recorded and not " + f"judged", + UserWarning, + stacklevel=2, + ) + sizing: dict = {} + + def judge(first: dict) -> None: + sizing.update(_block_size_record(request, plan, first)) + if sizing["refused"]: + raise ValueError(_too_heavy(request, plan, sizing)) + + results = _run_blocks(request, plan["blocks"], plan["n_workers"], judge) frames = [r["stats"] for r in results if len(r["stats"])] if not frames: raise ValueError("reduce: the leaves hold no row inside any window") stats = pd.concat(frames, ignore_index=True) + sizing.pop("refused", None) report = { **{k: v for k, v in self.describe(request).items() if k != "text"}, + "block_size": sizing, "failed_opens": sum(r["failed_opens"] for r in results), "max_worker_peak_gb": max(r["peak_gb"] for r in results), "rows_pooled": sum(r["rows"] for r in results), @@ -220,42 +344,179 @@ def run(self, request: ReduceRequest) -> tuple[pd.DataFrame, dict]: return stats[request.columns], report -def _run_blocks(request: ReduceRequest, blocks, n_workers: int) -> list[dict]: - """Every block's result, in any order. The first block that fails - stops the run, and a worker that dies raises `RuntimeError`.""" +def _block_size_record(request: ReduceRequest, plan: dict, first: dict) -> dict: + """The manifest's account of how the blocks were sized, the estimate + and the measurement of the first block side by side, and whether the + run is refused for it. Without a measurement the run is not + judged.""" + rows, growth = first["rows"], first["resident_growth_bytes"] + unavailable = first["measure_unavailable"] + measured = growth / rows if rows and growth is not None else None + judged = ( + plan["by"] == "estimate" + and unavailable is None + and measured is not None + and rows >= JUDGED_ROWS + ) + return { + "by": plan["by"], + "targets_per_block": ( + plan["groups_in_largest_block"] * request.footer["targets_per_group"] + if plan["by"] == "declared" + else None + ), + "estimate_bytes_per_row": plan["row_bytes"], + "measured_bytes_per_row": measured, + "measured_rows": rows, + "measured_growth_bytes": growth, + "worker_setup_peak_bytes": first["worker_setup_peak_bytes"], + "peak_after_block_bytes": first["peak_after_block_bytes"], + "measured_block": list(first["block"]), + "start_method": first["start_method"], + "measure": ( + "the growth of the peak resident memory, ru_maxrss, of the worker " + "that built the first block, from the peak once it had set itself " + "up and before it read the block, to the end of the block" + ), + "unavailable": unavailable, + "judged": judged, + "judged_from_rows": JUDGED_ROWS, + "refused_above": REFUSED_ABOVE, + "refused": judged and measured > REFUSED_ABOVE * plan["row_bytes"], + } + + +def _too_heavy(request: ReduceRequest, plan: dict, sizing: dict) -> str: + """The refusal of a run whose first block took more than + `REFUSED_ABOVE` times the estimate, with the largest declared block + that fits at the measured size.""" + per_group = request.footer["targets_per_group"] + first, stop = sizing["measured_block"] + targets = (stop - first) * per_group + per_target = sizing["measured_growth_bytes"] / targets + fits = int(plan["per_worker_gb"] * 1e9 // per_target) // per_group * per_group + way_out = ( + f"At the measured size a block of {fits} targets fits a worker." + if fits + else f"At the measured size not one row group of {per_group} targets " + f"fits a worker, so memory_gb has to be raised." + ) + return ( + f"reduce: the first block, row groups {first} to {stop - 1}, took " + f"{sizing['measured_bytes_per_row']:.0f} bytes a kept row over " + f"{sizing['measured_rows']:,} rows, more than {REFUSED_ABOVE} times " + f"the {sizing['estimate_bytes_per_row']} bytes a row the blocks were " + f"sized at, so a block can take more than a worker's " + f"{plan['per_worker_gb']:.3g} GB. No statistics were written. The " + f"measure is the growth of the worker's peak resident memory over " + f"the block. Declare the size of a block in " + f"[reduce.pandas] targets_per_block, in place of memory_gb. " + f"{way_out}" + ) + + +def _run_blocks(request: ReduceRequest, blocks, n_workers: int, judge) -> list[dict]: + """Every block's result, in any order. The first block is built + alone and measured, and handed to ``judge``, which may raise, before + any other is. The first block that fails stops the run, and a + worker that dies raises `WorkerDied`.""" # A process pool executor, because a `multiprocessing.Pool` would # wait for ever for a worker that died. + if not blocks: + return [] + first, rest = blocks[0], blocks[1:] if n_workers == 1: - _init_worker(request) - results = [] - for block in blocks: + _init_worker(request, own_process=False) + results = [_measured_block(first)] + results[0]["start_method"] = None + judge(results[0]) + _log_block(results, len(blocks)) + for block in rest: results.append(_reduce_block(block)) _log_block(results, len(blocks)) return results results = [] + # the platform's own, fork on Linux, named so the manifest can say it + context = multiprocessing.get_context() executor = ProcessPoolExecutor( - max_workers=n_workers, initializer=_init_worker, initargs=(request,) + max_workers=n_workers, + mp_context=context, + initializer=_init_worker, + initargs=(request,), ) try: - futures = {executor.submit(_reduce_block, block): block for block in blocks} + results.append( + _collect(executor.submit(_measured_block, first), first, executor) + ) + results[0]["start_method"] = context.get_start_method() + judge(results[0]) + _log_block(results, len(blocks)) + futures = {executor.submit(_reduce_block, block): block for block in rest} for future in as_completed(futures): - first, stop = futures[future] - try: - results.append(future.result()) - except BrokenProcessPool: - raise RuntimeError( - f"reduce: a worker died while row groups {first} to " - f"{stop - 1} were being reduced, most likely killed for " - f"memory. No statistics were written. Raise " - f"[reduce.pandas] memory_gb only if the node has it. " - f"Otherwise lower it, which makes the blocks smaller." - ) from None + results.append(_collect(future, futures[future], executor)) _log_block(results, len(blocks)) finally: executor.shutdown(wait=False, cancel_futures=True) return results +def _collect(future, block, executor) -> dict: + """The result of a block's future. Raises `WorkerDied` if a worker + died, saying how the workers ended, which is not always memory.""" + first, stop = block + try: + return future.result() + except BrokenProcessPool: + ended, killed = shut_down_broken(executor) + memory = ( + " Raise [reduce.pandas] memory_gb only if the node has it. " + "Otherwise lower it, which makes the blocks smaller." + if killed + else "" + ) + # Every block not back fails at once, so this one was not + # necessarily the dead worker's. + raise WorkerDied( + f"reduce: a worker died with row groups {first} to {stop - 1} " + f"among the blocks not back, {ended}. No statistics were " + f"written.{memory}" + ) from None + + +def _measured_block(block: tuple[int, int]) -> dict: + """`_reduce_block`, with the growth of the process's peak resident + memory over the block under 'resident_growth_bytes', or None and the + reason under 'measure_unavailable'. The growth is taken from the peak + once the worker has set itself up and before it reads the block, so + what the worker holds for every block, its imports and its target + table, is outside it.""" + setup = _peak_resident_bytes() + result = _reduce_block(block) + peak = _peak_resident_bytes() + growth, unavailable = _growth(setup, peak, _STATE["own_process"]) + result.update( + worker_setup_peak_bytes=setup, + peak_after_block_bytes=peak, + resident_growth_bytes=growth, + measure_unavailable=unavailable, + ) + return result + + +def _growth( + started: int | None, peak: int | None, own_process: bool +) -> tuple[int | None, str | None]: + """The growth of the peak resident memory over the first block, or + None and why it cannot be read off the peak.""" + if not own_process: + return None, _SHARED_PEAK + if started is None or peak is None: + return None, f"the unit of ru_maxrss on {sys.platform} is not known here" + if peak <= started: + return None, _FLAT_PEAK + return peak - started, None + + def _log_block(results: list[dict], n_blocks: int) -> None: last = results[-1] print( @@ -269,7 +530,11 @@ def _log_block(results: list[dict], n_blocks: int) -> None: _STATE: dict = {} -def _init_worker(request: ReduceRequest) -> None: +def _init_worker(request: ReduceRequest, own_process: bool = True) -> None: + """Load what every block needs. ``own_process`` is False where the + blocks run in the process that planned the run, whose peak resident + memory is not the worker's own.""" + _STATE.update(own_process=own_process) targets = leaf_format.TargetTable.read( Path(request.leaves_root) / request.targets_file ) @@ -281,11 +546,23 @@ def _init_worker(request: ReduceRequest) -> None: _STATE.update(request=request, targets=targets) -def _peak_gb() -> float: +def _peak_resident_bytes() -> int | None: + """This process's peak resident memory in bytes, from ru_maxrss, or + None on a platform whose unit of it is not in `_RU_MAXRSS_UNIT`.""" import resource - peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - return peak / 1e6 if sys.platform.startswith("linux") else peak / 1e9 + unit = next( + (u for name, u in _RU_MAXRSS_UNIT.items() if sys.platform.startswith(name)), + None, + ) + if unit is None: + return None + return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit + + +def _peak_gb() -> float: + peak = _peak_resident_bytes() + return float("nan") if peak is None else peak / 1e9 def _leaf_rows( diff --git a/cil_regionalization/stats.py b/cil_regionalization/stats.py index 95080ac..f471384 100644 --- a/cil_regionalization/stats.py +++ b/cil_regionalization/stats.py @@ -843,10 +843,15 @@ def _refuse_infinite_statistics( ) -def _refuse_infinite_values(data: pd.DataFrame, value_col: str) -> None: +def _refuse_infinite_values( + data: pd.DataFrame, value_col: str, rows: np.ndarray | None = None +) -> None: """Raise if a member value is infinite, under every quantile method - and summation, naming the first such row by its other columns.""" + and summation, naming the first such row by its other columns. + ``rows`` is a mask of the rows to look at, every row if it is None.""" infinite = np.isinf(_float_values(data[value_col])) + if rows is not None: + infinite &= rows if not infinite.any(): return first = data.loc[infinite].iloc[0].drop(value_col).to_dict() @@ -1079,12 +1084,10 @@ def window_means( if len(set(labels)) != len(labels): raise ValueError(f"duplicate window labels in request: {labels}") - _refuse_infinite_values( - data.loc[ - np.logical_or.reduce([data[time_col].between(lo, hi) for lo, hi in windows]) - ], - value_col, - ) + # the rows of each window, worked out once for the check of the + # values and for the means + in_window = [data[time_col].between(lo, hi).to_numpy() for lo, hi in windows] + _refuse_infinite_values(data, value_col, rows=np.logical_or.reduce(in_window)) group = [c for c in data.columns if c not in (time_col, value_col)] full_key = group + [time_col] # The group codes are worked out once and serve the duplicate check @@ -1111,9 +1114,13 @@ def window_means( # afterwards is a float64 that holds seven digits values = pd.Series(_float_values(values), index=values.index) floats = values.to_numpy() if summation == "exact" else None + # the key frame a groupby over the columns returns (it infers + # key dtypes), one row a group in order of first appearance, for + # every window to take its groups from + key_frame = None pieces: list[pd.DataFrame] = [] - for (lo, hi), label in zip(windows, labels): - mask = data[time_col].between(lo, hi).to_numpy() + for (lo, hi), label, rows in zip(windows, labels, in_window): + mask = rows if not mask.any(): raise ValueError( f"window ({lo}, {hi}) on {time_col!r} selects no rows " @@ -1125,7 +1132,7 @@ def window_means( # no group columns (groupby raises), or every row in the window # misses a key: the groupby over the columns, as it always ran piece = ( - data.loc[data[time_col].between(lo, hi)] + data.loc[rows] .groupby(group, sort=False, observed=True)[value_col] .mean() .reset_index() @@ -1139,15 +1146,14 @@ def window_means( means = pd.Series(exact[ids], index=ids) else: means = values[mask].groupby(gid[mask], sort=False).mean() - # the key frame a groupby over the columns returns (it infers - # key dtypes), from one row per group in this window's order - piece = ( - keys.take(means.index.to_numpy()) - .assign(**{value_col: 0.0}) - .groupby(group, sort=False, observed=True)[value_col] - .first() - .reset_index() - ) + if key_frame is None: + key_frame = ( + keys.assign(**{value_col: 0.0}) + .groupby(group, sort=False, observed=True)[value_col] + .first() + .reset_index() + ) + piece = key_frame.take(means.index.to_numpy()).reset_index(drop=True) piece[value_col] = means.reset_index(drop=True) piece[window_col] = label pieces.append(piece) diff --git a/cil_regionalization/workers.py b/cil_regionalization/workers.py new file mode 100644 index 0000000..993a1fe --- /dev/null +++ b/cil_regionalization/workers.py @@ -0,0 +1,129 @@ +"""Process pools that stop when a worker dies. + +A worker that dies outright, killed by a signal or ending while it sets +itself up, leaves a `multiprocessing.Pool` waiting for ever for the task +it held. A `ProcessPoolExecutor` raises `BrokenProcessPool` instead. +`run_in_waves` runs tasks on one, under the platform's own start method, +with new workers for every wave of tasks so that none lives for more +than its wave. `shut_down_broken` ends a broken pool and says how its +workers ended, from their exit codes. +""" + +# The executor's own recycling, max_tasks_per_child, refuses the fork +# start method and does not exist on Python 3.10, so the workers are +# renewed by starting a new executor for each wave instead. + +from __future__ import annotations + +import itertools +import multiprocessing +import signal +from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait +from concurrent.futures.process import BrokenProcessPool +from typing import Any, Callable, Sequence + + +class WorkerDied(RuntimeError): + """A worker of a pool ended without handing back its task.""" + + +def run_in_waves( + fn: Callable[[Any], Any], + tasks: Sequence[Any], + *, + n_workers: int, + per_worker: int, + initializer: Callable[..., None], + initargs: tuple, + on_result: Callable[[Any], None], + name: Callable[[Any], str], + what: str, +) -> None: + """``fn`` of every task, each result handed to ``on_result`` as it + comes back. The tasks run in waves of ``n_workers * per_worker``, + each on new workers set up by ``initializer``, so a worker takes + ``per_worker`` tasks on average and at most a wave. No more tasks + are handed out than there are workers, so a worker that dies raises + `WorkerDied` naming by ``name`` every task in flight, and saying how + the workers ended.""" + wave = n_workers * per_worker + context = multiprocessing.get_context() + for start in range(0, len(tasks), wave): + batch = iter(tasks[start : start + wave]) + executor = ProcessPoolExecutor( + max_workers=min(n_workers, len(tasks) - start), + mp_context=context, + initializer=initializer, + initargs=initargs, + ) + try: + out: dict = {} + for task in itertools.islice(batch, n_workers): + out[executor.submit(fn, task)] = task + while out: + done, _ = wait(out, return_when=FIRST_COMPLETED) + for future in done: + if not isinstance(future.exception(), BrokenProcessPool): + del out[future] + on_result(future.result()) + if any(future in out for future in done): + ended, _ = shut_down_broken(executor) + held = [name(task) for task in out.values()] + raise WorkerDied( + f"{what}: a worker died with {_and(held)} in flight, " + f"{ended}. The run stopped there." + ) from None + for task in itertools.islice(batch, n_workers - len(out)): + out[executor.submit(fn, task)] = task + finally: + executor.shutdown(wait=True, cancel_futures=True) + + +def _and(names: list[str]) -> str: + return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}" + + +def shut_down_broken(executor: ProcessPoolExecutor) -> tuple[str, bool]: + """Shut a broken executor down, and say how its workers ended from + their exit codes, with whether one was killed by SIGKILL. The pool + stops the workers still alive with SIGTERM when one dies, so those + are told apart.""" + # The process table is private and shutting down empties it, so the + # workers are taken from it first and their exit codes read after. + workers = list((getattr(executor, "_processes", None) or {}).values()) + executor.shutdown(wait=True) + for worker in workers: + worker.join(timeout=5) + codes = [w.exitcode for w in workers if w.exitcode is not None] + return how_workers_ended(codes), -signal.SIGKILL in codes + + +def how_workers_ended(codes: Sequence[int]) -> str: + """How the workers of a broken pool ended, from their exit codes.""" + stopped = list(codes).count(-signal.SIGTERM) + ended = [code for code in codes if code != -signal.SIGTERM] + if not codes: + return "and its exit code could not be read" + if not ended: + return f"{_ended(-signal.SIGTERM)}, as {stopped} workers did" + told = "; ".join(_ended(code) for code in ended) + if stopped: + told += f", and the pool then stopped the other {stopped} with SIGTERM" + return told + + +def _ended(code: int) -> str: + if code == 0: + return ( + "exiting with code 0 before it handed back a task, as a worker " + "does whose setup raised, which logs the traceback" + ) + if code > 0: + return f"exiting with code {code}" + try: + name = signal.Signals(-code).name + except ValueError: + name = f"signal {-code}" + if -code == signal.SIGKILL: + return f"killed by {name}, which is how an out-of-memory kill ends a process" + return f"killed by {name}" diff --git a/docs/reference.md b/docs/reference.md index 0470e72..0b3de09 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1458,6 +1458,11 @@ weights gave them. Can be left out. +``n_workers`` processes aggregate the leaves in waves, each wave on +new workers, since a worker's resident memory grows with the leaves +it has taken. A worker that dies stops the run, naming the leaves in +flight and saying how the workers ended. + | key | type | default | | --- | --- | --- | | `n_workers` | int, at least 1 | 1 | @@ -1475,10 +1480,13 @@ Can be left out. Can be left out. Options of the pandas backend. ``memory_gb`` is the memory all -its workers may hold together and has no default. ``n_workers`` -defaults to ``run.n_workers``. +its workers may hold together, which the blocks are sized from, and +``targets_per_block`` declares their size instead. One of the two is +needed and neither has a default. ``n_workers`` defaults to +``run.n_workers``. | key | type | default | | --- | --- | --- | | `memory_gb` | float, above 0 | not set | +| `targets_per_block` | int, at least 1 | not set | | `n_workers` | int, at least 1 | not set | diff --git a/examples/montecarlo/pipeline_example.toml b/examples/montecarlo/pipeline_example.toml index 41201a5..165cbcd 100644 --- a/examples/montecarlo/pipeline_example.toml +++ b/examples/montecarlo/pipeline_example.toml @@ -94,6 +94,7 @@ n_workers = 1 # the years. It # takes the statistics from the leaves under pipeline_out/leaves, one # block of targets at a time, and memory_gb is what all its workers may -# hold together. +# hold together. targets_per_block declares the size of a block in its +# place, and warns. [reduce.pandas] memory_gb = 4 diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index 09e2a91..2d04028 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -155,6 +155,104 @@ def _pipeline_cfg( _LEVELS = {"kumquat": ["k0", "k1"], "zeppelin": ["z0", "z1", "z2"]} +def _last_first_waves(fn, tasks, *, initializer, initargs, on_result, **_): + """In place of `run_in_waves`: in this process, the leaves handed back + last first, each as soon as it is done.""" + initializer(*initargs) + for task in reversed(list(tasks)): + on_result(fn(task)) + + +def _dies(task): + import os + + os._exit(1) + + +class TestWaves: + """The leaves are aggregated in waves, each on new workers.""" + + def test_waves_of_two_give_what_one_worker_gives( + self, weights_dir, tmp_path, monkeypatch + ): + """Six leaves over two workers in waves of two, so three waves.""" + from cil_regionalization.pipelines import montecarlo + + tree = tmp_path / "tree" + _build_tree(tree, _LEVELS) + one = run_pipeline( + _pipeline_cfg(weights_dir, tree, tmp_path / "one", levels=_LEVELS) + ) + monkeypatch.setattr(montecarlo, "LEAVES_PER_WORKER", 1) + waves = run_pipeline( + _pipeline_cfg( + weights_dir, tree, tmp_path / "waves", levels=_LEVELS, n_workers=2 + ) + ) + pd.testing.assert_frame_equal( + waves.stats, one.stats, check_exact=False, rtol=1e-12 + ) + + def test_a_worker_that_dies_stops_the_run_with_nothing_written( + self, weights_dir, tmp_path, monkeypatch + ): + """It hung on a multiprocessing.Pool, which waits for ever for the + leaf a dead worker held. The workers here are forked, so that they + see the leaf function this test puts in.""" + import multiprocessing + + from cil_regionalization.pipelines import montecarlo + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("needs forked workers") + tree, out = tmp_path / "tree", tmp_path / "out" + _build_tree(tree, _LEVELS) + monkeypatch.setattr(montecarlo, "_process_leaf", _dies) + before = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method("fork", force=True) + try: + with pytest.raises(RuntimeError) as error: + run_pipeline( + _pipeline_cfg(weights_dir, tree, out, levels=_LEVELS, n_workers=2) + ) + finally: + multiprocessing.set_start_method(before, force=True) + message = str(error.value) + # two workers, so the first two leaves of the plan were out + assert message.startswith( + "pipeline: a worker died with k0/z0 and k0/z1 in flight, exiting " + "with code 1" + ), message + assert message.endswith("The run stopped there. No statistics were written.") + assert not out.exists() or not any(out.rglob("*.parquet")) + + def test_a_worker_that_dies_leaves_the_leaves_manifest_incomplete( + self, weights_dir, tmp_path, monkeypatch + ): + """With leaf files written, the message says what is left on disk.""" + import multiprocessing + + from cil_regionalization.pipelines import montecarlo + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("needs forked workers") + tree, out = tmp_path / "tree", tmp_path / "out" + _build_tree(tree, _LEVELS) + monkeypatch.setattr(montecarlo, "_process_leaf", _dies) + before = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method("fork", force=True) + try: + with pytest.raises(RuntimeError) as error: + run_pipeline(_leaves_cfg(weights_dir, tree, out, n_workers=2)) + finally: + multiprocessing.set_start_method(before, force=True) + assert str(error.value).endswith( + "No statistics were written. The leaf files written so far are " + "kept, and the leaves manifest is left incomplete." + ) + assert _leaves_manifest(out)["complete"] is False + + class TestEndToEnd: def test_generation_application_statistics(self, weights_dir, tmp_path): tree = tmp_path / "tree" @@ -495,24 +593,10 @@ def test_rows_follow_the_config_not_the_arrival( ): """Both files come in the order of `_ordered`. The pool here runs in this process and hands the leaves back last first.""" - import types from cil_regionalization.pipelines import montecarlo - class LastFirstPool: - def __init__(self, processes, initializer, initargs, maxtasksperchild): - initializer(*initargs) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def imap_unordered(self, func, tasks, chunksize=1): - return [func(task) for task in reversed(list(tasks))] - - monkeypatch.setattr(montecarlo, "mp", types.SimpleNamespace(Pool=LastFirstPool)) + monkeypatch.setattr(montecarlo, "run_in_waves", _last_first_waves) tree = tmp_path / "tree" _build_tree(tree, self._ORDER_LEVELS) raw = self._cfg( @@ -1983,25 +2067,11 @@ def test_the_manifest_lists_every_leaf_in_plan_order( ): """The pool here runs in this process and hands the leaves back last first.""" - import types from cil_regionalization import leaves from cil_regionalization.pipelines import montecarlo - class LastFirstPool: - def __init__(self, processes, initializer, initargs, maxtasksperchild): - initializer(*initargs) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def imap_unordered(self, func, tasks, chunksize=1): - return [func(task) for task in reversed(list(tasks))] - - monkeypatch.setattr(montecarlo, "mp", types.SimpleNamespace(Pool=LastFirstPool)) + monkeypatch.setattr(montecarlo, "run_in_waves", _last_first_waves) tree, out = tmp_path / "tree", tmp_path / "out" _build_tree(tree, _LEVELS) run_pipeline(_leaves_cfg(weights_dir, tree, out, n_workers=2)) @@ -2417,24 +2487,10 @@ def test_the_first_leaf_to_arrive_fixes_the_columns( """Not the first in plan order. The pool here runs in this process and hands each leaf back as it is asked for, last first, so the odd leaf is the third to arrive.""" - import types from cil_regionalization.pipelines import montecarlo - class LastFirstPool: - def __init__(self, processes, initializer, initargs, maxtasksperchild): - initializer(*initargs) - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def imap_unordered(self, func, tasks, chunksize=1): - return (func(task) for task in reversed(list(tasks))) - - monkeypatch.setattr(montecarlo, "mp", types.SimpleNamespace(Pool=LastFirstPool)) + monkeypatch.setattr(montecarlo, "run_in_waves", _last_first_waves) tree, out = tmp_path / "tree", tmp_path / "out" _build_tree(tree, _LEVELS) path = tree / "k1" / "z0" / "damages.parquet" @@ -2722,6 +2778,52 @@ def run(*flags): _ONE_GROUP_GB = 7000e-9 +@pytest.fixture +def spawned_workers(): + """Workers started by spawn, for the test that reads a worker's real + peak resident memory over its first block. On macOS such a worker's + peak starts from its own setup. On Linux it starts from the peak of + the process that started it, so a small block reads nothing there. + Runs keep the platform's own start method.""" + import multiprocessing + + before = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method("spawn", force=True) + yield + multiprocessing.set_start_method(before, force=True) + + +def _forked_workers(monkeypatch, peak): + """Forked workers, which keep what a test puts in, reading their peak + resident memory from ``peak``.""" + import multiprocessing + + from cil_regionalization.reduce import pandas_blocks + + if "fork" not in multiprocessing.get_all_start_methods(): + pytest.skip("needs forked workers") + monkeypatch.setattr(pandas_blocks, "_peak_resident_bytes", peak) + before = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method("fork", force=True) + yield + multiprocessing.set_start_method(before, force=True) + + +@pytest.fixture +def forked_workers_with_a_rising_peak(monkeypatch): + """A peak that rises with every reading. A block this small can leave + the real peak where it was, and then there is nothing to judge.""" + readings = itertools.count(1) + yield from _forked_workers(monkeypatch, lambda: 10**9 + 10**4 * next(readings)) + + +@pytest.fixture +def forked_workers_with_a_flat_peak(monkeypatch): + """A peak that never rises, as on Linux over a block lighter than the + peak of the process the worker came from.""" + yield from _forked_workers(monkeypatch, lambda: 10**9) + + def _same_frames(one: pd.DataFrame, two: pd.DataFrame) -> None: """Equal with their dtypes and row order, and to the bit.""" pd.testing.assert_frame_equal(one, two, check_exact=True) @@ -2990,9 +3092,190 @@ def test_two_workers_give_the_same_bits(self, weights_dir, tmp_path): assert manifest["reduce"]["blocks"] == 2 assert manifest["reduce"]["options"] == { "memory_gb": 2 * _ONE_GROUP_GB, + "targets_per_block": None, "n_workers": 2, } + @pytest.mark.usefixtures("spawned_workers") + def test_the_estimate_and_the_measurement_are_recorded_side_by_side( + self, weights_dir, tmp_path + ): + """The first block is built alone in a worker and measured as the + growth of its peak resident memory over the block. A block this + small can leave the peak where it was, at the worker's setup or on + Linux at the peak of the process that started it, and then the + record says so. Either way it is below what is + judged, so it is recorded and not judged. It went red with + nothing measured.""" + from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK + + raw, whole, out = self._aggregated(weights_dir, tmp_path) + got = self._reduce(raw, memory_gb=2 * _ONE_GROUP_GB, n_workers=2) + _same_frames(got.stats, whole.stats) + sizing = json.loads((out / "again.manifest.json").read_text())["reduce"][ + "block_size" + ] + assert sizing["by"] == "estimate" and sizing["targets_per_block"] is None + assert sizing["estimate_bytes_per_row"] == 280 + assert sizing["measured_rows"] == 24 and sizing["measured_block"] == [0, 1] + assert sizing["start_method"] == "spawn" and "ru_maxrss" in sizing["measure"] + setup = sizing["worker_setup_peak_bytes"] + after = sizing["peak_after_block_bytes"] + assert after >= setup > 0 + if sizing["unavailable"] is None: + assert sizing["measured_growth_bytes"] == after - setup > 0 + assert ( + sizing["measured_bytes_per_row"] == sizing["measured_growth_bytes"] / 24 + ) + else: + assert after == setup and sizing["unavailable"] == _FLAT_PEAK + assert sizing["measured_growth_bytes"] is None + assert sizing["judged"] is False and sizing["judged_from_rows"] == 100_000 + assert "refused" not in sizing + + def test_in_one_process_the_block_is_not_measured_nor_judged( + self, weights_dir, tmp_path, monkeypatch + ): + """The process planned the run before, so its peak is not the + block's. Even with every block judged and the estimate set below + anything a block takes, the run goes through, and the manifest + says why there is no number.""" + from cil_regionalization.reduce import pandas_blocks + + raw, whole, out = self._aggregated(weights_dir, tmp_path) + monkeypatch.setattr(pandas_blocks, "JUDGED_ROWS", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_ROW", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_DIMENSION", 0) + got = self._reduce(raw, memory_gb=_ONE_GROUP_GB, n_workers=1) + _same_frames(got.stats, whole.stats) + sizing = json.loads((out / "again.manifest.json").read_text())["reduce"][ + "block_size" + ] + assert sizing["measured_bytes_per_row"] is None + assert sizing["measured_growth_bytes"] is None + assert sizing["measured_rows"] == 48 + assert sizing["judged"] is False and sizing["start_method"] is None + assert sizing["unavailable"] == ( + "the first block ran in the process that planned the run, whose " + "peak resident memory includes what it did before, so the " + "block's share of the peak cannot be told" + ) + + @pytest.mark.usefixtures("forked_workers_with_a_rising_peak") + def test_a_first_block_heavier_than_the_estimate_is_refused( + self, weights_dir, tmp_path, monkeypatch + ): + """In a worker, with every block judged, and the estimate set at + one byte a row, below anything a block takes. Nothing is written. + It went red with the run let through.""" + from cil_regionalization.reduce import pandas_blocks + + raw, _, out = self._aggregated(weights_dir, tmp_path) + monkeypatch.setattr(pandas_blocks, "JUDGED_ROWS", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_ROW", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_DIMENSION", 0) + # a row group of 24 rows at a byte a row fits 30 bytes, and two do + # not, so there are two blocks and the first goes to a worker + with pytest.raises(ValueError) as error: + self._reduce(raw, memory_gb=2 * 30e-9, n_workers=2) + message = str(error.value) + assert message.startswith( + "reduce: the first block, row groups 0 to 0, took " + ), message + assert ( + "bytes a kept row over 24 rows, more than 2 times the 1 bytes a " + "row the blocks were sized at, so a block can take more than a " + "worker's" + ) in message + assert "No statistics were written." in message + assert "growth of the worker's peak resident memory over the block" in message + assert ( + "Declare the size of a block in [reduce.pandas] targets_per_block" + in message + ) + assert not (out / "again.parquet").exists() + + @pytest.mark.usefixtures("forked_workers_with_a_rising_peak") + def test_a_first_block_within_the_estimate_is_judged_and_runs( + self, weights_dir, tmp_path, monkeypatch + ): + from cil_regionalization.reduce import pandas_blocks + + raw, whole, out = self._aggregated(weights_dir, tmp_path) + monkeypatch.setattr(pandas_blocks, "JUDGED_ROWS", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_ROW", 10**12) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_DIMENSION", 0) + # one row group a worker, so two blocks and a worker for the first + got = self._reduce(raw, memory_gb=2 * 30e3, n_workers=2) + _same_frames(got.stats, whole.stats) + sizing = json.loads((out / "again.manifest.json").read_text())["reduce"][ + "block_size" + ] + assert sizing["judged"] is True and sizing["start_method"] == "fork" + # the peak the fixture puts in, read in the worker + assert sizing["measured_growth_bytes"] % 10**4 == 0 + + @pytest.mark.usefixtures("forked_workers_with_a_flat_peak") + def test_a_forked_worker_whose_peak_did_not_rise_is_not_judged( + self, weights_dir, tmp_path, monkeypatch + ): + """Every block is judged and the estimate is below anything a block + takes, so a measurement would refuse the run. The run goes + through, and the manifest says why there is no number. It went + red with a flat peak taken for a growth of zero.""" + from cil_regionalization.reduce import pandas_blocks + from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK + + raw, whole, out = self._aggregated(weights_dir, tmp_path) + monkeypatch.setattr(pandas_blocks, "JUDGED_ROWS", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_ROW", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_DIMENSION", 0) + # two blocks, so the first goes to a worker + got = self._reduce(raw, memory_gb=2 * 30e-9, n_workers=2) + _same_frames(got.stats, whole.stats) + sizing = json.loads((out / "again.manifest.json").read_text())["reduce"][ + "block_size" + ] + assert sizing["start_method"] == "fork" + assert sizing["unavailable"] == _FLAT_PEAK + assert sizing["worker_setup_peak_bytes"] == sizing["peak_after_block_bytes"] + assert sizing["measured_growth_bytes"] is None + assert sizing["measured_bytes_per_row"] is None + assert sizing["judged"] is False + + @pytest.mark.parametrize("n_workers", [1, 2]) + def test_a_declared_block_size_is_used_warned_and_recorded( + self, weights_dir, tmp_path, n_workers + ): + """In place of a memory budget, with the same numbers. It went + red with the option unknown.""" + raw, whole, out = self._aggregated(weights_dir, tmp_path) + raw = json.loads(json.dumps(raw)) + raw["stats"].update({}) + raw["output"].update(stem="again", leaves_stem="statistics") + raw["reduce"] = {"pandas": {"targets_per_block": 1, "n_workers": n_workers}} + with pytest.warns(UserWarning, match="targets_per_block = 1 declares"): + got = run_pipeline( + MonteCarloPipelineConfig.model_validate(raw), stage="reduce" + ) + _same_frames(got.stats, whole.stats) + reduce = json.loads((out / "again.manifest.json").read_text())["reduce"] + assert reduce["blocks"] == 2 and reduce["per_worker_gb"] is None + assert reduce["options"]["targets_per_block"] == 1 + assert reduce["options"]["memory_gb"] is None + assert reduce["block_size"]["by"] == "declared" + assert reduce["block_size"]["targets_per_block"] == 1 + assert reduce["block_size"]["judged"] is False + assert reduce["block_size"]["measured_rows"] == 24 + + def test_a_budget_and_a_declared_size_together_are_refused( + self, weights_dir, tmp_path + ): + raw = self._raw(weights_dir, tmp_path / "t", tmp_path / "o") + raw["reduce"] = {"pandas": {"memory_gb": 1.0, "targets_per_block": 128}} + with pytest.raises(ValueError, match="memory_gb, which the blocks are sized"): + MonteCarloPipelineConfig.model_validate(raw) + def test_other_windows_need_neither_the_tree_nor_the_weights( self, weights_dir, tmp_path, recwarn ): @@ -3352,7 +3635,9 @@ def test_the_dry_run_says_what_it_would_do_and_touches_nothing( " sized at 280 bytes a row, 240 and 40 for each dimension of a " "leaf, with 0.5 of a group's rows kept. The " "rows of a group are known summed over the leaves, so this takes " - "every leaf to spread its rows over the groups alike.", + "every leaf to spread its rows over the groups alike. The first " + "block is measured in a worker of its own, and the run is refused " + "if it takes more than 2 times that.", f" leaves: every file under {out / 'leaves'} is in a leaves manifest", ] assert plan.missing == [] diff --git a/tests/integration/test_reduce_parity.py b/tests/integration/test_reduce_parity.py index 74fad17..dada11b 100644 --- a/tests/integration/test_reduce_parity.py +++ b/tests/integration/test_reduce_parity.py @@ -1266,8 +1266,9 @@ def test_a_group_that_does_not_fit_is_refused(self): def test_a_worker_that_dies_stops_the_run(self, tmp_path, monkeypatch): """Failed with a `multiprocessing.Pool`, which waits for the dead worker's block for ever. The workers here are forked, so - that they see the block function this test puts in.""" - import functools + that they see the block function this test puts in. The worker + exits with code 1, and the message says so where it blamed + memory for every death.""" import multiprocessing from cil_regionalization.reduce import pandas_blocks @@ -1275,17 +1276,17 @@ def test_a_worker_that_dies_stops_the_run(self, tmp_path, monkeypatch): if "fork" not in multiprocessing.get_all_start_methods(): pytest.skip("needs forked workers") request, _ = build_request(tmp_path, weighted=False, n_members=False) - monkeypatch.setattr( - pandas_blocks, - "ProcessPoolExecutor", - functools.partial( - pandas_blocks.ProcessPoolExecutor, - mp_context=multiprocessing.get_context("fork"), - ), - ) monkeypatch.setattr(pandas_blocks, "_reduce_block", _die) - with pytest.raises(RuntimeError, match="a worker died"): - _one_group_a_block(request, n_workers=2).run(request) + before = multiprocessing.get_start_method(allow_none=True) + multiprocessing.set_start_method("fork", force=True) + try: + with pytest.raises(RuntimeError, match="a worker died") as error: + _one_group_a_block(request, n_workers=2).run(request) + finally: + multiprocessing.set_start_method(before, force=True) + assert "exiting with code 1" in str(error.value) + assert "memory" not in str(error.value) + assert "No statistics were written." in str(error.value) def _die(block): diff --git a/tests/unit/test_block_sizing.py b/tests/unit/test_block_sizing.py new file mode 100644 index 0000000..2ca1807 --- /dev/null +++ b/tests/unit/test_block_sizing.py @@ -0,0 +1,209 @@ +"""How the pandas backend sizes its blocks, without leaves.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from cil_regionalization.reduce.base import PandasReduceOptions +from cil_regionalization.reduce.pandas_blocks import PandasBlocks, fixed_blocks + + +def _request(rows_per_group): + return SimpleNamespace( + leaves=[], + time_reduction="window_mean", + dimensions=(), + footer={"targets_per_group": 128}, + rows_per_group=rows_per_group, + n_workers=1, + ) + + +class TestDeclaredBlocks: + def test_runs_of_whole_row_groups_from_the_first_that_holds_rows(self): + assert fixed_blocks([0, 0, 5, 5, 0, 5, 5], 2) == [(2, 4), (4, 6), (6, 7)] + assert fixed_blocks([0, 0], 2) == [] + + def test_a_declared_size_is_a_whole_number_of_row_groups(self): + plan = PandasBlocks(PandasReduceOptions(targets_per_block=256))._plan( + _request([10, 10, 10]) + ) + assert plan["by"] == "declared" and plan["blocks"] == [(0, 2), (2, 3)] + with pytest.raises( + ValueError, + match="targets_per_block = 200 is not a whole number of the " + "leaves' row groups, which hold 128 targets each", + ): + PandasBlocks(PandasReduceOptions(targets_per_block=200))._plan( + _request([10, 10]) + ) + + def test_a_budget_or_a_declared_size_is_needed(self): + with pytest.raises(ValueError, match="or declare the size of a block"): + PandasBlocks(PandasReduceOptions())._plan(_request([10])) + + +class TestPeakResidentMemory: + """ru_maxrss counts bytes on macOS and kibibytes on Linux.""" + + @pytest.mark.parametrize( + "platform, expected", + [("darwin", 1000), ("linux", 1_024_000), ("freebsd14", None)], + ) + def test_the_unit_is_the_platform_s(self, monkeypatch, platform, expected): + """It went red on a peak taken as bytes everywhere, and on Linux + as thousands of bytes, a factor of 1.024 off.""" + import resource + import sys + + from cil_regionalization.reduce import pandas_blocks + + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr( + resource, "getrusage", lambda who: SimpleNamespace(ru_maxrss=1000) + ) + assert pandas_blocks._peak_resident_bytes() == expected + + def test_the_peak_logged_in_gigabytes_is_of_the_same_bytes(self, monkeypatch): + import resource + import sys + + from cil_regionalization.reduce import pandas_blocks + + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setattr( + resource, "getrusage", lambda who: SimpleNamespace(ru_maxrss=1_000_000) + ) + assert pandas_blocks._peak_gb() == 1.024 + + +class TestGrowth: + """When the growth of a peak says something of the first block.""" + + def test_a_peak_that_rose_gives_its_growth(self): + from cil_regionalization.reduce.pandas_blocks import _growth + + assert _growth(10**9, 10**9 + 5, own_process=True) == (5, None) + + def test_a_peak_that_did_not_rise_gives_no_measure(self): + """As under fork, when the block weighs less than what the worker + inherited. It went red with a growth of zero recorded.""" + from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK, _growth + + assert _growth(10**9, 10**9, own_process=True) == (None, _FLAT_PEAK) + assert "did not rise above the peak it started from" in _FLAT_PEAK + + def test_the_process_that_planned_the_run_gives_no_measure(self): + from cil_regionalization.reduce.pandas_blocks import _SHARED_PEAK, _growth + + assert _growth(10**9, 2 * 10**9, own_process=False) == (None, _SHARED_PEAK) + + def test_an_unknown_unit_gives_no_measure(self): + from cil_regionalization.reduce.pandas_blocks import _growth + + growth, why = _growth(None, None, own_process=True) + assert growth is None and "unit of ru_maxrss" in why + + def test_the_growth_leaves_out_what_the_worker_set_up(self, monkeypatch): + """The setup raises the peak by 100 and the block by 10, and the + growth is the block's. It went red with the peak taken as the + worker started, which gave 110.""" + from cil_regionalization.reduce import pandas_blocks + + peak = [1_000] + + def read(path): + peak[0] += 100 + return SimpleNamespace(digest="d") + + def block(rows): + peak[0] += 10 + return {"block": rows, "rows": 1} + + monkeypatch.setattr(pandas_blocks, "_STATE", {}) + monkeypatch.setattr(pandas_blocks, "_peak_resident_bytes", lambda: peak[0]) + monkeypatch.setattr(pandas_blocks, "_reduce_block", block) + monkeypatch.setattr( + pandas_blocks.leaf_format.TargetTable, "read", staticmethod(read) + ) + pandas_blocks._init_worker( + SimpleNamespace( + leaves_root="/", targets_file="t", footer={"target_digest": "d"} + ) + ) + got = pandas_blocks._measured_block((0, 1)) + assert got["worker_setup_peak_bytes"] == 1_100 + assert got["resident_growth_bytes"] == 10 + + +class TestJudged: + """What `_block_size_record` makes of a first block.""" + + PLAN = {"by": "estimate", "row_bytes": 280, "groups_in_largest_block": 1} + + @staticmethod + def _first(rows, growth, unavailable=None): + return { + "block": (0, 4), + "rows": rows, + "resident_growth_bytes": growth, + "worker_setup_peak_bytes": None if growth is None else 10**9, + "peak_after_block_bytes": None if growth is None else 10**9 + growth, + "measure_unavailable": unavailable, + "start_method": "fork", + } + + def _record(self, first, plan=None): + from cil_regionalization.reduce.pandas_blocks import _block_size_record + + return _block_size_record(_request([10]), plan or self.PLAN, first) + + def test_more_than_twice_the_estimate_is_refused(self): + got = self._record(self._first(200_000, 200_000 * 561)) + assert got["judged"] and got["refused"] and got["refused_above"] == 2 + assert got["measured_bytes_per_row"] == 561 + + @pytest.mark.parametrize("per_row", [281, 560]) + def test_up_to_twice_the_estimate_is_judged_and_passes(self, per_row): + """A tolerance on a noisy measure. It went red when once the + estimate was refused.""" + got = self._record(self._first(200_000, 200_000 * per_row)) + assert got["judged"] and not got["refused"] + + def test_below_the_judged_rows_is_recorded_and_not_judged(self): + got = self._record(self._first(99_999, 99_999 * 10_000)) + assert not got["judged"] and not got["refused"] + assert got["measured_bytes_per_row"] == 10_000 + + def test_without_a_measure_nothing_is_judged(self): + got = self._record(self._first(200_000, None, unavailable="why")) + assert got["measured_bytes_per_row"] is None and got["unavailable"] == "why" + assert not got["judged"] and not got["refused"] + + def test_a_declared_size_is_never_judged(self): + plan = {**self.PLAN, "by": "declared"} + got = self._record(self._first(200_000, 200_000 * 10_000), plan) + assert got["by"] == "declared" and not got["judged"] + assert got["targets_per_block"] == 128 + + def test_the_refusal_names_a_block_that_fits(self): + from cil_regionalization.reduce.pandas_blocks import _too_heavy + + sizing = self._record(self._first(200_000, 200_000 * 600)) + # 4 row groups of 128 targets took 120 MB, so a target 234,375 + # bytes, and a worker of 1 GB holds 4,266 targets, 33 row groups + message = _too_heavy( + _request([10]), {**self.PLAN, "per_worker_gb": 1.0}, sizing + ) + assert message == ( + "reduce: the first block, row groups 0 to 3, took 600 bytes a kept " + "row over 200,000 rows, more than 2 times the 280 bytes a row the " + "blocks were sized at, so a block can take more than a worker's 1 " + "GB. No statistics were written. The measure is the growth of the " + "worker's peak resident memory over the block. Declare the size of " + "a block in [reduce.pandas] targets_per_block, in place of " + "memory_gb. At the measured size a block of 4224 targets fits a " + "worker." + ) diff --git a/tests/unit/test_workers.py b/tests/unit/test_workers.py new file mode 100644 index 0000000..501ed78 --- /dev/null +++ b/tests/unit/test_workers.py @@ -0,0 +1,104 @@ +"""Pools that stop when a worker dies, in waves of new workers.""" + +from __future__ import annotations + +import os +import signal +import time + +import pytest + +from cil_regionalization.workers import WorkerDied, how_workers_ended, run_in_waves + + +def _setup() -> None: + pass + + +def _failing_setup() -> None: + raise ValueError("this setup fails") + + +def _pid_of(task: int) -> tuple[int, int]: + return task, os.getpid() + + +def _killed_on_three(task: int) -> int: + if task == 3: + os.kill(os.getpid(), signal.SIGKILL) + time.sleep(0.05) + return task + + +def _run(fn, tasks, *, initializer=_setup, n_workers=2, per_worker=2): + got = [] + run_in_waves( + fn, + tasks, + n_workers=n_workers, + per_worker=per_worker, + initializer=initializer, + initargs=(), + on_result=got.append, + name=lambda task: f"task {task}", + what="test", + ) + return got + + +def test_every_task_runs_once_on_new_workers_each_wave(): + """Waves of four, so the workers of one wave are none of the next. + It went red on one pool for every task.""" + got = _run(_pid_of, list(range(10))) + assert sorted(task for task, _ in got) == list(range(10)) + waves = [ + {pid for task, pid in got if start <= task < start + 4} for start in (0, 4, 8) + ] + assert not waves[0] & waves[1] and not waves[1] & waves[2] + + +def test_a_worker_killed_stops_the_run_at_once_and_says_how(): + """It hung on the pool before, waiting for the task the dead worker + held.""" + began = time.monotonic() + with pytest.raises(WorkerDied) as error: + _run(_killed_on_three, list(range(8)), per_worker=4) + assert time.monotonic() - began < 60 + message = str(error.value) + # two workers, so task 3 and one of 2 and 4 were out + assert message.startswith("test: a worker died with task "), message + assert " in flight, killed by SIGKILL, which is how an out-of-memory " in message + held = message.split("died with ")[1].split(" in flight")[0] + assert "task 3" in held and len(held.replace(" and ", ", ").split(", ")) == 2, held + + +def test_a_failing_setup_is_said_to_be_one(): + """Not blamed on memory. Its exit code is 0, and its traceback goes + to the log.""" + with pytest.raises(WorkerDied) as error: + _run(_pid_of, list(range(4)), initializer=_failing_setup) + assert "task 0 and task 1 in flight, exiting with code 0 before it " in str( + error.value + ) + assert "out-of-memory" not in str(error.value) + + +@pytest.mark.parametrize( + "codes, told", + [ + ( + [-9, -15], + "killed by SIGKILL, which is how an out-of-memory kill ends a process, " + "and the pool then stopped the other 1 with SIGTERM", + ), + ([1], "exiting with code 1"), + ( + [-11, -15, -15], + "killed by SIGSEGV, and the pool then stopped the other 2 with SIGTERM", + ), + ([-15, -15], "killed by SIGTERM, as 2 workers did"), + ([], "and its exit code could not be read"), + ], +) +def test_the_exit_codes_are_told_as_they_are(codes, told): + assert how_workers_ended(codes) == told