"""
Worker functions that run one release, or many releases.
Workers are handed releases. :func:`run_release` runs every variant of
one release. Variants with the same transport settings share one set of
particles, so it groups them: the transport model runs once per group where the
particles are missing (:func:`run_particles`), then each variant's stages
make their files from the particles in memory (:func:`run_stages`). A stage
is the class its ``stages`` block of ``config.yaml`` names
(:class:`runtraj.stages.Stage`), so this module imports none.
A failure is recorded with the simulation and the worker goes on, except
a connection or I/O error that a retry may get past, which is not recorded as a
failure: the simulation stays unfinished and the next run does it again.
:func:`run_releases` runs a list of releases in this process or a
process pool. A :class:`~runtraj.Simulation` itself runs nothing; these
functions write through its output directory.
"""
from __future__ import annotations
import contextlib
import datetime as dt
import logging
import multiprocessing
import os
import shutil
import signal
import socket
import threading
import traceback
import uuid
from collections.abc import Iterator
from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait
from concurrent.futures.process import BrokenProcessPool
from pathlib import Path
from typing import TYPE_CHECKING, Any
import pandas as pd
from runtraj._transient import is_transient
from runtraj.exceptions import SimulationError, WorkerDied
from runtraj.execution.config import ExecutionConfig
from runtraj.models import get_model, run_model, run_model_many
from runtraj.simulation import Simulation
from runtraj.stages import reads
if TYPE_CHECKING:
from upath import UPath
from runtraj.project import Project
logger = logging.getLogger(__name__)
def _raise_interrupt(signum: int, frame: object) -> None:
"""Turn a signal into KeyboardInterrupt so cleanup runs."""
raise KeyboardInterrupt
def _exit_worker(signum: int, frame: object) -> None:
"""Stop a pool worker: its ``finally`` blocks run, then the process exits."""
raise SystemExit(1)
@contextlib.contextmanager
def _sigterm_as_interrupt():
"""
Make SIGTERM raise ``KeyboardInterrupt`` inside the ``with`` block.
Slurm sends SIGTERM on preemption or when a job reaches its time limit.
Python's default action ends the process without running ``finally``
blocks, so pool workers would be left running.
It does nothing when SIGTERM is already handled: a handler the caller
set stays in charge. Signal handlers can only be set from the main
thread, so in any other thread this does nothing either.
"""
if threading.current_thread() is not threading.main_thread():
yield
return
previous = signal.getsignal(signal.SIGTERM)
if previous is not signal.SIG_DFL:
yield
return
signal.signal(signal.SIGTERM, _raise_interrupt)
try:
yield
finally:
signal.signal(signal.SIGTERM, previous)
# -- failure records ---------------------------------------------------------
def _failed(sim: Simulation, stage: str, error: Exception) -> str:
"""
Record why *sim* failed at *stage*, and return one line saying so.
*stage* is ``particles`` for the transport model run, or the name of
the stage that failed. The record goes in the logs of the folder whose
result failed (:meth:`runtraj.output.Output.record_failure`): a particles
failure covers every variant on those particles, a stage's failure
every variant with that stage's settings on them. ``reason`` is the
error's short cause, or its class
for an error without one. An expected failure (a
:class:`~runtraj.exceptions.SimulationError`) logs one line; any other
error logs, and records, its traceback.
A connection or I/O error that a retry may get past
(:func:`runtraj._transient.is_transient` says so: a bucket that stopped answering
while the result was written) is not a failure of the simulation, so
nothing is recorded (:func:`_unfinished`). A ``SimulationError`` always is one.
"""
if not isinstance(error, SimulationError) and is_transient(error):
return _unfinished(sim, stage, error)
expected = isinstance(error, SimulationError)
reason = getattr(error, "reason", None) or type(error).__name__
if expected:
logger.warning(
"simulation %s failed during %s (%s): %s", sim, stage, reason, error
)
else:
logger.exception("simulation %s failed during %s: %s", sim, stage, error)
record: dict[str, Any] = {
"stage": stage,
"reason": str(reason),
"message": str(error),
"time": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(),
}
if not expected:
record["traceback"] = traceback.format_exc()
try:
sim.output.record_failure(
stage, sim.variant, sim.release.id, record, sim.realization
)
except Exception:
logger.exception("simulation %s: could not record the failure", sim)
return f"{sim.variant.name} failed during {stage} ({reason}): {error}"
def _unfinished(sim: Simulation, stage: str, error: Exception) -> str:
"""
Leave *sim* unfinished after a connection or I/O error at *stage*, and return one line saying so.
No failure record is written, so the simulation is ``pending``, or
``interrupted`` once its particles run started, and ``runtraj run`` exits
with 3. A failure record from an earlier attempt is removed, so it does
not stand for this one; when the output cannot be reached to do that,
the old record stays until a run writes the result.
"""
name = type(error).__name__
logger.warning(
"simulation %s did not finish during %s, a retry may finish it: %s: %s",
sim,
stage,
name,
error,
)
logger.debug("simulation %s: the error", sim, exc_info=error)
try:
_succeeded(sim, stage)
except Exception as cleanup:
logger.warning(
"simulation %s: could not remove its earlier failure record: %s: %s",
sim,
type(cleanup).__name__,
cleanup,
)
return f"{sim.variant.name} did not finish during {stage} ({name}), a retry may finish it: {error}"
def _succeeded(sim: Simulation, stage: str) -> None:
"""Remove *sim*'s failure record for *stage*, whose result is now written."""
sim.output.clear_failure(stage, sim.variant, sim.release.id, sim.realization)
[docs]
def run_particles(
sim: Simulation,
*,
workdir: Path,
keep_workdir: bool = False,
timeout: int | None = None,
) -> pd.DataFrame:
"""
Run the transport model for a simulation and write its particles to the output directory.
The transport model the variant names runs in *workdir*
(:func:`runtraj.models.run_model`), with the variant's met. Its log is written to the output
directory whether the run succeeds or fails. The working directory is
then removed, unless the run failed or *keep_workdir* is set, in which
case it is copied under the output directory's ``scratch/`` first.
Parameters
----------
sim : Simulation
What to run.
workdir : Path
Directory to run in, made here. Anything in it is removed first,
so each run needs its own.
keep_workdir : bool, default False
Keep the working directory of a successful run too.
timeout : int, optional
Time limit for the transport model run, in seconds.
Returns
-------
pandas.DataFrame
The particles, also written to the output directory.
Raises
------
SimulationError
As the transport model raises it (with a ``reason``), or with
``reason`` ``NO_PARTICLE_DATA`` when the model wrote no particles.
:class:`~runtraj.exceptions.MeteorologyError` when the met files are
missing.
"""
output, rid = sim.output, sim.release.id
needs_workdir = getattr(get_model(sim.variant.model), "needs_workdir", True)
if needs_workdir:
# The model runs in an empty directory. The runner gives each run a
# new one, but a caller can hand over a directory that a stopped run
# left behind, so clear it.
shutil.rmtree(workdir, ignore_errors=True)
workdir.mkdir(parents=True)
_log_start(sim)
log = ""
succeeded = False
try:
result = run_model(
sim.variant.model,
sim.release,
sim.transport,
sim.variant.met_config,
workdir if needs_workdir else None,
timeout=timeout,
)
log = result.log
output.write_particles(
sim.variant,
sim.release,
result.particles,
result.met_files,
sim.realization,
)
succeeded = True
return result.particles
except SimulationError as error:
log = error.log
raise
finally:
if log:
output.write_log(sim.variant, rid, log, sim.realization)
if needs_workdir:
# An empty directory is not kept: a run that failed before
# writing anything, such as on missing meteorology, has nothing
# to look at.
if (keep_workdir or not succeeded) and any(workdir.iterdir()):
output.keep_workdir(sim.variant, rid, workdir, sim.realization)
shutil.rmtree(workdir, ignore_errors=True)
def _log_start(sim: Simulation) -> None:
"""
Write a log line saying the run of *sim*'s particles started, which the model's log replaces.
A run cut off before it ends keeps only this line, so it reads as
interrupted rather than as never run.
"""
started = dt.datetime.now(dt.UTC).isoformat(timespec="seconds")
sim.output.write_log(
sim.variant,
sim.release.id,
f"runtraj started this run at {started} on {socket.gethostname()}; "
"the transport model's log replaces this line when the run ends.\n",
sim.realization,
)
def run_particles_batch(
sims: list[Simulation], *, timeout: int | None = None
) -> tuple[dict[str, pd.DataFrame], dict[str, str]]:
"""
Run a batched transport model once for many releases, and write each one's particles.
*sims* are simulations of one variant and realization, one per release,
so they share the transport settings. The model's one call
(:func:`runtraj.models.run_model_many`) gives each release its
particles or an error: the particles and the log are written, and a
failure is recorded with its simulation.
Returns
-------
tuple of (dict, dict)
The particles written, and a line saying why for each release
that failed, both by release id.
"""
first = sims[0]
for sim in sims:
_log_start(sim)
try:
results = run_model_many(
first.variant.model,
[sim.release for sim in sims],
first.transport,
first.variant.met_config,
timeout=timeout,
)
except Exception as error:
log = getattr(error, "log", "")
failed: dict[str, str] = {}
for sim in sims:
if log:
sim.output.write_log(sim.variant, sim.release.id, log, sim.realization)
failed[sim.release.id] = _failed(sim, "particles", error)
return {}, failed
written: dict[str, pd.DataFrame] = {}
failed = {}
for sim in sims:
rid = sim.release.id
result = results[rid]
if result.log:
sim.output.write_log(sim.variant, rid, result.log, sim.realization)
if isinstance(result, SimulationError):
failed[rid] = _failed(sim, "particles", result)
continue
sim.output.write_particles(
sim.variant,
sim.release,
result.particles,
result.met_files,
sim.realization,
)
_succeeded(sim, "particles")
written[rid] = result.particles
return written, failed
@contextlib.contextmanager
def _stage_file(path: Path | UPath, suffix: str) -> Iterator[Path | UPath]:
"""
Yield where a stage writes *path*, and leave a whole file there or none.
A file already at *path* is removed first: it was made from what has
since been made again, so it must not outlive a stage that fails. On a
filesystem the stage writes under a temporary name beside *path*,
hidden by a leading dot and ending in *suffix* (a writer may choose its
format by the extension, or append one), which is moved into place when
the block ends. An object store has no rename, so the stage writes
*path* itself. Either way, what a block that raises has written is
removed.
"""
path.unlink(missing_ok=True)
if not isinstance(path, Path):
try:
yield path
except BaseException:
path.unlink(missing_ok=True)
raise
return
stem = path.name[: -len(suffix)]
tmp = path.with_name(f".{stem}.{uuid.uuid4().hex}{suffix}")
try:
yield tmp
os.replace(tmp, path)
finally:
tmp.unlink(missing_ok=True)
[docs]
def run_stage(sim: Simulation, name: str) -> None:
"""
Run one stage of a simulation, which writes its file to the output directory.
The stage is the one the variant's ``stages`` block names
(:meth:`runtraj.stages.Stage.run`), run with the variant's settings of
it. A file the stage made before is removed first, and the stage writes
under a temporary name beside the file's own, which is moved into place
when the stage returns. So a stage that fails, or is cut off part-way,
leaves no file that would count as complete: neither a half-written
one, nor an old one made from what has since been made again.
Raises
------
ValueError
If the variant does not use a stage of that name.
RuntimeError
If the stage returned without writing its file.
"""
variant = sim.variant
path = sim.output.make_path(name, variant, sim.release.id, sim.realization)
stage = variant.stage(name)
path.parent.mkdir(parents=True, exist_ok=True)
with _stage_file(path, stage.suffix) as target:
stage.run(variant.stages[name], sim, target)
if not target.exists():
raise RuntimeError(
f"The {name} stage returned without writing its file for {sim}. "
"A stage writes one file at the path it is given, whatever it "
"has to say."
)
[docs]
def run_stages(
sims: list[Simulation],
particles: pd.DataFrame | None = None,
*,
remade: bool = False,
skip_existing: bool = True,
) -> list[str]:
"""
Run the stages of the simulations of one release that share particles, and return what failed.
Each variant's stages run in the order :attr:`runtraj.config.Variant.stage_order`
gives, a stage after the ones it reads. A stage file that exists is
kept, unless something it is made from was made again in this call:
the particles (*remade*), or the file of a stage it reads. Then the old
file is removed before the stage runs, so one that fails leaves none. Variants
with equal settings of a stage, and of what it reads, share its file,
so it is made once. A failure is recorded with the simulation, and the
stages that read the failed one are left for the next run.
Parameters
----------
sims : list of Simulation
One release under each variant that shares its particles, as one
realization.
particles : pandas.DataFrame, optional
The particles, when they are in memory. Without them a stage reads
the stored ones, once for all the simulations.
remade : bool, default False
Whether the particles were just made, so every stage file is made
again.
skip_existing : bool, default True
Keep the stage files that already exist.
Returns
-------
list of str
One line per failure.
"""
problems: list[str] = []
seen: set[tuple[str, str]] = set() # each (stage, hash) is looked at once
made: set[tuple[str, str]] = set() # the files written in this call
failed: set[tuple[str, str]] = set() # and those that could not be
for sim in sims:
variant = sim.variant
for name in variant.stage_order:
key = (name, variant.stage_hashes[name])
if key in seen:
continue
seen.add(key)
read = [(r, variant.stage_hashes[r]) for r in reads(variant.stage(name))]
if any(r in failed for r in read):
failed.add(key) # nothing to read; the failure above is recorded
continue
again = remade or any(r in made for r in read)
if not again and skip_existing and sim.has(name):
continue
if particles is not None:
# Give the simulation the particles in memory, so that the
# stage's sim.particles reads no file (a cached property).
sim.__dict__.setdefault("particles", particles)
try:
run_stage(sim, name)
except Exception as error:
problems.append(_failed(sim, name, error))
failed.add(key)
continue
finally:
# What this stage read from the file serves the next one.
particles = sim.__dict__.get("particles", particles)
_succeeded(sim, name)
made.add(key)
return problems
[docs]
def run_release(
project: Project,
release_id: str,
*,
compute_root: Path,
execution: ExecutionConfig | None = None,
skip_existing: bool = True,
batched: bool = True,
) -> list[str]:
"""
Run every simulation of one release, and return what did not complete.
Each realization of an ensemble variant is a simulation of its own.
Variants with the same transport settings share one set of particles
(per realization), so they run as a group: the transport model runs
once for the group when the
particles are missing (or always, without ``skip_existing``), and each
variant's stages make their files from those particles in memory
(:func:`run_stages`). A stage's file is made
again whenever what it is made from was, so it always matches it.
A failure is recorded with the simulation (:attr:`runtraj.Simulation.failure`)
and does not stop the others; a failed transport model run fails every variant
of its group. A ``KeyboardInterrupt``, such as a preempted job, stops
the release and is raised again.
Parameters
----------
project : Project
Project the release belongs to.
release_id : str
Release to run.
compute_root : Path
Directory the workdirs are made in, a new one for each run, as
:func:`~runtraj.execution.runner.resolve_compute_root` returns it.
execution : ExecutionConfig, optional
Execution settings, for ``timeout`` and ``keep_workdir``. Defaults
to the project's.
skip_existing : bool, default True
Keep particles and stage files that already exist.
batched : bool, default True
Also run the variants of a batched transport model, one release
per call. :func:`run_releases` runs those for all its releases at
once first, and passes False.
Returns
-------
list of str
One line per failure, empty when every simulation is complete. The
failures are also recorded in the output directory, which is where
:meth:`runtraj.Project.status` reads them.
"""
execution = execution if execution is not None else project.config.execution
problems: list[str] = []
for (_, k), names in _groups(project).items():
if not batched and _is_batched(project, names[0]):
continue
group = [project.simulation(release_id, n, k) for n in names]
problems += _run_group(
project,
group,
compute_root=compute_root,
execution=execution,
skip_existing=skip_existing,
)
return problems
def _groups(project: Project) -> dict[tuple[str, int | None], list[str]]:
"""
Return the variants that share particles, by particles hash and realization.
Each group's transport model runs once per release (or once for many
releases, when it is batched), and each variant in it runs its stages
on those particles.
"""
groups: dict[tuple[str, int | None], list[str]] = {}
for name, variant in project.variants.items():
for k in variant.realization_numbers:
groups.setdefault((variant.particles_hash, k), []).append(name)
return groups
def _is_batched(project: Project, variant: str) -> bool:
"""Whether a variant's transport model runs many releases in one call."""
model = get_model(project.variants[variant].model)
return bool(getattr(model, "batched", False))
def _run_batched(
project: Project,
release_ids: list[str],
*,
execution: ExecutionConfig,
skip_existing: bool,
) -> dict[str, list[str]]:
"""
Run the variants of batched transport models for many releases, one model call per group.
For each group of variants that share particles, the releases whose
particles are missing (all of them, without *skip_existing*) run in one
call (:func:`run_particles_batch`); then each variant's stages run
per release. Returns the failures by release id.
"""
problems: dict[str, list[str]] = {rid: [] for rid in release_ids}
for (_, k), names in _groups(project).items():
if not _is_batched(project, names[0]):
continue
firsts = [project.simulation(rid, names[0], k) for rid in release_ids]
todo = [s for s in firsts if not (skip_existing and s.has_particles)]
written: dict[str, pd.DataFrame] = {}
if todo:
written, failed = run_particles_batch(todo, timeout=execution.timeout)
for rid, line in failed.items():
problems[rid].append(line)
ran = {s.release.id for s in todo}
for rid in release_ids:
if rid in ran and rid not in written:
continue # its particles failed, so no stage has any to read
sims = [project.simulation(rid, n, k) for n in names]
problems[rid] += run_stages(
sims, written.get(rid), remade=rid in ran, skip_existing=skip_existing
)
return problems
def _new_workdir(compute_root: Path, sim: Simulation) -> Path:
"""
Return a workdir for one run of *sim*'s transport model: a new path in *compute_root*.
The name is the release id, the variant, and the realization (in an
ensemble), then a random part, so two runs never share a workdir. Another project can use
the same compute root with the same release and variant names, and the
same simulation can run twice at once.
"""
return compute_root / f"{str(sim).replace('/', '_')}_{uuid.uuid4().hex[:8]}"
def _run_group(
project: Project,
sims: list[Simulation],
*,
compute_root: Path,
execution: ExecutionConfig,
skip_existing: bool,
) -> list[str]:
"""Run the simulations of one release that share particles: the transport model at most once, then each variant's stages."""
first = sims[0]
particles: pd.DataFrame | None = None
rerun = not (skip_existing and first.has_particles)
if rerun:
try:
particles = run_particles(
first,
workdir=_new_workdir(compute_root, first),
keep_workdir=execution.keep_workdir,
timeout=execution.timeout,
)
except Exception as error:
return [_failed(first, "particles", error)]
_succeeded(first, "particles")
return run_stages(sims, particles, remade=rerun, skip_existing=skip_existing)
def _log_progress(release_id: str, problems: list[str], done: int, total: int) -> None:
"""Log one progress line for a finished release: complete, or its first problem."""
if problems:
logger.info("[%d/%d] %s: %s", done, total, release_id, problems[0])
else:
logger.info("[%d/%d] %s complete", done, total, release_id)
# -- process pool -------------------------------------------------------------
_POOL_PROJECT: Project | None = None
_POOL_COMPUTE_ROOT: Path | None = None
_POOL_EXECUTION: ExecutionConfig | None = None
_POOL_SKIP: bool = True
def _init_pool_worker(
project: str,
output: str,
compute_root: str,
execution: ExecutionConfig,
skip_existing: bool,
rows: pd.DataFrame | None = None,
) -> None:
"""
Open the worker process's Project, on the parent's output, and set how it stops.
The parent stops its workers with SIGTERM (:func:`run_releases`). A
worker that gets it ends the transport model run it is in the middle
of and exits (:func:`_pool_run`). It ignores
Ctrl-C, which the terminal also sends to it: the parent answers that.
*rows* are the release rows the parent took in place of
``releases.csv`` (a Slurm task's), if any.
"""
from runtraj.project import Project
global _POOL_PROJECT, _POOL_COMPUTE_ROOT, _POOL_EXECUTION, _POOL_SKIP
signal.signal(signal.SIGTERM, _exit_worker)
signal.signal(signal.SIGINT, signal.SIG_IGN)
_POOL_PROJECT = Project(project, output=output)
if rows is not None:
_POOL_PROJECT._take_rows(rows)
_POOL_COMPUTE_ROOT = Path(compute_root)
_POOL_EXECUTION = execution
_POOL_SKIP = skip_existing
def _pool_run(item: tuple[int, str]) -> tuple[int, list[str]]:
"""Run one release in a pool worker, returning its index and problems."""
idx, release_id = item
assert _POOL_PROJECT is not None and _POOL_COMPUTE_ROOT is not None
try:
return idx, run_release(
_POOL_PROJECT,
release_id,
compute_root=_POOL_COMPUTE_ROOT,
execution=_POOL_EXECUTION,
skip_existing=_POOL_SKIP,
batched=False, # run_releases ran those first
)
except SystemExit:
# SIGTERM (:func:`_exit_worker`), after the run's `finally` blocks
# have cleaned up. The executor's worker loop catches every
# BaseException and waits for more work, so the process would
# outlive the stop; end it here.
os._exit(1)
def _check_workers_can_start(cpus: int) -> None:
"""
Start one worker that does nothing, and stop with a clear message when it cannot.
Python 3.14 on Linux, and macOS and Windows, start a worker by running
the calling script again, as ``__mp_main__``. A script that runs the
project at the top level, without ``if __name__ == "__main__":``, fails
in every worker. The pool would then stop with
:class:`~runtraj.exceptions.WorkerDied`, which blames memory, or with a
bare connection error (``forkserver``). Starting one worker first turns
that into an error that shows the fix. ``fork`` runs no script again,
so it skips the check.
"""
method = multiprocessing.get_start_method()
if method == "fork":
return
probe = multiprocessing.Process(target=int, daemon=True) # int() does nothing
failure: Exception | None = None
try:
probe.start()
probe.join()
except Exception as error:
# forkserver: its server process died importing the script, and
# start() raises a different error in each Python version.
failure = error
if failure is None and probe.exitcode == 0:
return
raise RuntimeError(
f"A worker process could not start (cpus={cpus}). With the {method!r} "
"start method, each worker starts by running your script again, and "
"that failed; the traceback above shows where. A script that runs a "
"project needs its code under a guard:\n\n"
' if __name__ == "__main__":\n'
" project = runtraj.Project(...)\n"
" project.run()\n\n"
"`runtraj run --cpus N` and a `cpus` of 1 need no guard."
) from failure
def _stop_workers(executor: ProcessPoolExecutor) -> None:
"""
End the pool's workers now: cancel what has not started, SIGTERM the rest.
A worker that gets SIGTERM ends its transport model run and exits
(:func:`_init_pool_worker`). The executor has no call for this before
Python 3.14, so the workers are read from ``_processes``.
"""
workers = list(executor._processes.values())
executor.shutdown(wait=False, cancel_futures=True)
for process in workers:
process.terminate()
for process in workers:
process.join()
#: Seconds the pool loop waits for a release to finish before it looks at the workers.
_WORKER_CHECK_SECONDS = 2.0
def _a_worker_died(executor: ProcessPoolExecutor) -> bool:
"""
Say whether a pool worker has exited, which it does only if it was killed.
The pool reports a worker killed outright (SIGKILL, as the out-of-memory
killer sends) by itself, but not always at once. On Python 3.14 it starts
the second worker after waking the thread that watches the workers, which
may already have made its list. If that worker is the one killed, the pool
learns of it only when another release finishes, which can be hours later
. Workers stay alive until the loop in :func:`_run_in_pool` ends, so
one that is not alive has died.
"""
return any(not process.is_alive() for process in list(executor._processes.values()))
def _run_in_pool(
project: Project,
release_ids: list[str],
earlier: dict[str, list[str]],
*,
compute_root: Path,
execution: ExecutionConfig,
skip_existing: bool,
) -> None:
"""
Run *release_ids* in ``execution.cpus`` worker processes, one release in each at a time.
Only as many releases are given to the pool as there are workers, so a
release given to it is a release in progress. If a worker dies without
Python's say (SIGKILL, as the out-of-memory killer sends), the pool cannot say which
release it held, and it cannot be used again: the run stops with
:class:`~runtraj.exceptions.WorkerDied`, naming every release in progress.
"""
total = len(release_ids)
_check_workers_can_start(execution.cpus)
executor = ProcessPoolExecutor(
execution.cpus,
initializer=_init_pool_worker,
initargs=(
str(project.directory),
str(project.output.directory),
str(compute_root),
execution,
skip_existing,
project._taken_rows,
),
)
waiting = enumerate(release_ids)
running: dict[Future[tuple[int, list[str]]], int] = {} # each one's index
done = 0
with _sigterm_as_interrupt():
try:
while True:
while len(running) < execution.cpus:
item = next(waiting, None)
if item is None:
break
running[executor.submit(_pool_run, item)] = item[0]
if not running:
break
finished, _ = wait(
running, timeout=_WORKER_CHECK_SECONDS, return_when=FIRST_COMPLETED
)
if not finished:
if _a_worker_died(executor):
raise BrokenProcessPool("a worker process died")
continue
for future in finished:
idx, problems = future.result()
del running[future]
done += 1
rid = release_ids[idx]
_log_progress(rid, earlier.get(rid, []) + problems, done, total)
# Normal completion: let the workers exit on their own.
executor.shutdown()
except KeyboardInterrupt:
# Preempted or Ctrl-C: SIGTERM the workers, which end their runs
# and exit; what finished is written.
logger.info(
"stopped after %d of %d releases; the rest did not run", done, total
)
_stop_workers(executor)
except BrokenProcessPool as error:
# A release that finished in the same moment is not lost.
lost = [
release_ids[idx]
for future, idx in running.items()
if not future.done() or future.exception() is not None
]
_stop_workers(executor)
raise WorkerDied(
f"A worker process died after {done} of {total} releases finished, "
f"most likely killed for using too much memory. These were in progress, "
f"and the pool cannot say which one it held: {', '.join(lost)}. "
"The run stopped. What finished is kept; run it again to continue "
"with what is missing, with fewer cpus or more memory per task if "
"workers keep dying."
) from error
except BaseException:
# A requeued Slurm task exits here (SystemExit), or a worker's
# own error re-raised by result(): the workers must not outlive
# the run, and the error reaches the caller.
_stop_workers(executor)
raise
[docs]
def run_releases(
project: Project,
release_ids: list[str],
*,
compute_root: Path,
execution: ExecutionConfig | None = None,
skip_existing: bool = True,
) -> None:
"""
Run a list of releases, in this process or in a process pool.
The variants of a batched transport model run first, one model call
for all the releases that need their particles. Then each release
runs its other variants. Pool workers open the project again from its
directory, with the same output directory. Ctrl-C, or a SIGTERM such as Slurm preemption or a stopped
pod, stops the batch: the transport model runs in progress are ended, the workers exit, and this logs
how many releases had finished and returns. What finished is in the output directory, with a failure
record for each simulation that failed; a run that was cut off leaves only its log line, so it is
``interrupted`` in :meth:`runtraj.Project.status`.
An error that escapes a release's own handling (:func:`run_release` records a failure
for one and goes on; this is anything outside that, such as a shared resource that stops
answering) stops the batch too: the pool is terminated and the error raised to the caller.
Parameters
----------
project : Project
Project the releases belong to.
release_ids : list of str
Releases to run.
compute_root : Path
Directory the workdirs are made in, a new one for each run, as
:func:`~runtraj.execution.runner.resolve_compute_root` returns it.
execution : ExecutionConfig, optional
Execution settings: ``cpus`` is the number of worker processes (1
runs in this process), and ``timeout`` and ``keep_workdir`` apply
to each run. Defaults to the project's.
skip_existing : bool, default True
Keep particles and stage files that already exist.
"""
if not release_ids:
return
execution = execution if execution is not None else project.config.execution
total = len(release_ids)
earlier: dict[str, list[str]] = {}
if any(_is_batched(project, names[0]) for names in _groups(project).values()):
with _sigterm_as_interrupt():
try:
earlier = _run_batched(
project,
release_ids,
execution=execution,
skip_existing=skip_existing,
)
except KeyboardInterrupt:
logger.info("stopped during a batched run; the rest did not run")
return
if execution.cpus <= 1:
with _sigterm_as_interrupt():
for i, release_id in enumerate(release_ids, 1):
try:
problems = earlier.get(release_id, []) + run_release(
project,
release_id,
compute_root=compute_root,
execution=execution,
skip_existing=skip_existing,
batched=False,
)
except KeyboardInterrupt:
logger.info("stopped at %s; the rest did not run", release_id)
return
_log_progress(release_id, problems, i, total)
return
_run_in_pool(
project,
release_ids,
earlier,
compute_root=compute_root,
execution=execution,
skip_existing=skip_existing,
)
__all__ = [
"run_particles",
"run_particles_batch",
"run_release",
"run_releases",
"run_stage",
"run_stages",
]