Skip to content

Commit 2bec214

Browse files
committed
feat: implement DVM diagnostics for enhanced task lifecycle tracking
1 parent 1640e5f commit 2bec214

2 files changed

Lines changed: 196 additions & 53 deletions

File tree

‎doc/user_guides/ensembles.rst‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,46 @@ The ensemble system provides robust error handling:
366366
- Resource allocation errors are reported with detailed messages
367367
- Configuration template errors are caught before execution begins
368368

369+
DVM diagnostics
370+
---------------
371+
372+
Each Dask worker's DVM launch creates a persistent directory beneath the
373+
ensemble driver's working directory::
374+
375+
dvm/<hostname>.<worker-pid>.<launch-uuid>/
376+
uri
377+
output.log
378+
lifecycle.jsonl
379+
shutdown.log
380+
381+
``uri`` contains PRTE's connection URI, and ``output.log`` captures the DVM's
382+
combined stdout and stderr directly to disk. ``lifecycle.jsonl`` contains
383+
UTC timestamps, monotonic elapsed times, worker and DVM identities, launch
384+
parameters, readiness, instance start/end records, observed exits, and shutdown
385+
actions. Only selected Slurm and PRTE environment settings are recorded.
386+
``shutdown.log`` is created when a shutdown command is attempted and captures
387+
its combined output. Records are flushed as they are written.
388+
389+
Shutdown first attempts ``pterm`` or ``prte-term`` with a ten-second timeout,
390+
then waits up to ten seconds for the DVM to exit. If necessary, it sends
391+
terminate and waits five seconds, then sends kill and waits another five
392+
seconds. Command results and escalation are recorded, and diagnostic files
393+
are retained.
394+
395+
Nonzero MPI task results returned by ``wait_task()`` create a
396+
``dvm-failures.<component-pid>.jsonl`` file in the component working directory.
397+
These records include the instance name, task command, return code, and the
398+
associated lifecycle journal path. Each component owns its own failure file
399+
to avoid concurrent appends from different processes.
400+
401+
DVM process state is sampled by the owning worker at lifecycle events,
402+
including instance start and end; there is no background monitor. Child
403+
failure records explicitly report DVM state as unknown in the child.
404+
An ``exit_observed`` timestamp is the time the worker detected an exit,
405+
not necessarily the time it occurred. A running process does not establish
406+
DVM responsiveness. Abrupt worker or node loss may leave no final record.
407+
Components must still check ``wait_task()`` results and propagate failures.
408+
369409
Limitations
370410
-----------
371411

‎ipsframework/services.py‎

Lines changed: 156 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import functools
77
import glob
88
import hashlib
9+
import json
910
import logging
1011
import logging.handlers
1112
import os
@@ -22,7 +23,7 @@
2223
import weakref
2324
from collections.abc import Callable, Iterable
2425
from copy import deepcopy
25-
from datetime import datetime
26+
from datetime import datetime, timezone
2627
from multiprocessing import Queue
2728
from operator import iadd
2829
from pathlib import Path
@@ -150,6 +151,12 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
150151
task_env = kwargs.get('task_env', {})
151152
new_env = os.environ.copy()
152153
new_env.update(task_env)
154+
diagnostics = getattr(worker, 'dvm_diagnostics', None)
155+
if diagnostics is not None:
156+
new_env['IPS_DVM_DIAGNOSTICS'] = str(diagnostics.path.resolve())
157+
new_env['IPS_DVM_INSTANCE'] = task_name
158+
diagnostics.record('instance_start', instance=task_name,
159+
instance_working_dir=str(working_dir_path))
153160

