# Runtime API
This guide documents the `scientific-workflow` 0.13.10 subsystem contract.
The `runtime` subsystem is the ultimate coordinator of active execution. It
accepts immutable intent from Study and owns output creation, replicate
admission, dependency scheduling, task concurrency, cooperative timeouts and
cancellation, execution unit or external-program invocation (including Config-lowered
Python environments), automatic persistence lifecycle, and
publication of inferred UI facts.
Runtime does not parse JSON, discover execution units, decode constants for planning,
or let application code construct phases/tasks. It never reparses the central
Config retained by Study.
## Basic API
Ordinary applications call the crate-level `scientific_workflow::run(&Path)`
facade, which loads a Study before handing it to Runtime. This keeps project
discovery and compilation out of the active-execution subsystem.
After successful preflight, Runtime creates a unique execution directory
beneath the inferred `<project-root>/output`, creates one isolated directory
per replicate, executes all phases and tasks, and completes each member's
recording or each program workspace.
Before creating output, Runtime constructs exactly one owned Rayon pool with
the required top-level `study.json.threads` worker count. Every execution-unit
initialization and step runs with that pool installed, so concurrent tasks and
replicates share one study-wide compute limit instead of creating independent
model pools. Ambient `RAYON_NUM_THREADS` does not override the manifest.
The same count also initializes one process-wide permit budget shared by all
replicate schedulers. External tasks reserve their configured thread count; `$npy` reserves
`min(study.threads, deduplicated recording count)`. Tasks
may overlap only while their aggregate reservation fits. External work and
in-process execution-unit work do not overlap: execution units cannot safely
shrink the fixed Rayon pool while it is active. This conservative class boundary
keeps the authored global ceiling exact.
For each task, Runtime derives the destination and constructs private
persistence sessions. A standalone unit opens one member recording; an ensemble
opens one recording per member. ExecutionUnit views submit independent initial/step/final
observations with bounded backpressure. Program tasks receive frozen configuration snapshots, logs, and
an artifacts workspace. Runtime commits terminal status and shuts the session
down; application/execution unit code performs none of this coordination.
For each execution unit task, Runtime also constructs one immutable
`InitializationContext` from Study's optional master seed, replicate ordinal,
task identity, registered execution-unit key, and the completed summaries from
its declared dependency phases. Dependency summaries are filtered to the same
resolved global configuration before initialization. The unit may request
purpose-named shared or member-scoped seeds. Runtime validates member identities
after initialization and passes each member's applicable actual requests into
Persistence before that execution unit's recording begins. A program or Python
task may instead declare one purpose-named task seed in `study.json`. Runtime
derives it from the same master seed, replicate, inferred task identity,
program kind, and purpose; the child receives only that derived value, not an
`InitializationContext` or the master seed.
Runtime owns the presentation observer port and execution, replicate, phase,
task, iteration, target, outcome, and recording-path fact vocabulary.
Crate-level composition attaches UI's automatic adapter after output creation;
Study contains no UI policy. Interactive stdin plus stderr selects the
Ratatui dashboard; otherwise UI emits stable plain lifecycle lines. Typing
`exit` while work is active or pressing Ctrl+C requests cooperative execution
cancellation. After any terminal outcome the dashboard remains visible until the
user explicitly types `exit`; Ctrl+C alone never closes it. Consequently an
interactive `execute` call returns only after execution has ended and that final
`exit` is submitted. Noninteractive execution never waits for input. UI is the
sole presentation boundary: renderer startup, terminal
initialization/input/drawing, and plain-output failures return
`RuntimeError::Presentation` rather than becoming cancellation or silent
fallback.
The default `terminal-ui` Cargo feature preserves this complete presentation
path. When an embedding explicitly disables default features, the UI module and
terminal dependencies are absent and composition attaches a silent observer to
Runtime's unchanged port. Execution and summaries behave normally, but there
is no presentation output or UI-originated cancellation in that build.
An execution blocks until all admitted work has stopped and all successful
persistence sessions have durably completed. ExecutionUnit cancellation is cooperative
between steps, so blocking application code inside one step may delay return.
External programs, including Python interpreters/environment managers, are
polled and own Linux process groups which are terminated, killed after bounded escalation,
and reaped when cancellation or timeout is observed. Pipe readers are joined
before resource permits are released. Future macOS/Windows implementations require
separate qualification; Linux is the only supported platform.
Failure does not overwrite prior output. Execution that fails after output creation
retains its unique directory and any failed/running recording evidence for
diagnosis. The crate-level facade wraps an active `RuntimeError` in
`WorkflowError::Runtime`; the complete-workflow composition is documented by
`WorkflowError`.
## Advanced API
### `runtime::execute`
`execute(study: Study) -> Result<RunSummary, RuntimeError>` consumes one
clone-cheap immutable Study. It is Runtime's sole execution entry and cannot
accept a project root, manifest, execution unit catalog, or unresolved declarations.
It is the supported embedding seam for callers that loaded and optionally
inspected a Study first.
It performs the same output-producing work reached through the crate facade.
It never mutates the supplied
declaration; consuming the handle simply makes accidental double execution
less likely at the call site. A caller may explicitly clone Study before the
call when multiple independent runs are intended.
Replicates run sequentially or concurrently according to `ReplicatePolicy`.
Every replicate gets `replicate-XXXXXX` beneath the unique execution scope.
Parallel fail-fast observes replicate completion as it occurs: the first
reported failure requests cancellation of still-running sibling replicates,
and Runtime waits for their cleanup before returning that originating error.
Parallel finish-all never performs this policy cancellation and collects every
terminal outcome before returning the first observed failure. Successful
summary order remains independent of worker completion order.
Phases run in stable topological order. Within a phase, runtime respects
`max_concurrency`, the minimum `start_interval` between successive admissions,
the global resource budget, task timeout, phase timeout, and sibling failure
policy. A resource-blocked task remains pending and is not reported as started.
The first eligible
task has no artificial pre-admission wait. Fail-fast stops further admission
and requests cancellation of active siblings; finish-all continues admitting
declared siblings and returns an error after they finish.
Task/phase deadlines and admission delays use one Runtime-owned pause-aware
clock. It freezes immediately on pause request, including while an in-flight
call or arbitrary program is still running. Resume never charges that paused time.
Task deadline classification uses the worker's completion timestamp, rather
than the later instant at which the polling scheduler joins it. A task that
completed before its deadline is therefore not retroactively timed out. Phase
deadlines likewise apply only while pending or unfinished work remains.
An interactive `exit` submitted during execution stops further admission,
cancels active execution unit/program workers, waits for their cleanup, restores the
terminal, and returns `RuntimeError::ExecutionCancelled`. Ctrl+C performs the
cancellation but leaves the completed dashboard open until the required `exit`
command. If execution has already reached a successful or failed terminal outcome,
`exit` only closes the interface and does not change that outcome.
### `runtime::RunSummary`
Returned only after complete success. It is cloneable and owns paths/summaries.
- `output_directory() -> &Path` returns the unique generated execution path.
- `replicates() -> &[ReplicateRunSummary]` returns ascending replicate order.
The summary performs no IO and does not keep recording files open.
### `runtime::ReplicateRunSummary`
- `index() -> u64`: zero-based replicate index;
- `output_directory() -> &Path`: isolated replicate directory; and
- `phases() -> &[PhaseRunSummary]`: successful phases in dependency execution
order.
Parallel worker completion order is never exposed; summaries are sorted by
index.
### `runtime::PhaseRunSummary`
- `was_reused() -> bool`: true when this phase imported completed outputs without executing its tasks.
- `name() -> &str`: stable manifest phase key;
- `tasks() -> &[TaskRunSummary]`: successful tasks restored to deterministic
Study plan order, independent of concurrent completion order.
### `runtime::TaskRunKind`
`TaskRunKind` is a non-exhaustive data-bearing enum. `ExecutionUnit` contains
the registration key and stable `Box<[MemberRunSummary]>`; `Program` contains
the resolved launcher executable and optional canonical Python script; and
`Npy` contains the Python launcher used by Workflow's reserved converter and
the standard execution-level processed-data directory.
Callers matching it must retain a fallback for future workload kinds.
### `runtime::TaskRunSummary`
- `identity() -> &str`: Study-inferred task identity;
- `kind() -> &TaskRunKind`: borrows the variant-specific result; and
- `output_directory() -> &Path`: task output root or program workspace. For a
single-member unit this is also the recording directory; every recording
path is available from the execution-unit variant's `members`.
Summary paths are owned. The enum prevents irrelevant or contradictory fields.
A task-level final iteration is intentionally absent because members can finish
at different iterations; callers can compute a maximum when meaningful.
Summary values do not authorize append/resume and carry no live task, process,
execution unit, or state.
Summaries and `RuntimeError` are `Send + Sync`.
### `runtime::MemberRunSummary`
One immutable per-member result owned by its task summary:
- `identity() -> &str` returns the stable identity supplied through
`MemberView`;
- `final_iteration() -> u64` returns that member's terminal iteration; and
- `output_directory() -> &Path` returns that member's completed recording.
For a multi-member unit, directories are
`<task-output>/members/member-<index>` in stable member order. The identity is
metadata, not a filesystem fragment, so application identities cannot redirect
persistence. Summary borrows are tied to the owning summary and perform no IO.
### External program and Python contract
Runtime starts a resolved executable directly, without a shell, inside its
private `artifacts/` directory. Standard input is closed. Standard output and
error are captured as `stdout.log` and `stderr.log`. Runtime supplies absolute
paths through:
- `WORKFLOW_CONFIG_PATH`: immutable `workflow-config.json`, containing the
captured `study` value and all `wf_configs/` JSON documents, with global
parameter selections resolved for this task;
- `WORKFLOW_DEPENDENCIES_PATH`: immutable `workflow-dependencies.json`, with
completed task summaries from declared dependency phases, filtered to this
task's resolved global configuration;
- `WORKFLOW_PROJECT_ROOT`: canonical project root;
- `WORKFLOW_EXECUTION_ROOT`: unique execution directory;
- `WORKFLOW_REPLICATE_ROOT`: current replicate directory; and
- `WORKFLOW_TASK_OUTPUT`: the task's `artifacts/` directory, also its working
directory;
- `WORKFLOW_NPY_OUTPUT`: present only for `$npy` and naming the standard
`<execution>/processed/replicate-NNNNNN` destination;
- `WORKFLOW_THREADS`: decimal positive thread count reserved for this external
task (one when `resources` is omitted);
- `RAYON_NUM_THREADS`: the same task reservation for Rayon-based child
programs; and
- `WORKFLOW_TASK_SEED`: decimal unsigned 64-bit task seed, present only when
the program/Python task declared `seed: {"purpose":"..."}`.
Programs may read any central configuration keys they understand. The supplied
workspace is their default location for temporary or task-scoped artifacts,
but an external program owns its domain-specific IO and may resolve a
project-relative destination from `wf_configs/parameters.json`. For example, the bundled
Python plotter writes directly to the configured `output/plots`. Rust
Persistence does not relocate or publish those Python-owned files. A Study uses
its captured snapshot: editing JSON after `Study::load` cannot alter these
files.
On completion Runtime writes terminal `program.json`; nonzero exit status is a
task failure. A seeded program's metadata records its purpose and actual
derived seed even when the child fails. Dependency JSON is deterministic. Each task contains `identity`,
`output_directory`, and one `workload` object. An execution-unit workload
contains its kind, registration key, and member identity/iteration/recording
summaries. A program workload contains `kind` (`program` or `python`), its
launcher executable, and the optional canonical Python script. Dependency JSON
remains a data handoff, not a shell command protocol.
A reserved `$npy` task receives the complete transitive prerequisite phase
graph across all inferred global configurations in its replicate. It converts
every field in every unique execution-unit member recording to manifest-directed,
C-contiguous `.npy` data at `<execution>/processed/replicate-NNNNNN` and writes
a batch manifest there. Numeric fields map directly or use ragged components;
structured fields retain lossless JSON-byte fallback data and nested numeric
projections. No representation uses object dtype or pickle.
Its dependency workload kind is `npy` and includes `processed_directory`, so a
downstream task never reconstructs the path. Ordinary dependency snapshots
remain direct and configuration-correlated; the aggregate `$npy` summary is
visible to every downstream configuration.
A nested Python task follows this exact runtime contract after Config lowers
its environment to one invocation. Runtime has no Python-specific scheduler,
active-environment lookup, package installer, or import-path mutation. The
script reads the same `WORKFLOW_*` files/paths as any program. It may use
`WORKFLOW_TASK_OUTPUT` or a validated destination from its project parameters.
Its `.py` file need not be executable. The selected
manager/interpreter, manager arguments, canonical script, and script arguments
are fixed before output creation.
### `runtime::RuntimeError`
This non-exhaustive enum reports failures after a valid Study is available:
- `Reuse { phase: String, path: PathBuf, reason: String }`: required completed outputs are missing, failed, or incompatible; detected before output creation.
- `PythonPrerequisite { interpreter: PathBuf, reason: String }`: the active
interpreter cannot import the coordinated Python 0.4.5 tools, NumPy and
threadpoolctl, or is older than Python 3.14. The error names the selected
interpreter and setup remedy. Runtime probes before scientific work and output
creation; Study::load performs no subprocess probe.
- `ComputePool { threads, source }`: Runtime could not create the exact
study-wide pool before output creation;
- `ExecutionCancelled`: the interactive `exit` command or Ctrl+C requested
cooperative cancellation;
- `Presentation { source }`: the selected automatic presentation adapter could
not start, publish plain/dashboard output, poll input, draw, or finish; it is
never a cancellation result;
- `OutputScope { path, source }`: unique execution or replicate directory could
not be created;
- `Task { task, source }`: execution unit, program, state, observation, config decode,
or persistence operation failed during invocation;
- `TaskPanicked { task }`: task execution unwound; Runtime marks any active
member recording failed with a bounded diagnostic before returning the stable
existing error shape;
- `TaskTimedOut { task, timeout }`: an execution unit observed its cooperative deadline
or an external process was terminated after its deadline;
- `TaskCancelled { task }`: runtime cancelled an active sibling;
- `PhaseTimedOut { phase, timeout }`: phase exceeded its deadline; active
execution units stop cooperatively and active external programs are terminated;
- `StartWorker { scope, source }`: OS thread creation failed;
- `ReplicatePanicked { index }`: parallel replicate worker unwound; and
- `Replicate { index, source }`: contextual wrapper for a failed replicate.
Sources retain their original error chains. A runtime error never represents a
manifest grammar or execution unit-key preflight failure; those remain `StudyError`.
## Example
The complete ordinary workflow uses the crate facade rather than the embedding
Runtime API:
```rust,no_run
use std::path::Path;
fn main() -> Result<(), scientific_workflow::WorkflowError> {
scientific_workflow::run(Path::new("."))
}
```
An embedding integration can retain completion paths:
```rust,no_run
use std::path::Path;
use scientific_workflow::runtime::{execute, TaskRunKind};
use scientific_workflow::study::Study;
# fn run() -> Result<(), Box<dyn std::error::Error>> {
let study = Study::load(Path::new("."))?;
let summary = execute(study)?;
for replicate in summary.replicates() {
println!("replicate {}: {}", replicate.index(), replicate.output_directory().display());
for phase in replicate.phases() {
for task in phase.tasks() {
match task.kind() {
TaskRunKind::ExecutionUnit { execution_unit, members } => {
println!("unit {execution_unit}");
for member in members {
println!(" member {} at {}", member.identity(), member.final_iteration());
}
}
TaskRunKind::Program { executable, .. } => {
println!("program {}", executable.display())
}
_ => println!("another task kind"),
}
}
}
}
# Ok(())
# }
```
## Not API
Scheduler polling, worker thread names, active task handles, atomic cancellation
flags, completion channels/timestamps, bounded panic-payload formatting,
task output ordinals, `RuntimeTaskHost`,
execution unit/program task environments, child-process polling, `PersistenceSession`,
Runtime-owned observer/event/task-presentation contracts, UI session, backend ownership, and
topological-position calculation are private.
Runtime passes `MemberRecordingProvenance` as semantic facts—task identity,
registered unit key, selected state, local parameter ordinal/source, resolved
constants, and the task's resolved project parameters—to
Persistence. Runtime does not construct durable JSON namespaces and does not
name the local backend or its format fields. Persistence authors recording
metadata, which keeps complete resolved constants under `constants`
and Workflow identity/source facts under a separate `workflow` object. The
workflow object names the selected registration, `parameter_ordinal`, canonical
`parameter_source`, resolved `parameters`, and the explicitly selected `state` key; the effective
object also records `member_index` and `member_identity` for every execution unit;
backend and byte settings are recorded under
`workflow.persistence`. The user-authored `chunk_target_mb` and
`queue_capacity_mb` have already been converted, so provenance deliberately
records the exact effective values as `chunk_target_bytes` and
`queue_capacity_bytes`. These namespaces never overwrite one another even
when scientific constants use the same field names.
The private output-directory allocator and local persistence adapter are
implementation details. A future backend may change internal construction
and wire mechanics while preserving the documented inferred root, isolation,
summaries, failure atomicity, effective-plan provenance, and observation
lifecycle.
An active task retains Config's clone-cheap immutable byte snapshot, not the
Config lookup/parser object. Program launch receives those bytes and dependency
facts through Persistence. Runtime obtains task execution/provenance/summary
facts through Study's peer view rather than opening Task descriptors.
The program execution port likewise supplies Task's semantic
`ProgramTaskInvocation`; Runtime does not import Config's resolved-program
representation.
Paths written to program dependency snapshots are exact UTF-8 values validated
during Config preflight; Runtime performs no lossy path rendering.
## Pause, program events, and process ownership
`pause` stops admission and freezes the execution clock immediately. Execution
units park at initialize/step boundaries; accepted persistence records drain.
The standard converter receives a private atomic control-file channel, checks
pause/cancel at bounded record/hash/job boundaries, and acknowledges only after
all active workers are parked or finished. Arbitrary external programs finish
normally while admission waits. UI distinguishes pausing from fully paused by
Runtime-owned activity/acknowledgement counts. `resume` wakes waiting units.
Cancellation wakes paused work; presentation failures also cancel and join task
workers, including early-return paths. Start publication uses a handshake before
worker progress can occur. No new public control handles or ExecutionUnit methods
are required.
`exit --force` restores the terminal, kills every registered owned child process
group, reaps direct children, then exits 130. The launch/force-exit registry is
locked across creation/exit to prevent late unowned children. Forced exit can
leave incomplete scientific recordings; it does not claim successful durability.
Programs must not deliberately escape their owned process group.
Stdout/stderr are concurrently drained while preserving all bytes in required
logs. Pipe-read/log-write/flush failures fail the task and trigger cleanup while
remaining pipe bytes are drained. Prefixed stderr JSON frames follow
`protocol/program-events-v1.md`: log severity and stage/count progress. Unsupported,
malformed, oversized or partial frames remain in stderr.log and produce at most
three warnings per task. They do not fail otherwise successful scientific work.
Frame memory is bounded to 16 KiB. UI text strips terminal controls and bounds
message length. Progress updates coalesce at 50ms and final progress is flushed;
complete raw logs remain available. Failed-process errors identify their log scope.
Standard converter workers use spawn, never fork inherited Rust state. Runtime
reserves the pool allowance in the shared ResourceBudget; concurrent replicates
cannot each independently consume the study ceiling. NumPy native pools are
limited to one thread per worker. No separate user worker-count setting is added.
### Explicit phase selection
Every `study.json` must contain `"active_phases": [0, 1, ...]`; there is no
implicit run-all default. Indices are zero-based in deterministic dependency
order: visit phases in JSON declaration order, recursively visit each `after`
list in its declared order, then assign each phase its index once. Selecting a
subset never renumbers phases, expanded tasks, output ordinals, or seed identities.
The order of indices in the selection does not change execution order. Duplicate,
negative, non-integer, and out-of-range indices are rejected. An empty list
explicitly selects no work.
For a six-phase preparation, reference, targets, lattice, export, and conversion
study, `"active_phases": [3, 4, 5]` starts at lattice. Supply
`"reuse_from": "output/execution-1234-0"` to reuse completed prerequisites.
The path names one execution directory and is resolved against the project root;
absolute paths are also accepted. Each replicate imports the matching source
replicate. Unselected phases that are not prerequisites are omitted entirely.
Workflow validates the complete graph and constants during Study loading.
Before creating new output, Runtime requires every imported task to have
successfully completed with matching captured inputs. `active_phases` and
`reuse_from` may differ between the captured and current study snapshots.
`$npy.exclude_streams` may also differ when the imported phase is neither
`$npy` nor a direct or transitive consumer of its output. NPY and its consumers
retain exact filter matching; all other captured inputs still must match.
A reused phase cannot depend on a phase selected to execute again. Missing,
failed, incompatible, or ambiguous legacy inputs fail without launching work.
Programs and `$npy` receive the original completed recording/artifact paths.
Recordings are never appended to or rewritten.
New executions commit private `workflow-result.json` receipts after each
successful phase, including references for reused tasks, so reuse can be chained.
Pre-0.13.9 program outputs may be imported from their successful `program.json`
and captured config. Legacy execution-unit imports additionally require an
authoritative matching summary in a dependent program's captured dependency
file; Workflow never guesses a final iteration from sampling cadence.
## Ensemble progress and filtered conversion
Runtime reports the maximum current member iteration and maximum declared target,
not summed member-work. If any target is unknown, the task target stays unknown.
For a lockstep ensemble, twelve members at 100 of 36000 steps report 100/36000.
Early-completed members do not hold back the clock. Completion events already
use the maximum final member iteration. ETA uses this same task clock; member
recordings and completion policies are unchanged.
The reserved `$npy` phase passes exact stream exclusions as repeated
`--exclude-stream=NAME` arguments to Python 0.4.5. Filtering affects conversion
only. All included data retains ordinary validation, locking, cancellation,
worker limits, and atomic publication. Filter identity is checked before reusing
member outputs or an existing batch; different filters never silently reuse data.