Changelog¶
[Unreleased]¶
[0.8.0] 2026-11-29¶
Added¶
DragonNativeExecutionBackend(backend namedragon_native) — a second Dragon backend besideDragonExecutionBackend, on Dragon'sProcess,ProcessGroup,PolicyandQueue, withoutdragon.workflows.batch. It takes the same task descriptions. Functions run in a persistent pool of workers, by default one per physical core, pinned to their hosts and CPUs (placed functions on a worker of that host, GPU tasks on a worker started for that GPU set), executables as one native process each, andprocess_templatesas one process group, with the PMI chosen bypmi. Unlike a Batch job, a group has no PMI by default. A relay process on the client's node trades tasks and results with the client in batches, so a client process that keeps its GIL busy still starts tasks quickly. Seedocs/execution/dragon-native.md.tests/integration/test-hpc/benchmarks/dragon_throughput.pymeasures it with--with-rhapsody-dragon-native, and--workers_per_nodesets its pool size;tests/performance/dragon_native_busy_client.pymeasures it next to a busy thread.DragonNativeExecutionBackend(hosts=...)limits a backend to some of the runtime's nodes: its pool, its unplaced tasks (process tasks and group templates whose policy names no node included, a template's ranks in blocks over the nodes), its process slots and the placements it accepts.hosts="local"is the client's node, so several clients of one multi-node runtime can each keep their pool on their own node without importing Dragon. A list names nodes as Dragon does (the ids intopology()); a name that is not a Dragon node fails the start, with Dragon's name for it where the backend can tell. Telemetry still samples every node.- Telemetry (experimental): every backend has an emitter.
backend.telemetryis a no-op emitter (enabledisFalse) until the telemetry manager attaches the backend and hands it a real one through the newBaseBackend.register_emitter/DataBackend.register_emitterhook (the counterpart ofregister_callback; override it to react). A backend reports plain data withself.telemetry.emit(name, attributes)and never imports OpenTelemetry.Sessionnow also attaches data backends to telemetry (emitter only: no resource adapter). A failing emitter handoff is now logged as a warning with its traceback instead of at debug level. - Telemetry (experimental): instrumentations. A backend names its domain with the class
attribute
telemetry_domain(onBaseBackendandDataBackend); the manager hosts the instrumentation registered for it (rhapsody.telemetry.instrumentation:Instrumentation,register_instrumentation) and routes the backend's events to it. See "Backends, emitters and instrumentations" in the telemetry reference. -
Telemetry (experimental): inference telemetry for
DragonVllmInferenceBackend. Per batch: onechat {model}span (real start and end, linked to the task spans of the batch), per-task attributes (batch id, prompt count, queue wait, timeouts), histograms of the request queue wait, batch duration and Dragon's model time, and counters of requests, prompts, timed-out prompts and batches. Prompt and response text is never carried. Names follow the OpenTelemetry GenAI conventions, which are still in development. See "Inference telemetry" in the telemetry reference. -
Agent Skills:
skills/rhapsody-telemetry/teaches AI coding agents to turn on, watch, read, export and diagnose RHAPSODY telemetry (low concurrency, long waits, failures by error type, idle GPUs, memory pressure), with stdlib snippets that read the JSONL checkpoint inreferences/diagnosis.md.TaskStartedstill marks when a backend accepted a task, not when it started, so the skill states that limit and its wait and concurrency readings print a warning.rhapsody-executionnow names it.
Changed¶
-
The
telemetryextra needsopentelemetry-sdk>=1.30.0(was 1.20), only for the histogram bucket advice of the inference durations. -
Telemetry (experimental): task and resource metrics are recorded by a task instrumentation instead of the
TelemetryManager. Instrument names, descriptions, attributes, values, therhapsodymeter scope andtask_count()/summary()are unchanged (a golden test pins them). The manager now hosts instrumentations and routes events to them. Three small differences: a failing metric update no longer skips that event's task span update, and the reverse; a failing metric update is logged as a warning once per backend and instrumentation, then at debug level, instead of one error per event; and a restarted manager no longer carries running-task and node-resource state over from the previous run. -
BEHAVIOUR CHANGE:
DragonVllmInferenceBackendkeeps the exception object of a failed batch. When the batch processor fails a batch,task["exception"]is now the exception itself (it was its text). Telemetryerror_typeof such a task is the exception class instead of"str",await taskof such an AITask now raises that exception (before, it returned normally), AsyncFlow reports the original exception class instead of a wrappedRuntimeError, andSession.wait_tasks()is unchanged. -
BEHAVIOUR CHANGE: a failing batch no longer fails the requests that wait in the queue.
DragonVllmInferenceBackendused to fail the batch it was processing and every pending request, including requests that were never sent. It now fails only the batch it was processing; the pending requests go into the next batch. If the pipeline stays down, each following batch fails in turn (one batch window and one error log each), so the requests still fail, one batch at a time instead of all at once. -
Telemetry (experimental, BEHAVIOUR CHANGE): the batch end event
rhapsody.inference.BatchEndedis split intoBatchDoneandBatchFailed.BatchDoneis emitted when every prompt of the batch was answered.BatchFailedcarries the same fields pluserror_type(the exception class name) and is emitted when prompts timed out (before, such a batch ended withBatchEnded), when Dragon answered a prompt with an exception, and when the batch processor fails a batch (before, that path emitted no end event at all). Code that subscribes toBatchEndedor reads it from the JSONL file must handle both names. The batch span of a failed batch is closed with status ERROR and theerror.typeattribute; the metrics are recorded as for a good batch.
Removed¶
-
BEHAVIOUR CHANGE: RADICAL-Pilot backend —
RadicalExecutionBackend(rhapsody.backends.execution.radical_pilot) and its tests are removed, with no deprecation period, along with theradical_pilotextra, itsrhapsody.backendsentry point, theradical_pilotpytest marker, themake test-rptarget and the RADICAL-Pilot sections of the docs and skills.discover_backends()andBackendRegistryno longer report aradical_pilotbackend:from rhapsody.backends import RadicalExecutionBackendnow raisesImportError,get_backend("radical_pilot")raisesValueError("Backend 'radical_pilot' not found ..."), andpip install "rhapsody-py[radical_pilot]"no longer installs RADICAL-Pilot. For HPC execution, useDragonExecutionBackend; "Coming from RADICAL-Pilot" indocs/getting-started/resource-specification.mdmaps the old task keys. The data-linking hooks onBaseBackend(supports_implicit_data_linking,supports_explicit_data_linking,link_implicit_data_deps,link_explicit_data_deps) stay as a backend-neutral extension point; no built-in backend declares them now. -
radical.profprofiling inOrbitExecutionBackend— the optional, undeclaredradical.profimport (a standalone profiling package, not on PyPI) and itstask_submit,task_batch_flushandtask_completeevents are removed. radical.orbit'sexamples/analyze_rhapsody.pyreads these events and will be updated on the Orbit side. Orbit task execution is unchanged.
Fixed¶
- A cancelled command stops its process —
cancel_task()onConcurrentExecutionBackendreportedCANCELEDwhile the task's command ran on to the end, with whatever it was using. The backend now sends SIGTERM to the command and the processes it started, and SIGKILL to what is left afterterm_graceseconds (5 by default), and reportsCANCELEDonce they have stopped, socancel_task()can take up to that long to return. Each command runs in its own session, because killing a shell alone leaves its children running: a signal sent to the process group of the caller, such as Ctrl-C in a terminal, no longer reaches commands directly.shutdown()andasyncio.run()stop them instead.shutdown()now waits for the commands, and a repeatedcancel_task()no longer reports the task twice. - A task's function is pickled once, not once per task.
DragonNativeExecutionBackend(pool tasks) andConcurrentExecutionBackendon a process pool cloudpickled each task's function again. For a function cloudpickle cannot import by name (a closure, a lambda, a function of__main__), each pickle scans every loaded module, so in a process that has loaded a few thousand modules a task wrapped in two closures cost about a millisecond of the event loop's time. A function's pickle is now kept, once a second pickle of it comes out the same, and given again while nothing it holds has changed: the function and its code, closure, defaults, attributes and the globals its code reads, and the functions, containers, cells and type hints among them, are the same objects with the same contents. A function holding an object whose changes cannot be seen this way (an instance, a class or module pickled by value) is pickled for every task, as before, at about the cost ofcloudpickle.dumps, and so is a function that changes before every task or whose pickle has been over 1 MB. A closure made for a single task is never kept. The native backend still loads a task's function and arguments on the worker as from one pickle, so an object both hold stays one object. - BEHAVIOUR CHANGE: the native backend's worker message is
(uid, fn_data, rest). It was(uid, body): a worker and a client of different versions cannot run each other's tasks. DragonNativeExecutionBackendno longer holds the event loop for a whole batch.submit_tasksbuilt every task of a batch in one go, and the result thread's batches of task states were handed to the callback in one loop callback: a batch of a few thousand tasks held the loop for seconds, and every other coroutine of the process with it. Both now let the loop run every 20 ms. A task that a submit has not reached yet can be cancelled, and is cancelled at shutdown.- BEHAVIOUR CHANGE:
DragonNativeExecutionBackend.cancel_taskreturnsTruefor a task of a batch still being submitted, and reports it CANCELED; it returnedFalsefor a task the backend had not built yet. A CANCELED callback that raises anExceptionis now logged, and the other CANCELED states and the cancel itself go on;cancel_taskused to raise it to its caller. - BEHAVIOUR CHANGE:
DragonNativeExecutionBackend.submit_taskscalls can interleave. Two concurrent calls now build their tasks in turns, 20 ms at a time. A call cancelled midway leaves the tasks it already built running and reports the rest CANCELED; after any other error the caller fails the batch, as before. - The telemetry checkpoint file can be followed during a run. The docs said the JSONL file
is line-buffered and can be read with
tail -f; since it moved to a 128 KB buffer it stayed empty until the buffer filled or the session closed, unlesscheckpoint_intervalwas set. The manager now flushes it about a second after events are written (one timer at a time, so at most one write per second and nothing while no events arrive). The buffer stays, andcheckpoint_intervalstill sets the metric and span snapshots. - Telemetry on GPU nodes: per-GPU samples no longer overwrite the node's values. Each poll
sends a node-level
ResourceUpdateand then one per GPU, which carries only that GPU'sgpu_percent.summary()["resources"]kept the last of them, so on a GPU node it showed CPU, memory, disk and network asnull, and thenode_gpu_utilizationmetric ended at the last GPU's value instead of the busiest one. Both now use only the node-level sample, whosegpu_percentis the busiest GPU; the per-GPU events are unchanged. A custom adapter that sends only per-GPU samples no longer appears insummary()["resources"]or in the node metrics. - Telemetry under Dragon no longer keeps a core busy. The Dragon telemetry adapter runs its
resource samplers as a Dragon
ProcessGroup, and Dragon 0.15's group client watches the group's exception queue in a thread that spins a whole core for as long as the group runs: every process with RHAPSODY's telemetry on under Dragon carried one, and at interpreter exit, with telemetry not stopped, the process never ended. The group now ignores errors on exit, so Dragon starts no such thread; a sampler that fails costs only its node's readings, as before. - Telemetry costs less CPU per task. An application with tens of thousands of tasks per engine
sends six events per task through the telemetry manager (an AsyncFlow engine does), and each cost
more than it had to. The task counters and the running-tasks gauge are now tallied in the
instrumentation and read by observable instruments when metrics are collected, instead of one
instrument call per lifecycle event; each finished task still records its duration as it ends.
A subscriber's kind (coroutine function or not) is found once, when it subscribes, not for every
event; the checkpoint writer reuses one JSON encoder and each event class's field names; a task
span's final attributes are set in one call; and event ids come from a generator of their own
(seeded from
os.urandom, seeded again in a forked child) instead of a system call per event.summary(),task_count(),task_spans(),read_traces(),read_metrics()and the checkpoint file give what they gave. One difference for a metric reader passed withmetric_readersthat sets its temporality per instrument kind: the task counters are nowObservableCounterandObservableUpDownCounterinstruments, so such a reader must name those kinds to get them as deltas (OTLP'sDELTApreference does). -
BEHAVIOUR CHANGE:
ConcurrentExecutionBackendlets go of a task once it has reported the task's final state. It kept every task it ran intasks, and each task's handler (an asyncio task) in the task's"future", so an engine on it kept every task, and in Python 3.12 eachasync deffunction task cost more than the one before (asyncio.runwalks every live asyncio task). Nowtasksholds only the tasks that have not ended, and a task that ended has no"future"; its results stay in the task.cancel_all_tasks()returns the number of tasks that were still running, not of every task the backend ran. A task cancelled before it started, a later task with the same uid, and a handler that an eager task factory ran to its end insidesubmit_tasksare handled too. The noop backend no longer keeps a finished asyncio task per task under an eager task factory. -
DragonVllmInferenceBackend: aqueue.Emptyfromget_nowait()no longer fails a whole batch — the response loop calledempty()and thenget_nowait(). Dragon documentsempty()as unreliable, soget_nowait()could still raisequeue.Empty, and the batch processor then failed the batch. The loop now only callsget_nowait()and treatsqueue.Emptyas "no answer yet". -
DragonVllmInferenceBackend: a prompt that Dragon answers with an exception object fails its task — a worker that fails a prompt puts the exception object in the response queue (RuntimeError(...)), which was returned as the prompt's result and the task was reported DONE. The task is now reported FAILED withtask["exception"]set to that exception; the prompt's result is"ERROR: <class>: <message>"; the batch ends withBatchFailed. The string"LLM inference failed ..."that Dragon sends for a failed whole batch is not detected (it has no marker): such a task is still reported DONE. -
DragonVllmInferenceBackend:generate([])no longer hangs — a request without prompts was never answered, so the call waited until its timeout.generate()now raisesValueErrorfor an empty prompt list. AnAITaskcannot have an empty prompt (its constructor refuses it); a plain dict task without prompts is still not validated and is never finished. -
Telemetry: a batch that fails in the batch processor now ends its batch span — the batch span stayed open until the next batch or the end of the session, ending with "batch did not finish", and the queue times of its tasks were missing. It now emits
BatchFailed(see above). A batch cancelled while in flight (for example by a shutdown) still emits no end event. -
DragonVllmInferenceBackend: late responses after a batch timeout no longer leak into the next batch — the answers of a batch that timed out used to stay in the one response queue shared by all batches, and the next batch read them as its own, so a task could get another task's text and be reported DONE with healthy-looking telemetry (issue B2). A batch that gives up now hands its response queue to a background task that reads and discards the late answers and then closes it; the next batch uses a new queue. Batches that are fully read still share one queue, so nothing is allocated per batch. Shutdown now runsInference.destroy()in a thread with a bounded wait (120 s) while the late answers are discarded. This also removes a shutdown hang: with the old code, one timed-out batch of 224 prompts (more late answers than one 100-slot response queue holds) madeshutdown()hang, and with this change it returns in a few seconds. Checked with a 0.5B model on one node with one GPU (1 hang in 1 run before, no hang in 5 of 5 runs after) and on two nodes with one GPU each (no hang in 5 of 5 runs after; the old code was not run there). -
BEHAVIOUR CHANGE:
DragonVllmInferenceBackendreports a timed-out AITask as FAILED, not DONE — when some prompts of a task got no response within the batch deadline (300 s), the task was reported DONE with"ERROR: Timeout ..."strings as its response. It is now reported FAILED, withtask["exception"]set to aTimeoutErrorand the partial response kept (answered prompts plus theERROR:strings).Session.wait_tasks()now sees the failure, and in AsyncFlow the dependents of such a task no longer run.generate()and the HTTP endpoints are unchanged. The deadline covers the whole batch, not each task: if a batch takes longer than 300 s, every task with a prompt still unanswered at that point is FAILED, including tasks whose prompts were last in the batch. The deadline is the module constant_BATCH_RESPONSE_TIMEOUT_S. -
Executable tasks submitted through
OrbitExecutionBackendnever completed — the radical.orbit rhapsody plugin sends DONE notifications withoutstdout, and an executable's result is its stdout, so the consumer's callback failed (KeyError: 'stdout') and the task's future never resolved. For a DONE executable withoutstdout, the backend now fetches the task (get_task) and fires DONE with its output. If the fetch fails, or the fetched task carries nostdout(as a pool dispatcher's task record does), the task is reported FAILED with the reason. A cancel while the fetch runs is a no-op, since the task has already finished, andshutdown()waits for fetches in flight. - Telemetry:
Failed to detach contexterror at shutdown, and task spans without a parent —TelemetryManager.start()attached the session span as the ambient OTel context of the asyncio task that called it. Whenstop()ran in another task, OTel loggedERROR Failed to detach context(ValueError: ... was created in a different Context). Task events emitted from a context the session never touched, e.g. ORBIT callbacks, gave task spans without a parent. The ambient session span also leaked into the caller's OTel context. The session span is now never attached: it is the explicit parent of task and scope spans that have no caller span.
[0.7.0] 2026-11-09¶
Changed¶
-
HPC test suite restructured into groups —
tests/integration/test-hpc/run_suite.pyrunstasks,placement,scale, andmpias separatedragonlaunches in one allocation, each with a time budget, and merges the results into one JUnit file. A crash or hang costs that group, not the whole run, and appears as a failed<group>.launchertest. Duplicate tests were merged, leaving 19 tests instead of 24, and GPU tests now check the exact GPU assigned.RHAPSODY_RUN_SCALEis removed: use-m scale. The newRHAPSODY_HPC_REQUIREturns a missing capability into a failure instead of a skip. The throughput benchmark moved totests/integration/test-hpc/benchmarks/dragon_throughput.py. -
Task metrics no longer carry
task_id—tasks_*andtask_duration_secondsaggregate per (session, backend, executable, task_type). Thetask_idattribute opened a new metric series for every task: memory grew with the task count, and it was the most expensive part of per-event processing. Per-task identity stays on the task spans; dashboards that grouped these metrics bytask_idneed to use the spans. Event ids are built without aUUIDobject (still UUID4 hex). Together about 30% less telemetry cost per task and per dependent step. - Dragon pin raised to
dragonhpc==0.15.0in thedragonextra (was==0.14.1). radex needsDDict.wait_for_keys()(first in 0.14.2), and 0.15.0 supports co-located attach to a running Dragon runtime, which 0.14.1 lacks. Dragon start-up and teardown are noticeably slower on 0.15.0 (35-60% longer Dragon test suites on Perlmutter). Because thebackends/allextras also includedragon, they now resolvedragonhpc[ai]at 0.15.0 (vLLM>=0.11,<0.20); theaiextra on its own stays unpinned.
Fixed¶
- Telemetry dropped events on
stop()—stop()gave the event backlog a fixed 5 s to drain and then dropped the rest, logging only that the drain had not finished: a 100k-task session lost 59% of its task events. It now queues the stop sentinel behind the backlog and waits for the dispatch loop to reach it, as long as the backlog shrinks (logging progress). A crashed dispatch loop is reported at once, a stalled one is cancelled after one stall window, and both warnings give the number of events not processed.start_telemetry(drain_on_stop=False)skips the backlog instead (discarded with a warning) for a fast shutdown, e.g. close to a job walltime. tasks_runningcounted tasks that never ran — a task that ended before RUNNING decremented the gauge without a matching increment, and its -1 could land on a different label set than its +1. Each task now counts once, and its -1 uses the labels of its +1.-
DragonExecutionBackendoversubscribed partial-node Slurm allocations (#95) — Dragon'sBatchstartsos.cpu_count() // 2workers per node, even when the job may use only part of the node: a 4-CPU job on a 512-CPU node got 256 workers on those 4 CPUs, and every task took minutes. When the job may use fewer physical cores than that on the nodes Batch uses, the backend now passesworkers_per_node(one per allowed core on the smallest node) and logs a warning. Batch's placement capacity for process and MPI jobs is unchanged, so those jobs still place ranks as if the job had whole nodes. Aworkers_per_nodeinbatch_kwargstakes precedence;size_pool_to_affinity=Falsekeeps Batch's sizing and only warns. Whole-node allocations are unchanged. Supersedes theNode.num_cpuspatch first proposed in #106, which also shrank the placement capacity and hung process jobs with more ranks thanallowed // 2. -
Dragon process/job exit codes reported like the other backends — a non-zero exit code from a
process()/job()task (executables, and functions run viaprocess_template/process_templates) no longer becomes aSystemExitintask["exception"], which exited the caller when the task was awaited.task["exit_code"]is now set (0on success; for a job, a non-zero code from Dragon's per-rank list, whose order is not guaranteed — all codes stay intask["return_value"]), and awaiting a failed task raisesTaskExecutionError(uid, stderr, exit_code)with the task's stderr (for templated functions, the rank's traceback), as documented and as the concurrent and dask backends do.task["exception"]staysNonefor these failures. - Dragon-side cancellations reported off the event loop — when Dragon
cancelled a task itself (a timeout or an upstream cancel, surfacing as
TaskCancelledErrorfromget()),DragonExecutionBackendcalled the registered callback withCANCELEDdirectly on itsdragon_monitor_loopthread, whileDONE/FAILEDwere handed to the event loop withcall_soon_threadsafe. Consumers that touch asyncio from the callback had those calls rejected (and the error swallowed by the monitor loop), so dependents waited on their own periodic scans. Cancellations now take the samecall_soon_threadsafepath; a task already reported bycancel_task()is still reported only once. - Dragon MPI jobs launched with Cray's PMI everywhere —
DragonExecutionBackendpassed no PMI toBatch.options(), so everyprocess_templatesjob got Batch's default,PMIBackend.CRAY. That is right for Cray MPICH, but with Open MPI each rank ran as a one-rank job with no error (Open MPI 5), or every rank exited 1 (Open MPI 4.1). A newpmiargument ("pmix","cray","none"or aPMIBackend) sets the PMI for every job, and"pmi"in a task'stask_backend_specific_kwargsoverrides it; only job submissions get it, and an unknown name fails any task. With neither, Batch's default is kept, and a warning is logged once for each kind of job it can break: an executable with several ranks, and a Python function with one rank or with several. Under Cray MPICH (CRAY_MPICH_DIRorCRAY_MPICH_VERSIONset), where that default is right, a debug line takes its place. The first multi-rank job without atimeout, or withNone, which now means the default, logs a warning too: when a rank dies, Dragon does not end the job, and the other ranks wait until the timeout (1e9s by default)."pmi": "none"declares a job's processes non-MPI: they run without a PMI, and neither warning is logged. No job is refused. -
Example 02's and the tutorials' parallel function jobs crashed on a non-Cray node — with Batch's default PMI, every rank of a 2+2 Python function job aborted with "double free or corruption" (exit code -6) under Dragon 0.14.1 and 0.15.0. Their parallel jobs now set
"pmi": "none". -
pip install rhapsody-py[dragon]could not import Dragon'sBatch— dragonhpc 0.15.0 importsrequestsindragon.workflows.batch, but lists it only under its own extras, so a plain install failed withModuleNotFoundError: No module named 'requests'. Thedragonextra now requiresdragonhpc[requests]==0.15.0. -
discover_backends()reports real availability — a backend is available only when its runtime dependencies are importable (newBaseBackend.is_available()); Dragon, RADICAL-Pilot and Orbit were reported available without them. OrbitExecutionBackendis exported fromrhapsody.backends, like the other backends.- Docs: real
DragonExecutionBackendconstructor, noSession.get_statistics(), correct default session uid, removed never-implementedRHAPSODY_LOG_LEVEL/RHAPSODY_WORK_DIR.
Removed¶
- Python 3.9 and 3.10 support — RHAPSODY now requires Python 3.11 or
newer (
requires-python = ">=3.11"). Python 3.9 reached end of life in October 2025 and 3.10 in October 2026, and CI no longer tests them. The 3.8, 3.9 and 3.10 classifiers are gone, and the install, contributing and AI backend docs say 3.11.
Added¶
- Agent Skills —
skills/rhapsody-execution/teaches AI coding agents to run RHAPSODY workloads (backends, tasks, resources, CPU/GPU affinity, failures, multi-node Dragon).
[0.6.0] 2026-10-19¶
Fixed¶
DaskExecutionBackendPicklingError on async function tasks —submit_taskswrapped every async callable in a local closure decorated with@functools.wraps(task["function"])before submitting it.@wrapscopies the original function's__module__/__qualname__onto the closure, so pickling it by reference resolved to a different object living at that name and raisedPicklingError: Can't pickle <function ...>: it's not the same object as module.name. Dask workers already natively detectiscoroutinefunction()on a submitted callable and run it on the worker's own event loop (no thread pool) — sync and async callables are now both submitted directly (optionally throughfunctools.partialto pre-bind kwargs), eliminating the wrapper entirely rather than patching around it.DaskExecutionBackend._check_resources_satisfiable()could never detect a satisfiable resource request — it calledClient.scheduler_info(), which for an asynchronous client always returns a cached snapshot with an emptyworkersmapping (see that method's own docstring). Every resource-constrained task failed regardless of whether a matching worker actually existed. Fixed to useawait client.scheduler.identity(), Dask's own documented alternative for a live per-worker view (called with non_workers=kwarg — that parameter is absent on olderdistributedreleases still within this project'sdask[distributed]>=2023.0.0support range and raisesTypeErrorthere).DaskExecutionBackendcould silently share one DaskFutureacross two distinct tasks —client.submit()defaults topure=Truewith no explicitkey, deriving the Dask key fromtokenize(func, kwargs, *args). Two RHAPSODY tasks calling the same function with the same arguments tokenized to the identical key, so the secondsubmit()silently returned the first task'sFutureinstead of doing independent work. Fixed by always passingkey=task["uid"](unless the caller already set one viatask_backend_specific_kwargs).DaskExecutionBackend.shutdown()always closed the DaskClient, even one the caller supplied viaclient=/cluster=— the constructor already tracked_client_provided/_cluster_providedbut never consulted them at shutdown. Ownership is now tracked explicitly (_owns_client) andshutdown()only closes a client this backend created itself.
Changed¶
DaskExecutionBackendno longer mutates the caller's task dict for submission bookkeeping:task["args"]is no longer rewritten, andasyncio.Futurearguments are no longer silently filtered out ofargs(nothing in RHAPSODY's task contract puts one there; a genuinely unpicklable argument now surfaces as a real, attributable submission failure on that task instead of silently shifting positional args). The DaskFuturehandle moved off the shared task dict into a private per-task runtime record.DaskExecutionBackend.submit_tasks()now raisesValueErrorimmediately for a task specifying neitherfunctionnorexecutable, instead of recording it as a per-taskFAILEDcallback — this is a caller programming error, not a runtime submission failure. Also raisesBackendErrorif the Dask client itself is unusable (e.g. scheduler connection lost), rather than attributing a whole-backend outage to whichever task happened to be submitting at the time.DaskExecutionBackendnow requires an externally-suppliedclient=to have been constructed withasynchronous=True; raisesValueErrorat init time otherwise instead of failing confusingly later.- Registered callbacks on
DaskExecutionBackendmay now be sync or async callables; a raising callback is caught and logged instead of corrupting task completion state.
Added¶
- Data-linking capability flags on
BaseBackend—supports_implicit_data_linkingandsupports_explicit_data_linking(bothFalseby default;TrueonRadicalExecutionBackend) declare which data-linking hooks a backend implements. Workflow engines such as AsyncFlow calllink_implicit_data_deps/link_explicit_data_depsonly on backends that declare the matching capability. Backends declaring explicit linking must return a data-dependency descriptor containing at least"target". Previously AsyncFlow called the hooks on every backend and expected a descriptor that only RADICAL-Pilot returned, so any explicitOutputFile→InputFiledependency shut the engine down on all other backends. examples/07-dask-backend-slrum-cluster.py—DaskExecutionBackendagainst a real Slurm allocation viadask_jobqueue.SLURMCluster, including theasynchronous=True/async withconstruction required for non-LocalClustercluster managers driven from async code (seedocs/getting-started/advanced-usage.md#dask-distributed-backend). Documented inexamples/README.md.- Regression tests for all four fixes above, plus client/cluster
ownership-on-shutdown tests, async-callback and callback-isolation tests, and a
test proving the deleted
@wraps-closure pattern really did break pickling. - New
rhapsody.backends.datapackage, introducing two data backends: RedisDataBackend— launches and owns one or more independentredis-serverprocesses and hands back ahost:portendpoint per node.DragonDataBackend— constructs and owns a DragonDDictand hands back its serialized descriptor.- Both follow a shared
DataBackend/Endpointlifecycle (state machineCREATED → STARTING → {READY, FAILED},{CREATED,READY,FAILED} → SHUTDOWN; idempotentstart()/shutdown();await RedisDataBackend(...)/await DragonDataBackend(...)as a single step, consistent with every execution backend), and neither constructs a client itself — callers build whichever client they want (RADEX's typed clients, or a native one likeredis-py/dragon.data.ddict.DDict.attach()) from the endpoint. Sessionnow acceptsDataBackendinstances in the same list/add_backend()call as execution backends, for shared lifecycle/work_dirbookkeeping and inclusion insession.close().- New docs: AI, Data, and Execution top-level sections
(
docs/ai/index.md,docs/data-backends/{index,redis,dragon}.md,docs/execution/index.md). - New examples under
examples/data/: paired Redis/Dragon producer/consumer scripts, once using RADEX's typed clients and once using plainredis-py/nativedragon.data.ddict.DDict.
[0.5.0] - 2026-08-20¶
Added¶
OrbitExecutionBackend— submits tasks to a remote HPC node through the ORBIT broker/endpoint infrastructure (radical.orbit); the endpoint node runs a RHAPSODY plugin with a local backend (e.g. Dragon) that actually executes the work. Delegates toRhapsodyClientinternally, inheriting template compression, pipelined batching, and event-based wait/batch notifications.NoopExecutionBackend— tasks are markedDONEimmediately without executing anything; for benchmarking RHAPSODY's own submission/orchestration overhead independent of any real backend.- Dragon 0.14.1 public API migration completed for
DragonExecutionBackend— task metadata (name,timeout,stdout/stderr) now goes throughBatch.options()rather than direct kwargs toprocess()/job()/function(), matching the 0.14.1 API.V1/V2backends and theBatchError/Policyimports they required are removed;DragonExecutionBackendV3is kept only as a deprecated alias. DragonVllmInferenceBackendmigrated todragon.ai.inference— moved fromrhapsody.backends.inferencetorhapsody.backends.ai, and from a YAMLconfig_file=argument to typed config objects (ModelConfig,HardwareConfig,BatchingConfig,GuardrailsConfig,DynamicWorkerConfigin the newrhapsody.backends.ai.config), re-exported as-is fromdragon.ai.inference. Breaking change for existing callers still passingconfig_file="config.yaml"— seedocs/ai/index.mdfor the new constructor shape.DragonVllmInferenceBackendnow supportsawait DragonVllmInferenceBackend(...)as a single step, consistent with every other backend (DragonExecutionBackend,ConcurrentExecutionBackend,DaskExecutionBackend,RadicalExecutionBackend). The existing two-stepbackend = DragonVllmInferenceBackend(...); await backend.initialize()pattern still works unchanged. Docs, README, examples, and the tutorial notebook updated to the new pattern.- conda packaging — added a conda-forge staged-recipes candidate
(
recipe/meta.yaml), excluded from thecheck-yamlpre-commit hook since conda recipes use Jinja templating that isn't plain YAML. - ReadTheDocs configuration (
.readthedocs.yaml) — builds docs viamkdocs, installing the.[docs]extra.
Fixed¶
__version__drifted from package metadata — the 0.4.0 sdist shipped__version__ = "0.2.0"whilepyproject.tomlsaid0.4.0.__version__is now derived from the installed distribution's metadata (importlib.metadata.version("rhapsody-py")), sopyproject.tomlstays the single source of truth and the two can't drift again.- Task completions silently dropped under load —
submit_tasks()used to register each task into_monitored_batchesonly after building the entire batch, so a fast task could complete and be polled by the monitor thread before its own registration landed; the monitor loop then treated the unmatched tuid as "already delivered as cancelled" and dropped the result permanently.build_task()now registers each task immediately after Dragon dispatch, and the monitor loop buffers (_pending_tuids) and retries any tuid that arrives before registration instead of assuming cancellation.cancel_task()now marks confirmed cancellations in_cancelled_tuidsso genuinely cancelled tuids are still discarded immediately. - Dragon exit codes not surfacing as
FAILED— Dragon 0.14.1'sprocess()/job()tasks return a non-zero exit code as the task result instead of raising, so a failed executable was silently reportedDONE. Non-zeroint/list[int]results from process/job tasks are now normalized to a raisedSystemExitso RHAPSODY deliversFAILEDas expected. runinfo/directory left behind after every run — Dragon'stask_logsfeature (needed socapture_stdio=Falsetasks get real stdout/stderr content back viaget_stdout()/get_stderr()) creates aruninfo/<run-id>/tree andmanifest.jsonlin the working directory.shutdown()now removes it viaBatch.log_dir()afterjoin()/destroy()complete.- CI silently reporting broken Dragon installs as "skipped" —
make test-citreated anytest-dragon-onlyfailure (dragon launcher genuinely missing, or dragon present but broken) as "Dragon not available on this Python version" and reported success either way. It now only skips when thedragonlauncher itself isn't onPATH; a real test failure now fails the build. - Missing
flask/gunicorndependency —dragon.workflows.batchimportsdragon.telemetry.telemetryunconditionally, which requiresflask/gunicorneven when telemetry is never used;dragonhpc's own package metadata doesn't declare them. Added to thedragonextra inpyproject.toml, and CI now installs viapip install -e ".[dragon]"instead of a barepip install dragonhpcso the extra actually takes effect. - Stale test assertion in
test_monitor_loop_get_called_after_pollexpectingget(block=False); the code correctly callsget(block=True)(poll() and the DDict write aren't atomic) since an earlier fix — the test just never caught up.
[0.4.0] - 2026-06-11¶
Added¶
- Dragon 0.14.0 full migration —
DragonExecutionBackendV3is fully ported to the DragonHPC 0.14.0 API. Key changes: - Sharded DDict — task results are now read from the correct DDict shard
using
results_ddict.manager(shard_idx)[tuid], matching how Dragon 0.14.0 writes results permanager_idx. The previous unsharded access caused the monitor loop to block indefinitely. - Real task cancellation —
cancel_task()now calls Dragon'sbatch_task.cancel()instead of a soft/fake cancel. Cancelled tasks are eagerly removed from both_task_registryand_monitored_batches, preventing the monitor thread from stalling on DDict polls for tasks that will never deliver results. - Stdout capture restored — Dragon 0.14.0 removed the unconditional
stdout=Popen.PIPEthat Dragon 0.13.2 applied automatically. RHAPSODY now explicitly injects it across all fiveProcessTemplateconstruction paths so stdout is captured for every process and executable task by default. Users can override it viaprocess_template. -
Python 3.13 support — Dragon 0.14.0 extends support to Python 3.13; the CI matrix and
pyproject.tomlextras comment are updated accordingly. -
HPC integration test suite (
tests/integration/test-hpc/dragon/) — 25 end-to-end tests across five categories: multi-node GPU execution, single-node GPU, task pinning and affinity, scale/stress (10 K+ tasks), and MPI (mpi4py gather/allreduce/broadcast). Topology is detected dynamically fromdragon.native.machine.System; tests auto-skip when the required resources are absent. The entire suite is excluded from CI via apytest_ignore_collecthook and only runs on a live cluster withRHAPSODY_HPC=1. -
HPC machine guides — new setup guides for PSC Bridges-2 (SSH-based Dragon launcher with TCP transport) and Purdue Anvil (Cray PE stack, identical to Delta). The HPC machines index now clarifies that
ConcurrentExecutionBackendworks out of the box on every machine, whileDragonExecutionBackendV3requires machine-specific configuration documented per page. -
Team and contributor documentation —
docs/project/team.mdandREADME.mdupdated to credit both the RADICAL Research Group (Rutgers) and the HPE team.
Changed¶
-
TaskStateManager.update_task— removed per-callasyncio.get_running_loop()/try-except RuntimeErroron-loop detection. All backends already call this from the event loop; the check was firing 128 K+ times per 64 K-task workload and always taking the inline branch. The method now calls the implementation directly. Unusedasyncio.Lockalso removed. -
_build_process_template_kwargshelper — ProcessTemplate construction across all five task priorities is consolidated into a single helper, adopted from theashao/dragon-executor-hanging-bugfixbranch and adapted for RHAPSODY'sstdout_pipesemantics. Co-Authored-By: Andrew Shao (HPE).
Fixed¶
-
Monitor loop race condition — the two-step
if tuid not in dict/dict[tuid]access in_monitor_loopwas a TOCTOU race withcancel_taskrunning on the event loop. Replaced with a single atomicdict.get(tuid)call. -
Python 3.13
asyncio.get_event_loop()error — thebackend_v3test fixture calledasyncio.get_event_loop()in a sync context. Python 3.13 tightened this from aDeprecationWarningto a hardRuntimeError. Fixed by usingasyncio.new_event_loop()instead. -
long_runningtask fixture unresponsive to cancellation — the integration test helper usedtime.sleep(60), which ignores Dragon'skill_by_exceptionmechanism until the sleep finishes (up to 60 seconds). Changed to awhile True: time.sleep(0.1)loop so the Dragon worker is freed within ~100 ms of cancellation.
[0.3.1] - 2026-05-19¶
Fixed¶
- Pinned
dragonhpc==0.13.2in thedragonoptional dependency. Dragon 0.14.0 changed DDict write routing inBatchsuch thatDragonExecutionBackendV3's monitor loop blocks indefinitely on every task result. Users on Dragon 0.14.0 should upgrade to the forthcoming release that includes the full migration fix.
[0.3.0] - 2026-05-15¶
Added¶
-
SpanBuffer— new public, thread-safe span collector that replacesInMemorySpanExporteras RHAPSODY's internal span store. Useslist.extend()for O(1) appends (vs. the exporter's O(n²)tuple +=per flush).shutdown()is a no-op so spans remain accessible aftertracer_provider.shutdown().get_finished_spans(),clear(), andforce_flush()match theInMemorySpanExporterAPI. -
Provider-agnostic OTel injection —
TelemetryManager.__init__()andSession.start_telemetry()accept three new optional parameters: span_processors: list | None— OTelSpanProcessorinstances (e.g.BatchSpanProcessor(OTLPSpanExporter())) added to RHAPSODY's privateTracerProvideralongside the internalSpanBuffer. Callers own exporter construction; RHAPSODY never imports specific exporter classes.metric_readers: list | None— OTelMetricReaderinstances (e.g.PeriodicExportingMetricReader(OTLPMetricExporter())) added to RHAPSODY's privateMeterProvideralongsideInMemoryMetricReader.-
resource: Resource | None— optional OTelResourceoverride.None(default) callsResource.create()which readsOTEL_SERVICE_NAMEandOTEL_RESOURCE_ATTRIBUTESfrom the environment automatically. -
TelemetryManager.annotate_current_span(event)— records aBaseEventas an OTel span event (with serialized attributes) on the currently active span. No-op when no valid span is active or telemetry is stopped. -
TelemetryManager.register_span_enricher(func)— registers a callback invoked atTaskCreatedtime that returns extradictattributes to stamp onto the task's OTel span. Multiple enrichers are applied in registration order. Used by orchestration layers (e.g. AsyncFlow) to inject workflow-level grouping keys. -
TelemetryManager.export_as_otlp(path=None)— serializes all finished spans to a standards-compliant OTLP JSON payload (the POST/v1/traceswire format: 32/16-char hex IDs, nanosecond timestamps as strings, typed KV attributes). Returns the JSON string and optionally writes topath. -
TelemetryManager._task_contexts— internal dict that captures the OTel context (context.get_current()) atTaskCreatedemit time and restores it viaattach/detachin_process_event(). This is the standard in-process OTel propagation pattern across asyncio task boundaries. -
TelemetryManager._session_ctx_token— stores the attach token for the session span context, detached cleanly instop().
Performance¶
- Batch-drain dispatch loop — replaced the per-event
asyncio.wait_for(queue.get(), timeout=0.05)pattern in_dispatch_loopwith a batch-drain approach that reduces asyncio event-loop interactions from O(N) to O(N/500) under burst load.
Key changes:
- Fast path: drain up to 500 events per iteration with queue.get_nowait()
(plain deque.popleft() — zero asyncio scheduling overhead, no timer handle,
no Task allocation per event). Fall back to a blocking await queue.get()
only when the queue is empty.
- asyncio.sleep(0) yielded once per full batch, not once per event.
Partial batches block naturally on the next await queue.get().
- _flush_batch() — new helper that processes OTel instruments, writes the
JSONL checkpoint, and dispatches to subscribers for an entire batch at once.
Subscriber dispatch is guarded by if self._subscribers to skip the inner
loop when no subscribers are registered.
- _write_batch() — new helper that serializes a batch of events and issues a
single file.write() call per batch. Uses
dataclasses.fields() + getattr instead of dataclasses.asdict(): avoids
the deep-recursive copy, and correctly captures init=False class-level
fields (e.g. event_type) that vars() / __dict__ miss on frozen
dataclass subclasses.
- Checkpoint file opened with buffering=131072 (128 KB block buffer) instead
of buffering=1 (line-buffered). The previous setting issued one write()
syscall per event — up to 80 000 syscalls for a 40 K-task session.
- Sentinel-based shutdown — stop() sets _running=False, awaits
queue.join() with a 5 s timeout to guarantee full drain, then pushes
_STOP_SENTINEL to unblock the dispatch loop cleanly. emit() is now a
no-op after stop() to prevent late emissions racing with the sentinel.
Measured at 40 000 tasks (DragonExecutionBackend):
| Telemetry overhead | |
|---|---|
Before (per-event wait_for) |
+7 s (3.66× slower than no-telemetry) |
| After (batch-drain) | +2 s (1.73× slower than no-telemetry) |
71% reduction in telemetry overhead at 40 K tasks.
Fixed¶
-
Task callback contract (
stdout/stderr) —task["stdout"]andtask["stderr"]are now guaranteed to bestr(never absent, neverNone) after any DONE or FAILED callback across all backends.DragonExecutionBackendV3,ConcurrentExecutionBackend, andDaskExecutionBackendeach had paths that left the key missing or set it toNone, causingKeyError: 'stdout'in consumers using bracket notation. A newpytest.mark.result_contractmarker groups seven cross-backend regression tests that enforce this invariant. -
TaskCreatedas task span head — task spans were previously opened atTaskSubmitted, leavingTaskCreated(the earliest lifecycle event) with only atrace_idand nospan_idin the JSONL. The span is now opened atTaskCreatedso all lifecycle events carry bothtrace_idandspan_id, making the JSONL 100% OTel-aligned from the first event. -
Same-batch span ordering hazard — when
TaskCreatedandTaskCompleted/TaskFailedland in the same 500-event batch,_process_eventcloses the span before_span_ids_for_eventcan look it up for intermediate events in the batch. Fixed by: _completed_span_ctxdict: stores theSpanContextsnapshot when a span is ended so intermediate events in the same batch can still retrieve it via.get()(not.pop()).- Terminal events (Completed/Failed/Canceled)
.pop()the entry, ensuring no unbounded growth. -
Same fix applied to the session span:
_completed_session_ctxsnapshot is taken atSessionEndedso JSONL serialization for same-batch session events still finds a valid context. -
ResourceUpdateJSONL correlation —ResourceUpdateevents now carry the session span'strace_idandspan_id(previously(None, None)), making node and GPU metrics queryable within the session trace in Jaeger / Tempo. -
TaskSubmitted/TaskQueuedfallback — ifTaskCreatedwas never seen (incomplete lifecycle, e.g. task registered before telemetry started),TaskSubmittedopens the task span instead, preserving best-effort correlation. -
External trace/span injection — components outside RHAPSODY (e.g. an orchestration layer or application code) can now emit events that carry an explicit
trace_id/span_idand have them written to the JSONL with the correct OTel correlation IDs, enabling cross-component trace stitching. -
Memory leak in
ConcurrentExecutionBackend._run_executable— file handles (stdout_f,stderr_f) opened forcapture_stdio=Truetasks were not closed on exception paths (subprocess launch failure, timeout, etc.). Refactored to initialize both handles andexit_codebefore thetryblock and close them infinally, eliminating the leak. -
OTel span parent hierarchy — task spans previously had no parent span and scattered across multiple unrelated traces. Root cause:
_dispatch_loopruns in a separate asyncioTaskand does not inherit the calling coroutine's OTel context. Fix: capturecontext.get_current()atTaskCreatedemit time, store in_task_contexts, restore viaattach/detachin_process_event(). All task spans now correctly nest under the session root span in the trace hierarchy. -
span_scope()session span fallback — when called from a context with no valid active span (e.g. inside a block body spawned beforestart_telemetry()),span_scope()now explicitly usesself._session_spanas the parent context instead of creating a root span. Replaces custom_null_context()with stdlibnullcontext.
Changed¶
-
TelemetryManager.export_as_otlp()— renamed fromexport_traces_otlp_json()for consistency with the OTel ecosystem naming convention. -
TelemetryManager.start()OTel provider setup — always usesResource.create({"service.name": "rhapsody", "session_id": ...})as the default resource (readsOTEL_SERVICE_NAMEfrom env automatically as fallback). Caller-suppliedspan_processorsare added viatracer_provider.add_span_processor()after the internalSpanBufferprocessor. Caller-suppliedmetric_readersare appended to theMeterProviderreader list alongside the internalInMemoryMetricReader.
Docs¶
docs/telemetry/integrations.md:- Fixed "Connecting an OTLP exporter" section: removed the broken
set_tracer_provider()pattern (RHAPSODY creates private providers and ignores globals) and replaced with the correctspan_processors=injection. Added tip block showing env-var configuration for Honeycomb/Grafana Cloud. - Fixed "Grafana + Prometheus Step 3": removed
set_meter_provider()pattern; replaced withmetric_readers=[PrometheusMetricReader()]. -
Updated "What RHAPSODY produces" table:
InMemorySpanExporter→SpanBuffer. -
docs/telemetry/quickstart.md: added three missing rows to thestart_telemetryparameters table (span_processors,metric_readers,resource). -
docs/telemetry/reference.md: added "Span annotation and enrichment API" section documentingspan_scope(),annotate_current_span(),register_span_enricher(), andexport_as_otlp(). -
docs/telemetry/index.md: updated "OpenTelemetry compatibility" paragraph to accurately describe the private-provider model and direct users to thespan_processors/metric_readersinjection API. -
ComputeTask: newcapture_stdio: bool = Falseparameter. WhenTrue, stdout and stderr from executable tasks are redirected directly to files ({work_dir}/{session_uid}/{task_uid}.stdout/.stderr) with zero in-memory buffering.task.stdoutandtask.stderrthen hold file paths instead of decoded strings. Function tasks are unaffected regardless of the flag value. ConcurrentExecutionBackend: honourscapture_stdioby passing open file handles toasyncio.create_subprocess_exec/asyncio.create_subprocess_shell; the kernel writes directly, no Python-level buffering.DaskExecutionBackend: honourscapture_stdioin the module-level_run_executablefunction; file handles are passed tosubprocess.runinside the worker process.DragonExecutionBackendV3: honourscapture_stdioby wrapping the command inbash -c "cmd 1>out 2>err", bypassing Dragon's internal PIPE infrastructure entirely.BaseBackend: added_work_dir: str(defaults toos.getcwd()) andis_attached: bool = False.Session.add_backend()is now the single authority that sets_work_dir = {session.work_dir}/{session.uid}and flipsis_attached = True.Session.add_backend(): raisesRuntimeErrorif the same backend instance is added to more than one session, preventing silent sharing bugs.- Unit tests for
capture_stdioacrossConcurrentExecutionBackend,DaskExecutionBackend, andDragonExecutionBackendV3. - Getting-started guide: new Capturing stdout/stderr to Files section in
docs/getting-started/advanced-usage.md.
[0.2.0] - 2026-04-04¶
Added¶
- Telemetry Abstraction Layer (TAL): new
rhapsody.telemetrypackage providing event-driven, backend-agnostic observability built on the OpenTelemetry Python SDK.TelemetryManager: central orchestrator owning the asyncio event bus, OTelMeterProvider+TracerProvider(in-memory), JSONL checkpoint writer, and subscriber fan-out.Session.enable_telemetry(resource_poll_interval, checkpoint_interval, checkpoint_path): one-call activation; returns aTelemetryManagerwired into the task state manager and all registered backends.- Event types:
SessionStarted,SessionEnded,TaskSubmitted,TaskQueued,TaskStarted,TaskCompleted,TaskFailed,ResourceUpdate— all frozen dataclasses with consistentevent_id,event_time,emit_time,session_id,backendfields. - OTel trace hierarchy: session span (root) → task spans (children, opened on
TaskStarted, closed onTaskCompleted/TaskFailed) →ResourceUpdateevents anchored to the session span. Every JSONL line carriestrace_idandspan_id. ResourceUpdate.resource_scope: computed discriminator field ("per_node"or"per_gpu") set automatically fromgpu_id. Replaces ad-hocgpu_id is Nonechecks throughout consumers.- Per-GPU telemetry:
ResourceUpdateevents withresource_scope="per_gpu"carry onlygpu_percentandgpu_id;cpu_percent,memory_percent, and all I/O fields areNoneon per-GPU events. Node-level aggregates useresource_scope="per_node". - Backend adapters:
ConcurrentTelemetryAdapter: psutil for CPU/memory/disk/net; pynvml (NVIDIA only) for per-device GPU, initialized once at thread start.ImportErroron missing pynvml is silent; driver failures (e.g., no NVIDIA kernel module loaded) log a one-timeWARNING.DaskTelemetryAdapter: pollsscheduler_info()per worker; emits disk I/O deltas from cumulative Dask counters; net I/O and GPU not exposed by Dask.DragonTelemetryAdapter: reads Dragon'sdpsmetric queue; emits per-device GPU events tagged withdevice_id; supports NVIDIA, AMD, and Intel GPU vendors.
- Adapter registration: failures during
_attach_telemetry_adapternow log atWARNINGwith full traceback instead of silently passing. TelemetryReaderandTelemetrySubscriber: typed pull/push interfaces overTelemetryManager.TelemetryManager.summary(),.task_spans(),.task_count(),.session_duration(): convenience methods returning plain dicts; no OTel knowledge required.- JSONL checkpoint file (
rhapsody.session.<id>.<ts>.telemetry.jsonl): line-buffered, readable during a live run; containsevent,metric, andspansections. - OTel contract test suite:
tests/unit/telemetry/conftest.py(AdapterCapabilities,assert_resource_update_contract) +tests/unit/telemetry/test_otel_contract.py(parametrized across Concurrent, Dask, Dragon). - Full telemetry documentation:
docs/telemetry/(overview, events & metrics reference, quick start, integrations).
DragonExecutionBackendV3: migrated to the Dragon batch.py streaming pipeline. Tasks submitted viasession.submit_tasks()are dispatched individually by a continuously running background thread — there is no compile or start step.DragonExecutionBackendV3: accepts two new constructor parameters:num_nodes(total nodes) andpool_nodes(nodes per worker pool), forwarded directly toBatch().DragonExecutionBackendV3.fence(): new method that delegates tobatch.fence(), allowing callers to wait for all in-flight tasks submitted by this client to complete.DragonExecutionBackendV3.create_ddict(): new helper that creates a DragonDDictinstance directly from the backend.DragonExecutionBackendV3._deliver_batch(): replaces_deliver_result/_deliver_failure. All tasks that complete within a single monitor sweep are collected into a list and delivered to the asyncio event loop in onecall_soon_threadsafecall instead of one per task — reducing cross-thread wakeups from O(tasks) to O(sweeps).DragonExecutionBackendV3result monitoring reads directly fromBatch.results_ddict(the same distributed dict Dragon workers write to) instead of going through theTaskobject. The membership check and value read are now a singletry/except KeyErroroperation, eliminating the redundant__contains__network round-trip (was two DDict RTTs per ready task, now one).DragonExecutionBackendV3: monitor thread now starts lazily on firstsubmit_tasks()call instead of at_async_inittime, eliminating the idle-spin phase while tasks are being built and registered.DragonExecutionBackendV3._cancelled_tasksconverted fromlisttoset: O(1) membership checks and automatic deduplication. Cancelled UIDs are now removed from the set once the monitor loop processes the task, preventing unbounded growth.DragonExecutionBackendV3._task_registryentries are now removed atomically (viadict.pop) on result or failure delivery, eliminating unbounded registry growth for long-running sessions.
Changed¶
ResourceUpdate.cpu_percentandResourceUpdate.memory_percent: type changed fromfloat(default0.0) tofloat | None(defaultNone). These fields areNoneonresource_scope="per_gpu"events and non-null floats onresource_scope="per_node"events. Consumers filtering node-level events should useevent.resource_scope == "per_node"instead ofevent.gpu_id is None.
Fixed¶
ConcurrentTelemetryAdapter: replaced nvidia-smi subprocess (one blocking call per poll, no per-device breakdown) with pynvml initialized once at thread start. Per-device GPU utilization is now collected with device index matching Dragon's pattern.ConcurrentTelemetryAdapter: pynvml driver failure (e.g., driver not loaded, permission denied) now logs a one-timeWARNINGinstead of silently disabling GPU metrics with no indication.ConcurrentExecutionBackend: regular (synchronous) functions are now executed correctly in bothThreadPoolExecutorandProcessPoolExecutor. Previously, all function tasks were dispatched viaasyncio.run(func(...)), which raisedValueErrorfor non-coroutine callables. The executor now detectsasyncio.iscoroutinefunctionand calls sync functions directly.Session/TaskStateManager: task futures now propagate exceptions on failure. Previously all futures were resolved withset_result(task)regardless of outcome. Failures now resolve as:- Function task raises → original exception propagated via
fut.set_exception(exc). - Executable task returns non-zero exit code →
fut.set_exception(TaskExecutionError(uid, stderr, exit_code)). - Successful tasks →
fut.set_result(task)(unchanged).
- Function task raises → original exception propagated via
Session.wait_tasks: replaced bareexcept Exception(which silently swallowed all errors) withasyncio.gather(*futures, return_exceptions=True). Task failures no longer propagate throughwait_tasks; callers inspecttask.state/task.exception/task.stderrdirectly.- API documentation: new Wait Modes reference in
docs/api/index.mdwith a comparison table ofwait_tasks,asyncio.gather(*futures), andawait future / await task, including exception types and when to use each. - API documentation: new Callable Task API section documenting sync and async function support, executor behaviour, and result access fields.
- Getting-started guide: new Wait Modes and Sync and Async Callable Tasks sections added to
docs/getting-started/advanced-usage.mdwith runnable code examples. ConcurrentExecutionBackend: executable tasks now honour per-task working directory viatask.cwd(task-level) ortask_backend_specific_kwargs={"cwd": "..."}(overrides task-level); passed ascwd=toasyncio.create_subprocess_exec/asyncio.create_subprocess_shell.DaskExecutionBackend: executable tasks now honourcwdfromtask_backend_specific_kwargs(overrides task-leveltask.cwd); forwarded to_run_executablewhich passes it ascwd=tosubprocess.run.DragonExecutionBackendV3: documented that per-task working directory must be set viatask_backend_specific_kwargs={"process_template": {"cwd": "..."}}(or"process_templates"for MPI jobs); this is the only supported mechanism in V3.ConcurrentExecutionBackend: executable tasks now honourenvfromtask_backend_specific_kwargs={"env": {...}}; passed asenv=toasyncio.create_subprocess_exec/asyncio.create_subprocess_shell.None(default) inherits the parent process environment.- Unit tests for
cwdandenvbehaviour acrossConcurrentExecutionBackend,DaskExecutionBackend, andDragonExecutionBackendV3. DaskExecutionBackendnow supports all threeComputeTasktypes: sync functions, async functions, and executable tasks (via subprocess inside a Dask worker).- Cluster-agnostic design: pass
cluster=orclient=to target any Dask-compatible cluster (SLURM, Kubernetes, LocalCUDACluster, etc.) without changing task code. - Resource scheduling via
task_backend_specific_kwargs={"resources": {"GPU": 1}}routes tasks to workers advertising matching Dask resources. shell=Truefor executable tasks viatask_backend_specific_kwargs={"shell": True}.DaskExecutionBackend._check_resources_satisfiable(): pre-submit check that immediately fails tasks with unsatisfiable resource constraints instead of hanging indefinitely. Function tasks settask.exception; executable tasks settask.stderrandtask.exit_code = 1.- Integration tests for Dask backend: end-to-end sync/async/executable task execution, cluster injection (cluster and client), and resource constraint failure behavior.
Performance¶
DragonExecutionBackendV3._monitor_loop: eliminated redundantBatch.results_ddict.__contains__check — each ready task previously required two distributed DDict network round-trips (membership test + value read); now a singletry/except KeyErrorread is used, saving ~570µs per task on HPC interconnects (~5.7s for 10K tasks).DragonExecutionBackendV3._monitor_loop: monitor thread now starts lazily at firstsubmit_tasks()call instead of at backend initialisation, eliminating ~1.2s of idle spinning while tasks are being built.DragonExecutionBackendV3._deliver_batch: cross-thread wakeups reduced from O(tasks) to O(sweeps) — all completions found in a single sweep are batched into onecall_soon_threadsafecall (~0.78s saved for 10K tasks).DragonExecutionBackendV3: removed per-tasklogger.debugcalls from the monitor hot path, eliminating 10K f-string allocations per run (29ms at 10K tasks, scales linearly).TaskStateManager: removed_task_statesshadow dict — task state is now read directly fromtask["state"](single source of truth), eliminating one dict write per task completion.TaskStateManager._update_task_impl:_task_futuresentries are now removed viadict.popon resolution, preventing unbounded memory growth at scale.Session: removed history recording (task["history"]timestamps) — twotime.time()syscalls and two dict writes per task eliminated.Session.get_statistics: method removed entirely; it depended on history timestamps and iterated all tasks on every call.
Measured on 2 nodes / 128 workers (HPC), 10K function tasks:
| Run 1 | Run 2 | Run 3 | Run 4 | |
|---|---|---|---|---|
| Dragon batch only | 9.82s | 10.92s | 9.99s | 10.08s |
| RHAPSODY + Dragon batch | 10.50s | 12.17s | 9.92s | 11.18s |
RHAPSODY overhead reduced from ~7.8s (before) to ≤1.3s (after) — within normal run-to-run variance of the Dragon batch itself.
Fixed¶
ConcurrentExecutionBackend._run_in_thread: calling a regular (sync) function no longer raisesValueError: a coroutine was expected.ConcurrentExecutionBackend._run_in_process: same fix — sync functions are called directly after cloudpickle deserialization.TaskStateManager._update_task_impl: futures for failed tasks are now resolved withset_exceptioninstead ofset_result, soawait futureandawait asyncio.gather(*futures)correctly raise on task failure.TaskStateManager.get_wait_future: same fix applied to the race-condition path (task already completed beforeget_wait_futurewas called).Session.wait_tasks: removedexcept Exception: logger.error(...)which was silently eating all non-timeout exceptions including programming errors.
Changed¶
ComputeTask: renamedworking_directoryparameter and dict key tocwdto distinguish task-level working directory from backend-level working directory (used by Dragon V1/V2 viaresources["working_dir"]). Update call sites:ComputeTask(cwd="/path")andtask["cwd"].DragonExecutionBackendV3: removed the silently-ignoredworking_directoryparameter from__init__andcreate()— it was never stored or used (unlike V1/V2 which honourresources["working_dir"]). Usetask_backend_specific_kwargs={"process_template": {"cwd": "..."}}instead.DaskExecutionBackend: resource constraints are now specified exclusively viatask_backend_specific_kwargs={"resources": {...}}(previously viagpu=/cpu_threads=onComputeTask).DaskExecutionBackend._build_dask_resources(): reads fromtask_backend_specific_kwargs["resources"]instead of task-levelgpu/cpu_threadsfields.DaskExecutionBackend._submit_executable():shell=now reads fromtask_backend_specific_kwargsfor consistency.- Optimized Dragon backend tests by using module-scoped fixtures, reusing a single backend instance per Dragon version (V1, V2, V3) across all tests instead of creating/destroying one per test.
Breaking Changes¶
DragonExecutionBackendV3: removednum_workers,disable_background_batching, anddisable_batch_submissionconstructor parameters. These were incompatible with the new streaming pipeline — the Dragon batch always runs in streaming mode and worker counts are controlled vianum_nodes/pool_nodes. Migration:DragonExecutionBackendV3(num_workers=16)→DragonExecutionBackendV3(num_nodes=4, pool_nodes=2)(or simply omit both to let Dragon decide)DragonExecutionBackendV3(disable_batch_submission=True)→ remove (streaming is now always on)DragonExecutionBackendV3(disable_background_batching=True)→ remove
ComputeTaskandAITask: removedranks,memory,gpu,cpu_threads, andenvironmentparameters. These fields were never consumed by any execution backend — they were silently ignored, creating a misleading API. Resource requirements are now backend-specific and must be passed viatask_backend_specific_kwargs. Migration:ComputeTask(executable=..., gpu=2)→ComputeTask(executable=..., task_backend_specific_kwargs={"resources": {"GPU": 2}})(Dask) ortask_backend_specific_kwargs={"process_template": {"gpu": 2}}(Dragon V3)ComputeTask(executable=..., environment={"K": "V"})→ComputeTask(executable=..., task_backend_specific_kwargs={"env": {"K": "V"}})(Concurrent/Dask)ComputeTask: removedcwdandshellas named parameters. All execution context is now exclusively specified viatask_backend_specific_kwargsfor consistency. Migration:ComputeTask(executable=..., cwd="/path")→ComputeTask(executable=..., task_backend_specific_kwargs={"cwd": "/path"})ComputeTask(executable=..., shell=True)→ComputeTask(executable=..., task_backend_specific_kwargs={"shell": True})
Fixed¶
_run_executable: replacedstdout=subprocess.PIPE, stderr=subprocess.PIPEwithcapture_output=True(ruff UP022).
[0.1.2] - 2026-02-16¶
Fixed¶
- Fixed project URLs in
pyproject.tomlto point to the correct GitHub repository. - Removed Python 3.8 classifier (package requires Python >= 3.9).
[0.1.1] - 2026-02-16¶
Fixed¶
- Fixed
ImportErrorwhen installingrhapsody-pywithout optional backends (Dragon, Dask, RADICAL-Pilot). Optional backend imports inbackends/__init__.pyare now wrapped intry/except.
[0.1.0] - 2025-02-16¶
Added¶
- Initial PyPI release as
rhapsody-py(import name:rhapsody). - Execution backends: Concurrent (built-in), Dask, RADICAL-Pilot, Dragon (V1, V2, V3).
- Inference backend: Dragon-VLLM for LLM serving on HPC.
- Task API:
ComputeTaskfor executables/functions,AITaskfor LLM inference. - Session API for task submission, monitoring, and lifecycle management.
- Backend discovery and registry system.
- Removed ThreadPoolExecutor wait approach (
_wait_executor), streamlining concurrency management. - Added
disable_batch_submissionparameter toDragonExecutionBackendV3for configurable task submission strategy. - Introduced polling-based batch monitoring with
_monitor_loopand_process_batch_results.