154161
if 'HWLOC_XMLFILE' in new_env:
155162
log.debug('Removing HWLOC_XMLFILE from task environment')
@@ -211,6 +218,8 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
211218
env=new_env,
212219
)
213220
except Exception as e:
221+
if diagnostics is not None:
222+
diagnostics.record('instance_launch_failed', instance=task_name, error=str(e))
214223
worker.log_event(
215224
'ips',
216225
{
@@ -234,7 +243,7 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
234243
{
235244
'event_type': 'IPS_DASK_TASK_END',
236245
'event_time': finish_time,
237-
'state': 'Succeeded',
246+
'state': 'Succeeded' if ret_val == 0 else 'Failed',
238247
'comment': f'task_name = {task_name}, elapsed time = {finish_time - start_time:.2f}s',
239248
'start_time': start_time,
240249
'elapsed_time': finish_time - start_time,
@@ -244,6 +253,8 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
244253
)
245254

246255
except subprocess.TimeoutExpired:
256+
if diagnostics is not None:
257+
diagnostics.record('instance_timeout', instance=task_name, timeout=timeout)
247258
worker.log_event(
248259
'ips',
249260
{
@@ -259,6 +270,8 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
259270
log.error(f'Task {task_name} with command {cmd} timed out after {timeout}s')
260271
ret_val = -1
261272
except Exception as e:
273+
if diagnostics is not None:
274+
diagnostics.record('instance_wait_failed', instance=task_name, error=str(e))
262275
worker.log_event(
263276
'ips',
264277
{
@@ -270,6 +283,8 @@ def launch(executable: Any, task_name: str, working_dir: str | os.PathLike, *arg
270283
)
271284
log.error(f'Task {task_name} with command {cmd} failed with {e!s}')
272285
finally:
286+
if diagnostics is not None:
287+
diagnostics.record('instance_end', instance=task_name, return_code=ret_val)
273288
if out:
274289
print(out)
275290
if err:
@@ -1373,6 +1388,24 @@ def wait_task(self, task_id: int, timeout: int = -1, delay: int = 1) -> int:
13731388
finish_time - task.start_time,
13741389
)
13751390

1391+
if task_retval != 0 and os.environ.get('IPS_DVM_DIAGNOSTICS'):
1392+
reference = os.environ['IPS_DVM_DIAGNOSTICS']
1393+
failure = dict(
1394+
event='mpi_task_failed', timestamp=datetime.now(timezone.utc).isoformat(),
1395+
instance=os.environ.get('IPS_DVM_INSTANCE'), task_id=task_id,
1396+
return_code=task_retval, command=task.command,
1397+
hostname=socket.gethostname(), process_pid=os.getpid(),
1398+
dvm_lifecycle=reference, dvm_state='unknown_in_child',
1399+
)
1400+
try:
1401+
# Each component process owns its own journal; no shared-file append races.
1402+
path = Path(self.get_working_dir()) / f'dvm-failures.{os.getpid()}.jsonl'
1403+
with path.open('a') as stream:
1404+
stream.write(json.dumps(failure) + '\n')
1405+
except OSError:
1406+
self.logger.exception('Unable to write DVM task failure diagnostics')
1407+
event_comment += f' return_code = {task_retval}; DVM lifecycle = {reference}'
1408+
13761409
self._send_monitor_event(
13771410
'IPS_TASK_END',
13781411
event_comment,
@@ -3221,15 +3254,55 @@ def send_ensemble_instance_to_portal(ensemble_name: str, data_path: Path) -> Non
32213254
return instances
32223255

32233256

3257+
3258+
class _DVMDiagnostics:
3259+
"""Worker-local, thread-safe lifecycle journal; constructed after plugin transfer."""
3260+
3261+
def __init__(self, directory, worker):
3262+
self.directory = directory
3263+
self.path = directory / 'lifecycle.jsonl'
3264+
self.lock = threading.Lock()
3265+
self.started = time.monotonic()
3266+
self.worker = worker
3267+
self.shutdown_requested = False
3268+
self.exit_recorded = False
3269+
3270+
def record(self, event, **fields):
3271+
with self.lock:
3272+
process = getattr(self.worker, 'dvm_proc', None)
3273+
code = process.poll() if process is not None else None
3274+
common = dict(
3275+
timestamp=datetime.now(timezone.utc).isoformat(),
3276+
elapsed_seconds=time.monotonic() - self.started,
3277+
dvm_id=self.directory.name,
3278+
hostname=socket.gethostname(),
3279+
worker_pid=os.getpid(),
3280+
worker_address=str(self.worker.address),
3281+
dvm_pid=process.pid if process is not None else None,
3282+
dvm_state=(
3283+
'not_started' if process is None
3284+
else ('running' if code is None else 'exited')
3285+
),
3286+
dvm_return_code=code,
3287+
signal=-code if code is not None and code < 0 else None,
3288+
shutdown_requested=self.shutdown_requested,
3289+
)
3290+
with self.path.open('a') as stream:
3291+
if code is not None and not self.exit_recorded:
3292+
stream.write(json.dumps(dict(common, event='exit_observed')) + '\n')
3293+
self.exit_recorded = True
3294+
stream.write(json.dumps(dict(common, event=event, **fields)) + '\n')
3295+
3296+
32243297
class DVMPlugin(WorkerPlugin):
32253298
def __init__(self, logger, working_dir, oversubscribe=False, hwthreads=False):
32263299
"""
32273300
Dask worker plugin to launch and manage an OpenMPI PRTE DVM on each
32283301
worker node.
32293302
32303303
:param logger: Logger object
3231-
:param working_dir: Directory for the DVM URI and log files; shared by
3232-
all workers, so file names are suffixed with host and PID.
3304+
:param working_dir: Parent of the persistent DVM diagnostic directories.
3305+
Each launch gets a unique directory containing host, PID, and UUID.
32333306
:param oversubscribe: Whether to allow oversubscription of nodes
32343307
when launching the ensemble runs. Default is False.
32353308
:param hwthreads: Whether to use hardware threads
@@ -3263,8 +3336,11 @@ def setup(self, worker: Worker):
32633336
self.logger.info('Launching DVM')
32643337
# The working dir is shared by all workers (possibly across nodes), so
32653338
# each worker needs a unique suffix.
3266-
suffix = f'{socket.gethostname()}.{os.getpid()}'
3267-
self.worker.dvm_uri_file = str(self.working_dir / f'dvm.uri.{suffix}')
3339+
suffix = f'{socket.gethostname()}.{os.getpid()}.{uuid.uuid4().hex}'
3340+
directory = self.working_dir / 'dvm' / suffix
3341+
directory.mkdir(parents=True)
3342+
worker.dvm_diagnostics = _DVMDiagnostics(directory, worker)
3343+
self.worker.dvm_uri_file = str(directory / 'uri')
32683344
Path(self.worker.dvm_uri_file).unlink(missing_ok=True) # never read a stale URI
32693345
# The command to launch the DVM. Note that we use `prte` instead of
32703346
# `mpirun` or `prun`. This is because we want to launch the DVM
@@ -3300,59 +3376,86 @@ def setup(self, worker: Worker):
33003376

33013377
# prte output goes to a file, not a PIPE: an undrained pipe can fill
33023378
# up and block the DVM, and the file survives for post-mortems.
3303-
self.worker.dvm_log_file = self.working_dir / f'dvm.log.{suffix}'
3379+
self.worker.dvm_log_file = directory / 'output.log'
33043380
self.worker.dvm_log = open(self.worker.dvm_log_file, 'w')
3381+
diagnostics = worker.dvm_diagnostics
3382+
diagnostics.record(
3383+
'launch_requested',
3384+
command=command,
3385+
working_dir=os.getcwd(),
3386+
environment={
3387+
key: os.environ[key]
3388+
for key in (
3389+
'SLURM_JOB_ID', 'SLURM_JOB_NODELIST', 'SLURM_JOB_NUM_NODES',
3390+
'PRTE_MCA_ras_slurm_use_entire_allocation',
3391+
'PRTE_MCA_rmaps_default_mapping_policy',
3392+
)
3393+
if key in os.environ
3394+
},
3395+
)
33053396
try:
3306-
self.logger.debug(f'Executing command: {command!s}')
3307-
self.worker.dvm_proc = subprocess.Popen(
3308-
command, stdout=self.worker.dvm_log, stderr=subprocess.STDOUT
3397+
worker.dvm_proc = subprocess.Popen(
3398+
command, stdout=worker.dvm_log, stderr=subprocess.STDOUT
33093399
)
3310-
except Exception as e:
3311-
print(f'Exception during setting up DVM: {e}', file=sys.stderr)
3312-
console.print(Traceback.from_exception(type(e), e, e.__traceback__))
3400+
diagnostics.record('launched')
3401+
uri_path = Path(worker.dvm_uri_file)
3402+
deadline = time.monotonic() + 30
3403+
while True:
3404+
if worker.dvm_proc.poll() is not None:
3405+
raise RuntimeError(f'DVM exited during startup; see {worker.dvm_log_file}')
3406+
uri = uri_path.read_text().strip() if uri_path.exists() else ''
3407+
if uri:
3408+
worker.dvm_uri = uri
3409+
break
3410+
if time.monotonic() >= deadline:
3411+
raise RuntimeError(f'DVM startup timed out; see {worker.dvm_log_file}')
3412+
time.sleep(0.1)
3413+
os.environ['PMIX_SERVER_URI41'] = worker.dvm_uri
3414+
diagnostics.record('ready', uri=worker.dvm_uri)
3415+
except Exception as exc:
3416+
diagnostics.record('startup_failed', error=str(exc))
3417+
self.teardown(worker)
33133418
raise
33143419

3315-
# Wait for prte to write its URI; fail loudly if it dies or stalls.
3316-
uri_path = Path(self.worker.dvm_uri_file)
3317-
deadline = time.time() + 30
3318-
while not (uri_path.exists() and uri_path.stat().st_size > 0):
3319-
if self.worker.dvm_proc.poll() is not None or time.time() > deadline:
3320-
raise RuntimeError(
3321-
f'DVM failed to start (exit code {self.worker.dvm_proc.poll()}), '
3322-
f'see {self.worker.dvm_log_file}:\n{self.worker.dvm_log_file.read_text()}'
3323-
)
3324-
time.sleep(0.1)
3325-
3326-
with open(self.worker.dvm_uri_file, 'r') as f:
3327-
self.worker.dvm_uri = f.readline().strip()
3328-
self.logger.debug(f'Read DVM URI: {self.worker.dvm_uri}')
3329-
3330-
os.environ['PMIX_SERVER_URI41'] = self.worker.dvm_uri
3331-
33323420
def teardown(self, worker: Worker):
3333-
self.logger.info(f'Shutting down DVM at {self.worker.dvm_uri}')
3334-
3335-
# On some systems we use `pterm` to shut down the DVM, and on others we
3336-
# use `prte-term`, so check for both.
3337-
pterm_cmd = shutil.which('pterm')
3338-
if pterm_cmd is None:
3339-
# On MacOS homebrew, pterm -> prte-term
3340-
pterm_cmd = shutil.which('prte-term')
3341-
if pterm_cmd is None:
3342-
# if it's *still* none, then there is a serious
3343-
# configuration problem.
3344-
self.logger.critical('Neither pterm nor prte-term command found')
3345-
else:
3346-
self.logger.debug(f'DVMPluggin.teardown(), pterm: {pterm_cmd!s}')
3347-
command = [pterm_cmd, '--dvm-uri', self.worker.dvm_uri]
3348-
subprocess.call(command)
3349-
# Regardless if we have `pterm` or `prte-term`, we can still just
3350-
# kill the process directly.
3351-
self.worker.dvm_proc.terminate()
3352-
self.worker.dvm_proc.kill()
3353-
self.worker.dvm_log.close()
3354-
3355-
self.logger.info('DVM shutdown')
3421+
diagnostics = worker.dvm_diagnostics
3422+
# Observe an already-dead DVM before marking this as intentional shutdown.
3423+
diagnostics.record('shutdown_begin')
3424+
diagnostics.shutdown_requested = True
3425+
process = getattr(worker, 'dvm_proc', None)
3426+
try:
3427+
if process is not None and process.poll() is None:
3428+
pterm = shutil.which('pterm') or shutil.which('prte-term')
3429+
if pterm and getattr(worker, 'dvm_uri', None):
3430+
command = [pterm, '--dvm-uri', worker.dvm_uri]
3431+
diagnostics.record('shutdown_command', command=command)
3432+
with (diagnostics.directory / 'shutdown.log').open('a') as output:
3433+
try:
3434+
result = subprocess.run(
3435+
command, stdout=output, stderr=subprocess.STDOUT, timeout=10
3436+
)
3437+
diagnostics.record('shutdown_command_end', return_code=result.returncode)
3438+
except (OSError, subprocess.TimeoutExpired) as exc:
3439+
diagnostics.record('shutdown_command_failed', error=str(exc))
3440+
else:
3441+
diagnostics.record('shutdown_command_unavailable')
3442+
try:
3443+
process.wait(timeout=10)
3444+
except subprocess.TimeoutExpired:
3445+
diagnostics.record('terminate_requested')
3446+
process.terminate()
3447+
try:
3448+
process.wait(timeout=5)
3449+
except subprocess.TimeoutExpired:
3450+
diagnostics.record('kill_requested')
3451+
process.kill()
3452+
process.wait(timeout=5)
3453+
diagnostics.record('shutdown_complete')
3454+
except Exception as exc:
3455+
diagnostics.record('shutdown_failed', error=str(exc))
3456+
self.logger.exception('DVM cleanup failed')
3457+
finally:
3458+
worker.dvm_log.close()
33563459

33573460

33583461
class TaskPool:

0 commit comments

Comments
 (0)