scientific-workflow 0.13.6

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Runtime API

This guide documents the `scientific-workflow` 0.13.5 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`

- `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:

- `PythonPrerequisite { interpreter: PathBuf, reason: String }`: the active
  interpreter cannot import the coordinated Python 0.4.3 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.