# Scientific Workflow Rust crate
> **BREAKING UPDATE: Rust 0.15.0 / Python 0.5.0.**
> This supersedes the Rust 0.14.x / Python 0.4.x runtime-policy generation.
> Output disk usage now pauses work at 95% by default; configure
> `disk.pause_at_percent` or explicitly use `null` to bypass it. Execution names
> use UTC timestamps, operational settings no longer invalidate completed work,
> and finalized JSON cannot be rewritten through Workflow's writers.
> `--clean` clears the complete output directory after guarded preflight.
> Execution requires the dashboard: use `screen` or `tmux`. Disk recovery requires
> typing `resume`; NPY defaults to gradual `auto` worker admission.
> `$npy` requires companion 0.5.0 for fixed/auto worker admission.
> No aliases restore the old execution names or JSON rewrite behavior.
> Scientific APIs and recording formats 7/8 remain compatible.
Rust 0.13.11 and Python 0.4.5 correct ensemble progress to the maximum member
iteration/target and support `"$npy":{"after":["evolve"],"exclude_streams":["checkpoint"]}`.
The UI preserves complete numeric counters at narrow widths. Stream exclusions
affect conversion only; raw recordings and scientific stepping are unchanged.
Scientific Workflow is an inference-first library for typed scientific state,
configuration-driven execution unit or program execution, and durable outputs.
Existing 0.13.x projects should follow the
[0.14.0 compute migration guide](../docs/migration-0.14.0.md) before updating.
## New to Workflow?
Start with the [beginner getting-started guide](https://github.com/dingyisun0101/Scientific-Workflow/blob/v0.15.0/rust/getting-started.md). It
explains Serde and deserialization, Rust traits, and the difference between a
study, phase, task, execution unit, member, and state before presenting a
minimal runnable project.
The shortest mental model is:
```text
Study -> Phase -> Task -> ExecutionUnit -> Member -> SystemState -> recording
```
Ordinary users author `wf_configs/study.json` and call `run`. They do not build
the Rust `Study`, task graph, Runtime, persistence sessions, or UI themselves.
Most scientific models expose exactly one member; ensembles use the same
execution-unit contract but expose several independently recorded members.
For disk protection, thread budgets, scheduling, timeouts, buffering, and Python
launchers, see the [`study.json` system settings](#studyjson-system-settings).
## Workflow at a glance
### Architecture and ownership
```text
Runtime (owns one study-wide compute pool, execution, scheduling, and cancellation)
+-- consumes: immutable Study
| +-- retains: Config
| |
| `-- owns: replicate policy + dependency-ordered phase graph
| `-- phases own assembled tasks
| +-- scientific task
| | +-- retains: resolved parameters
| | +-- retains: selected project schema OR validated standard provider
| | +-- retains: bound observation plan
| | `-- creates: ExecutionUnit with immutable InitializationContext
| | +-- standalone unit
| | | `-- member -> SystemState
| | `-- ensemble
| | +-- member -> SystemState
| | `-- member -> SystemState
| |
| `-- program/Python task
| `-- retains: resolved executable, arguments, and environment
|
+-- creates and coordinates: Persistence sessions
| +-- one recording per exposed member
| | +-- borrows that member's SystemState at automatic boundaries
| | +-- records applicable requested seed derivations
| | `-- owns bounded stream writers
| | `-- commit metadata + immutable chunks
| |
| `-- program workspace
| `-- owns config snapshot + logs + status + artifacts directory
|
`-- publishes lifecycle/progress facts to: automatic terminal UI
```
Runtime consumes a completed Study but does not reinterpret it. Study retains
Config and the assembled phase/task graph. Each scientific task retains its own
selected, validated schema; every live member directly owns its `SystemState`.
Persistence—not the execution unit—owns recording lifecycle, writer threads, durable
chunks, program workspaces, metadata representation, and reconstruction rules.
Runtime passes semantic task provenance rather than authoring storage JSON, and
active program tasks retain only Config's frozen byte snapshot. External
programs write their own domain artifacts, while UI only receives Runtime-owned
lifecycle and progress facts.
### General project procedure
```text
[1. Implement/register execution units and prepare program or Python tasks]
|
v
[2. Author wf_configs/study.json and wf_configs/parameters.json]
- add named project state schemas when not using a linked provider
- add one top-level seed when stochastic units request derived seeds
|
v
[3. Call scientific_workflow::run(project_root)]
|
v
[4. Config reads and strictly parses all project JSON once]
|
v
[5. Study performs effect-free assembly and preflight]
- validate every named project schema or linked standard provider
- resolve execution unit keys, programs, and Python environments
- expand/decode parameters and bind observation plans
|
v
[6. Runtime creates execution/replicate output scopes]
|
v
[7. Dependency-ordered phases admit eligible tasks]
| |
v v
[Scientific task] [Program/Python task]
initialize unit with context launch resolved invocation
observe each initial state capture config/dependencies
coordinated step + observe capture logs/status/workspace
finalize each member |
| |
v |
[Persistence writers commit] |
[verified metadata + chunks] |
| |
+---------------+---------------+
|
v
[8. Return deterministic summaries and completed output]
```
Configuration or preflight failures stop before output exists. Once execution
starts, Runtime owns scheduling, cancellation, and task coordination;
successful member recordings are published only after Persistence finalizes
their metadata and writers.
## Installation
### Use the published crate
For application development, prefer the published release:
```toml
[dependencies]
scientific-workflow = "0.15.0"
serde = { version = "1", features = ["derive"] }
```
Or add the same dependencies from the command line:
```bash
cargo add scientific-workflow@0.15.0
cargo add serde --features derive
```
Rust 1.97 or newer is required. Application executables should commit
`Cargo.lock`; libraries should normally leave final version selection to their
downstream application. The execution-unit attribute is re-exported by
`scientific-workflow`; no separate procedural-macro dependency is needed.
Projects declaring the reserved `$npy` phase also install the coordinated
optional converter:
```bash
python3.14 -m venv .venv
source .venv/bin/activate
python -m pip install \
"scientific-workflow[npy] @ git+https://github.com/dingyisun0101/Scientific-Workflow.git@v0.15.0#subdirectory=python"
```
Execution requires terminal standard input and standard error for the dashboard.
For long or remote runs, start `tmux new -s workflow` or `screen -S workflow`,
then activate the Python environment and run your application inside it.
Noninteractive or redirected execution is rejected before output creation or
`--clean` deletion. The `terminal-ui` feature and silent execution mode have been
removed; disabling default features does not remove the dashboard. Configuration
loading and recording-reader APIs can still be used without launching a run.
Serde is Rust's standard data-conversion framework. Workflow uses its
`Deserialize` trait to turn expanded JSON from `wf_configs/parameters.json`
into an execution unit's typed `Constants` value. Application code normally
adds `#[derive(Deserialize)]`; the [getting-started guide](https://github.com/dingyisun0101/Scientific-Workflow/blob/v0.15.0/rust/getting-started.md#why-serde-and-deserialize-appear)
shows the exact JSON-to-Rust mapping and explains why
`#[serde(deny_unknown_fields)]` is recommended.
The published crate is the right choice when the supported workflow matches
the project:
- Rust workloads can implement `ExecutionUnit`, expose one or more members that
each own `SystemState`, and use JSON-deserializable constants;
- work can be expressed as dependency-ordered execution unit, executable, or Python
tasks in `wf_configs/study.json`;
- named JSON state schemas and the central `wf_configs/parameters.json` are suitable
configuration boundaries, or an upstream crate can provide a standard
embedded schema to a receiving unit;
- automatic local recordings, program workspaces, and terminal UI are desired;
and
- completed recordings can be analyzed through `StoredStateSeriesReader` and
field decoders.
In that case, cloning the repository adds no capability. Depend on the release
and use only the public API below.
### Clone a local copy
Clone the complete repository when evaluating unreleased work, running the
bundled example and full Rust/Python validation suites, contributing upstream,
or temporarily consuming a local revision before it is published:
```bash
git clone https://github.com/dingyisun0101/Scientific-Workflow.git
```
Point an application at the cloned crate directory:
```toml
[dependencies]
scientific-workflow = { path = "../Scientific-Workflow/rust" }
serde = { version = "1", features = ["derive"] }
```
Adjust the relative path to match the checkout location. Clone the whole
repository rather than copying `rust/` alone because the crate uses the sibling
procedural-macro package and the repository also contains its Python companion,
example, architecture, and conformance tests. A path dependency follows local
edits immediately; commit the repository revision separately because
`Cargo.lock` cannot reproduce uncommitted path contents.
### Fork instead of only cloning
Create a fork when the required behavior deliberately exceeds the supported
replacement boundaries or must be maintained independently. Typical reasons
include:
- exposing a different public orchestration or execution unit contract;
- implementing a custom persistence backend, writer lifecycle, or incompatible
recording format (the current cross-language contract is the repository's
[recording v7 protocol](https://github.com/dingyisun0101/Scientific-Workflow/blob/v0.15.0/protocol/recording-v7.md));
- replacing scheduling, cancellation, output-layout, or UI policy;
- carrying organization-specific changes that cannot be contributed upstream;
or
- preparing a pull request through a personal remote.
Do not fork merely to define new execution units, payload types, observation plans,
field decoders, executable tasks, Python tasks, or project configuration; those
are supported extension points. Before changing internals, read the subsystem
`api.md` replacement contract and pin dependent applications to a known fork
commit. This crate is pre-1.0, so review breaking notes before upgrading either
the release or a fork.
## `study.json` system settings
This reference covers the operational settings in `wf_configs/study.json` for
Rust 0.15.0 / Python 0.5.0. Settings are captured when the study loads; editing
the file does not reconfigure an active run. Unknown fields are rejected.
Defaults below apply when a field is omitted, including when its optional
parent object is omitted. Required fields have no inferred default.
### Global resources and disk protection
| `threads` | Required positive integer | Shared compute-thread budget across tasks, phases, and replicates. No CPU-count inference or `RAYON_NUM_THREADS` override. |
| `compute.mode` | Required: `"auto"` or `"isolated"` | `auto` shares the available budget as equally as possible among working execution-unit tasks and can resize their private pools between host calls. `isolated` gives each unit its declared fixed allocation. |
| `disk.pause_at_percent` | `95`; finite number greater than `0` and at most `100`, or `null` | Pause work when used space on the execution output filesystem reaches this percentage. `null` explicitly disables the guard. |
| `persistence.chunk_target_mb` | `64`; positive integer | Approximate recording chunk size target in decimal MB. |
| `persistence.queue_capacity_mb` | `64`; positive integer | Per-stream capacity for queued encoded recording data; applies backpressure when full. Decimal MB. |
Persistence settings apply to member-state recording streams. One MB is
1,000,000 bytes; sizes that overflow the internal byte representation are
rejected. These buffers do not impose a total process RAM
limit. The thread budget counts allocated compute threads, not every OS thread;
programs receive thread-count environment variables and must honor their
allocation. Execution units in `auto` must declare
`THREAD_COUNT_INVARIANT = true`; they cannot declare task `resources`.
The disk guard checks before work admission and every 250 ms of wall time,
including while paused. At `max(0, pause_at_percent - 2)` percent used space
(93% with the default threshold), the dashboard reminds you to type `resume`
and Enter. Space recovery alone never resumes work; an early command is rejected.
Polling interval and recovery margin are fixed behavior, not JSON settings.
In-flight work may take time to pause. See
[disk guard behavior](#disk-guard-and-npy-resource-policy) for process handling
and monitor failures. To bypass it, use `"disk":{"pause_at_percent":null}`;
omitting `disk` or using `"disk":{}` keeps the 95% default.
### Replicate, phase, and task scheduling
In this table, `<phase>` is a key in `phases`, and `tasks[]` means each authored
task object in that phase.
| `replicates.scheduling` | `"sequential"`; also `"parallel"` | Run replicates in sequence or allow them to overlap within the shared resource budget. |
| `replicates.failure_policy` | `"fail_fast"`; also `"finish_all"` | Stop sibling replicate work after failure, or allow the remaining replicates to finish. Failures still make the run unsuccessful. |
| `phases.<phase>.max_concurrency` | `1`; positive integer | Maximum concurrently admitted tasks in this phase, still subject to the global thread budget. |
| `phases.<phase>.start_interval_ms` | `0`; nonnegative integer | Minimum delay between successive task admissions. The first eligible task starts immediately. |
| `phases.<phase>.timeout_ms` | No limit; `null` or nonnegative integer | Phase timeout in milliseconds. `0` is an immediate deadline, not a disabled timeout. |
| `phases.<phase>.failure_policy` | `"fail_fast"`; also `"finish_all"` | Stop sibling task work after failure, or allow the remaining tasks in this phase to finish. The phase still fails if a task fails. |
| `phases.<phase>.tasks[].timeout_ms` | No limit; `null` or nonnegative integer | Task timeout in milliseconds, independently of the phase timeout. `0` is an immediate deadline. |
| `phases.<phase>.tasks[].resources.threads` | Program/Python: `1`; execution unit: required in `isolated`, forbidden in `auto` | Positive integer no greater than global `threads`. Reserves a fixed allocation for the task lifetime; execution units use a private pool of that size. |
Admission delays and timeouts use the pause-aware active clock. Execution-unit
timeouts are cooperative at host-call boundaries; they cannot interrupt an
arbitrarily long unit call. Program timeout handling terminates and reaps the
child. Neither `finish_all` policy bypasses dependency requirements,
cancellation, or timeouts.
### NumPy conversion workers
These settings apply only to the reserved `$npy` phase. Ordinary phases reject
`threads` and `mode`; their concurrency control is `max_concurrency` above.
| `phases.$npy.threads` | Global `threads`; `null` or positive integer no greater than that budget | Caps single-thread conversion workers; `null` uses the global budget. Runtime reserves the smaller of this limit and the number of distinct input recordings. |
| `phases.$npy.mode` | `"auto"`; also `"fixed"` | `fixed` admits workers up to the allowance immediately. `auto` starts at one and raises the admission limit by one every 250 ms of active time up to the same allowance. |
Leave `$npy.mode` and `$npy.threads` unset for the automatic defaults. Set a
lower thread limit only when reserving resources for other tasks requires it.
The full allowance remains reserved during the automatic ramp. Auto mode uses
worker counts, with no CPU or RAM utilization target. `$npy` creates one
aggregate task per replicate, so phase `max_concurrency` does not set its worker
count. Phase scheduling, timeout, and failure settings still apply. Each worker
limits native numerical pools to one thread. Workflow resolves `python3` for
the standard converter; `$npy` has no authored `python.environment` override.
### Schema and run selection
| `workflow_schema` | Required: `1` | Selects the supported manifest grammar. |
| `active_phases` | All phases; `null` or array of unique valid zero-based indices | Selects phases in the deterministic dependency order; `null` selects all. An empty array selects no work; array order does not change execution order. |
| `reuse_from` | None; `null` or an execution-directory path | Supplies completed prerequisites for selected phases. Accepts an absolute path or a path relative to the project root. |
| `phases.<phase>.tasks[].active` | `true`; boolean or `null` | Execution-unit tasks only: `false` keeps the planned identity but suppresses execution and reuse; `null` uses the default. A boolean `active` is rejected on program and Python tasks. |
Selection keeps phase indices, task identities, output ordinals, and seed
identities stable. Imported prerequisites must have completed successfully with
matching scientific inputs before new output is created. See
[phase and execution-unit selection](#optional-phase-and-execution-unit-selection)
for index ordering and reuse restrictions.
### Python task environments
Every authored Python task requires
`phases.<phase>.tasks[].python.environment`. Its `manager` has no default.
Only the fields listed for the chosen manager are accepted.
| `"system"` | Optional `executable` | Uses the explicit interpreter path/command, or resolves `python3`. |
| `"venv"` | Required `path` | Uses the interpreter in that virtual-environment directory (`bin/python` on Linux). |
| `"mamba"` | Required `name`; optional `executable` | Uses the explicit manager or `mamba`, then `run -n <name> python`. |
| `"conda"` | Required `name`; optional `executable` | Uses the explicit manager or `conda`, then `run -n <name> python`. |
| `"uv"` | Required `project`; optional `executable` | Uses the explicit manager or `uv`, then `run --project <project> python`. |
| `"poetry"` | Required `project`; optional `executable` | Uses the explicit manager or `poetry`, then `--directory <project> run python`. |
Directory paths must exist; relative paths resolve against the project root.
Manager/interpreter commands resolve through the project root or `PATH` during
study loading. Environment names must be nonblank and cannot begin with `-`.
See the [Config reference](src/config/api.md) for full path validation rules.
### Workload fields and fixed runtime behavior
Scientific definitions are documented in the [project JSON procedure](#2-write-project-json)
and [Config grammar](src/config/api.md): `seed`, `paths.states`, phase `after`
and `tasks`, task execution-unit/state/program/script selection, arguments, and
task seed derivation. `replicates.count` also describes the experiment (default
`1`, positive integer). `$npy.exclude_streams` selects conversion content
(default empty array of stream names). These are workload settings.
Operational budgets, scheduling, timeouts, failure policies, buffering, disk
policy, Python environments, and run selection may change without invalidating
completed work for reuse. Scientific inputs, replicate count, and schema
generation must still match. Stream exclusions must match when reusing `$npy`
or its consumers. If a resource choice changes scientific meaning, represent
that choice in scientific parameters.
`--clean` is a command-line option. The inferred output directory, UTC execution
names and log timestamps, terminal task paging, disk polling/recovery constants,
and NPY ramp interval have no `study.json` setting. There is no persistence
backend selector, process RAM cap, or CPU-utilization target in this grammar.
## Public API reference
The canonical ordinary import is `scientific_workflow::prelude::*`.
Readers and embedding hosts import less-common APIs from their owning module
roots.
The tables below list every supported public symbol and callable operation.
Documentation-hidden `__private`, `ExecutionUnitRegistration`, and `PayloadTuple`
exports exist only for procedural-macro expansion or sealed tuple bounds and
are not supported application APIs.
The complete supported symbol inventory is:
- Crate root and ordinary prelude: `run`, `execution_unit`, `WorkflowError`, `ExecutionUnit`,
`InitializationContext`, `MemberCompletion`, `MemberView`, `SeedError`, `UnitResult`,
`ObservationPlan`, `ObservationStream`, `ObservationError`, `StateTime`,
`SystemStateSchema`, `SystemState`, `StateSeries`, `StateSeriesPushError`,
`PayloadInsertError`, `StateError`, and `StateSeriesError`.
- Owning module roots: `ConfigError`, `Study`, `StudyError`, `execute`,
`RunSummary`, `ReplicateRunSummary`, `PhaseRunSummary`, `TaskRunSummary`,
`MemberRunSummary`,
`TaskRunKind`, `RuntimeError`, `StateFieldSchema`, `StateSchemaProvider`, `JsonPayloadDecoder`,
`JsonPayloadDecoderRegistry`, `StoredStateSeriesReader`,
`RecordingTiming`, and `PersistenceError`.
### Crate root, errors, and import scopes
| `scientific_workflow::run(project_root)` | `project_root: &Path` | Loads and preflights a project, executes it, and returns `Result<(), WorkflowError>`. This is the ordinary entry point. |
| `#[scientific_workflow::execution_unit("key")]` | One nonempty, whitespace-exact string literal on an `ExecutionUnit` impl | Registers the standalone execution unit or ensemble under the stable key selected by `wf_configs/study.json` and `wf_configs/parameters.json`. |
| `WorkflowError` | Variants `Study(StudyError)` and `Runtime(RuntimeError)` | Distinguishes effect-free loading/preflight failure from active execution failure. |
| `prelude` | Glob import; no parameters | Re-exports `run`, registration attributes, ordinary state, observation, unit, and workflow-error APIs. |
Config, Study, Persistence, Runtime, State, and Observation expose their
specialized public APIs directly at their module roots. Task, UI, and the
facade-error implementation remain private subsystems; unit authoring and
`WorkflowError` are exposed at the crate root.
### Execution-unit API
`UnitResult<T = ()>` is
`Result<T, Box<dyn Error + Send + Sync + 'static>>` and is the common execution unit
error boundary.
`ExecutionUnit` is `Send + Sized + 'static` and has one
associated type, `Constants: DeserializeOwned + 'static`. Constants themselves
need not be `Send` or `Sync` because each preflight/runtime decode is created
and consumed within its current thread:
| `standard_state_schema()` | no parameters; returns `Option<StateSchemaProvider>` | Optional static upstream schema used only when the task omits project `state`. The default is `None`; explicit project selection takes precedence. |
| `preflight(constants, schema)` | `constants: &Self::Constants`; `schema: &SystemStateSchema` | Optional side-effect-free unit-owned validation and observation declaration hook. Study trusts success. The default returns `ObservationPlan::all_fields()`; overrides may validate domain rules and select streams, fields, cadence, and units. |
| `initialize(constants, schema, context)` | fresh equivalent owned `Self::Constants`; `schema: &SystemStateSchema`; `context: &InitializationContext` | Required Runtime constructor for a standalone execution unit or ensemble. Every exposed state uses this schema allocation. Deterministic units may ignore the context; stochastic units request named seeds from it. |
| `member_count()` | `&self` | Returns the stable positive number of independently stateful members. |
| `member(index)` | `&self`; zero-based `usize` | Returns `Some(MemberView)` for every declared index and `None` outside the count. |
| `step()` | `&mut self` | Required coordinated transition. Every success advances at least one incomplete member; completed members cannot advance. |
Units receive no paths, writers, persistence sessions, progress callbacks, or
UI handles. Runtime checks cancellation between steps and automatically
observes initial, successful-step, and final states for each member.
Study and Runtime independently decode equivalent constants from the same
immutable Config value; custom `Deserialize` implementations must therefore be
deterministic and side-effect-free.
`InitializationContext` is a Workflow-created, immutable
initialization service. `dependencies()` exposes completed summaries from the
task's declared dependency phases, already correlated to the same resolved
global parameter configuration. `has_master_seed()` reports whether the study declared
one. `shared_seed(purpose)` derives a seed for unit-wide coordination;
`member_seed(member_identity, purpose)` derives one for a specific exposed member.
Both return `Result<u64, SeedError>`. Names must be stable, nonempty, and free
of surrounding whitespace. Derivation is versioned, includes study/runtime
identity facts, and is independent of request order and thread scheduling.
Every successful request and its actual seed is stored automatically with its
associated member recording. Deterministic units do not need a study seed and
simply ignore the context.
`SeedError` is the non-exhaustive error for a missing master seed,
invalid request name, or member-scoped request that does not match an exposed
`MemberView` identity. Its variants are `MissingMasterSeed`,
`InvalidName { field, value }`, and `UnknownMemberIdentity { identity }`. It
converts through `?` into `UnitResult`.
`MemberView<'a>` is a copyable borrow created with
`MemberView::new(identity, state, completion, target_iteration)`. Its getters are
`identity()`, `state()`, `completion()`, and `target_iteration()`. Identity,
index order, state address, and schema allocation are stable for the execution;
identity is nonempty, whitespace-exact, and unique. Completion is monotonic,
and a present target cannot decrease or disappear. A single execution unit returns one
view; an ensemble returns one per member. `completion()` is `None` while active
and `Some(MemberCompletion)` when complete. Use
`MemberCompletion::without_reason()` or `MemberCompletion::with_reason(&json_object)`;
`reason()` returns the optional borrowed object.
### Observation API
| `ObservationPlan::all_fields()` | None | Creates one inferred stream named `state` containing every schema field. |
| `ObservationPlan::fields(fields)` | `fields: IntoIterator<Item = impl Into<String>>` | Creates the inferred `state` stream with a nonempty unique field selection. |
| `ObservationPlan::streams(streams)` | `streams: IntoIterator<Item = ObservationStream>` | Creates a nonempty multi-stream plan; normalized stream names must be unique. |
| `ObservationPlan::with_iteration_unit(unit)` | consumes `self`; `unit: impl Into<String>` | Adds a nonblank unit for the iteration axis. |
| `ObservationPlan::with_physical_time_unit(unit)` | consumes `self`; `unit: impl Into<String>` | Adds a nonblank unit for the physical-time axis. |
| `ObservationStream::all_fields(name)` | `name: impl Into<String>` | Creates a named every-iteration stream containing all fields. |
| `ObservationStream::fields(name, fields)` | name plus `IntoIterator<Item = impl Into<String>>` | Creates a named stream with nonempty unique selected fields. |
| `ObservationStream::every_iterations(iterations)` | consumes `self`; positive `iterations: u64` | Changes cadence to iteration zero and iterations divisible by the interval; final observation is handled automatically. |
| `ObservationError` | Non-exhaustive error enum | Reports `EmptyPlan`, `EmptyStreamName`, `DuplicateStreamName`, `EmptyFieldName`, `EmptyFieldSelection`, `DuplicateField`, `UnknownField`, `InvalidSamplingInterval`, `EmptyAxisUnit`, `SchemaMismatch`, `StateAccess`, `EncodeField`, or `NonIncreasingObservation`. |
Plans and streams are immutable, cloneable declarations. They perform no IO;
Study binds them to the execution unit task's selected schema during preflight.
### State API
#### `StateTime`
| `from_iteration(iteration)` | `iteration: u64` | Creates an iteration-only coordinate. |
| `from_iteration_and_physical_time(iteration, physical_time)` | `u64`, finite `f64` | Returns `Some(StateTime)` for a finite physical coordinate, otherwise `None`. |
| `iteration()` | `self` | Returns the iteration. |
| `physical_time()` | `self` | Returns `Option<f64>`. |
| `checked_advance(increment)` | `self`; `increment: Option<f64>` | Computes the next iteration and optional physical-time advance without mutation. |
#### `SystemStateSchema` and `SystemState`
| `StateSchemaProvider::new(id, document)` | `id: &'static str`; `document: &'static [u8]` | Creates a const static handoff for a code-owned standard JSON schema. Parsing remains a Study responsibility. |
| `provider.id()` / `provider.document()` | `self` | Returns the stable provenance ID or borrowed static JSON bytes. This specialized type lives at `scientific_workflow::state`. |
| `provider.resolve()` | `self` | Validates the embedded JSON and returns a new `SystemStateSchema` without filesystem IO for direct integrations. Study performs cached resolution automatically. |
| `SystemStateSchema::load_json_template(path)` | `path: &Path` | Reads and strictly validates a standalone JSON state schema. Composed Workflow instead supplies Config's already parsed named documents internally. |
| `schema.create_empty_state(time)` | `time: StateTime` | Creates an empty `SystemState` sharing the schema. |
| `state.time()` | `&self` | Returns the current `StateTime` by value. |
| `state.advance_time(increment)` | `&mut self`; `Option<f64>` | Atomically advances iteration and, when supplied, an existing physical coordinate. |
| `state.schema()` | `&self` | Borrows the shared `SystemStateSchema`. |
| `state.contains_payload(key)` | `key: &str` | Reports whether a declared field is populated. |
| `state.initialize_payload(key, payload)` | `key: &str`; owned `T: Serialize + Clone + Send + 'static` | Initializes a field exactly once and establishes its retained concrete type. Failure returns the unchanged payload in `PayloadInsertError<T>`. |
| `state.insert_payload(key, payload)` | same key and `T` bounds | Initializes or replaces a same-typed payload, returning `Option<T>` for the previous owner. |
| `state.payload::<T>(key)` | `key: &str`; `T: Any` | Returns `&T` after field, presence, and exact-type validation. |
| `state.payload_mut::<T>(key)` | `key: &str`; `T: Any` | Returns `&mut T` under the same validation. |
| `state.borrow_payloads::<Q>(keys)` | tuple type `Q`; matching tuple of 2-8 field names | Returns checked immutable references to distinct typed fields. |
| `state.borrow_payloads_mut::<Q>(keys)` | tuple type `Q`; matching tuple of 2-8 field names | Returns checked disjoint mutable references after complete validation. |
| `state.take_payload::<T>(key)` | `key: &str`; `T: Any + Send` | Moves a payload out without cloning while retaining the field's type contract. |
`SystemState` is `Clone`; cloning deep-clones every populated payload. It is
`Send` but not `Sync`, so shared cross-thread mutation requires external
synchronization.
#### `StateSeries` and ownership-preserving errors
| `StateSeries::new(schema)` | owned `SystemStateSchema` | Creates an empty ordered series. |
| `StateSeries::with_capacity(schema, capacity)` | schema; `capacity: usize` | Creates an empty series with owner capacity reserved. |
| `schema()`, `len()`, `is_empty()`, `capacity()` | `&self` | Inspect collection identity and size. |
| `reserve(additional)` | `&mut self`; `additional: usize` | Reserves state-owner capacity. |
| `state_at(position)` | `position: usize` | Borrows a state by collection position, not scientific iteration. |
| `payload_mut_at::<T>(position, key)` | `usize`, `&str`; `T: Any` | Mutably borrows one payload without exposing structural state mutation. |
| `first_state()`, `last_state()` | `&self` | Borrow boundary states, or `None` when empty. |
| `as_state_slice()`, `iter()` | `&self` | Borrow all states in increasing iteration order. |
| `push_state(state)` | owned `SystemState` | Appends only when schema identity matches and iteration strictly increases. Rejection preserves the state. |
| `pop_state()` | `&mut self` | Moves out the last state. |
| `clear_states()` | `&mut self` | Drops states but retains schema and allocation capacity. |
| `into_states()` | owned `self` | Moves out the complete backing vector. |
| `StateSeriesPushError::error()` | `&self` | Borrows the `StateSeriesError`. |
| `StateSeriesPushError::state()` | `&self` | Borrows the unchanged rejected state. |
| `StateSeriesPushError::into_parts()` | owned `self` | Returns `(StateSeriesError, SystemState)`. |
| `PayloadInsertError<T>::error()` / `payload()` | `&self` | Borrow the rejection reason or unchanged incoming payload. |
| `PayloadInsertError<T>::into_parts()` | owned `self` | Returns `(StateError, T)` without cloning. |
`StateSeries` supports `IntoIterator` for owned and borrowed series. Explicit
`Clone` deep-clones its states and payloads. `StateError` is non-exhaustive and
currently exposes `TemplateRead`, `TemplateParse`, `EmptyFieldName`,
`DuplicateField`, `UnknownField`, `RepeatedPayloadBorrow`, `MissingPayload`,
`TypeMismatch`, `PayloadAlreadyInitialized`, `IterationOverflow`,
`MissingPhysicalTime`, and `InvalidPhysicalAdvance`. `StateSeriesError` is
non-exhaustive and exposes `SchemaMismatch`, `NonIncreasingIteration`,
`PositionOutOfBounds`, and `PayloadAccess`.
### State inspection and maintenance API
These are inherent methods; no extension-trait import is required:
| `StateFieldSchema::position()` | `&self` | Returns declaration-order slot position. |
| `StateFieldSchema::name()` | `&self` | Borrows the normalized field name. |
| `StateFieldSchema::description()` | `&self` | Borrows the optional normalized description. |
| `SystemStateSchema::shares_schema_instance(other)` | `other: &SystemStateSchema` | Tests shared allocation identity, not structural equality. |
| `template_path()` | `&self` | Borrows retained schema provenance path. |
| `field_schemas()` | `&self` | Borrows fields in declaration order. |
| `field_schema(name)` / `contains_field(name)` | `name: &str` | Looks up or tests a field. |
| `len()` / `is_empty()` | `&self` | Inspects schema field count. |
| `to_json_template()` | `&self` | Returns strict pretty JSON for the schema. |
| `SystemState::clone_structure_without_payloads(time)` | `time: StateTime` | Creates an empty related state retaining schema and field type contracts. |
| `replace_time(time)` | `&mut self`; `StateTime` | Replaces time and returns the previous value. |
| `populated_field_count()` | `&self` | Counts populated slots. |
| `payload_has_type::<T>(key)` | `key: &str`; `T: Any` | Tests the exact concrete type of a populated field. |
| `clear_payload(key)` | `key: &str` | Drops one payload and returns whether one was present. |
| `clear_all_payloads()` | `&mut self` | Drops every payload while retaining structure and type contracts. |
### Config and Study API
| `ConfigError` | Non-exhaustive enum | Reports `Read`, `Parse`, `DuplicateKey`, `InvalidDocument`, `PathOutsideConfig`, `InvalidProgram`, `UnknownDependency`, `UnknownState`, `ExpansionOverflow`, or `DecodeExecutionUnitConstants`. Context fields retain paths, JSON pointers, execution unit/state/phase keys, ordinals, and sources as applicable. |
| `Study::load(project_root)` | `project_root: &Path` | Performs complete effect-free Config loading, state validation, execution unit discovery, parameter decode, program/Python resolution, and observation preflight. |
| `study.project_root()` | `&self` | Borrows Config's canonical project root. |
| `study.output_root()` | `&self` | Borrows the inferred `<project-root>/output` path; it need not exist yet. |
| `StudyError` | Non-exhaustive enum | Reports `Config`, contextual project `State`, `ProvidedState`, `InvalidStateSchemaProvider`, `MissingStateSchema`, `InvalidExecutionUnitRegistration`, `UnknownExecutionUnit`, `ExecutionUnitPreflight`, or `TaskIdentityOverflow`. Every variant occurs before Runtime creates output. |
`Study` is immutable and clone-cheap through shared ownership. Its phase graph,
tasks, selected schemas, resolved constants, and policies are intentionally not
publicly mutable or inspectable.
### Runtime API
| `runtime::execute(study)` | owned `Study` | Executes validated intent and returns `Result<RunSummary, RuntimeError>`. |
| `RunSummary::output_directory()` | `&self` | Borrows the unique execution directory. |
| `RunSummary::replicates()` | `&self` | Borrows successful replicate summaries in ascending index order. |
| `ReplicateRunSummary::index()` | `&self` | Returns the zero-based replicate index. |
| `ReplicateRunSummary::output_directory()` | `&self` | Borrows the replicate directory. |
| `ReplicateRunSummary::phases()` | `&self` | Borrows phases in dependency execution order. |
| `PhaseRunSummary::name()` | `&self` | Borrows the manifest phase key. |
| `PhaseRunSummary::tasks()` | `&self` | Borrows task summaries in deterministic Study order. |
| `TaskRunSummary::identity()` | `&self` | Borrows the Study-inferred identity. |
| `TaskRunSummary::kind()` | `&self` | Borrows non-exhaustive `TaskRunKind`: `ExecutionUnit { execution_unit, members }` or `Program { executable, python_script }`. |
| `TaskRunSummary::output_directory()` | `&self` | Borrows the task root or program-workspace directory. |
| `MemberRunSummary::identity()` | `&self` | Borrows the member identity supplied by the execution unit. |
| `MemberRunSummary::final_iteration()` | `&self` | Returns that member's terminal iteration. |
| `MemberRunSummary::output_directory()` | `&self` | Borrows that member's completed recording directory. |
| `RuntimeError` | Non-exhaustive enum | Reports `ExecutionCancelled`, `OutputScope`, `Task`, `TaskPanicked`, `TaskTimedOut`, `TaskCancelled`, `PhaseTimedOut`, `StartWorker`, `ReplicatePanicked`, or contextual `Replicate` failure. |
Summary objects are cloneable, read-only owned values and perform no IO.
### Persistence read API
Persistence writing is automatic and has no public writer constructor. The
public surface reconstructs completed member recordings:
| `JsonPayloadDecoder<T>::decode_json_payload(raw_json)` | `raw_json: &str` containing exactly one JSON value | Converts borrowed encoded input into one owned typed field payload. The associated `Error` must be thread-safe and `'static`; compatible closures implement the trait. |
| `JsonPayloadDecoderRegistry::new()` | None | Creates an empty exact-field decoder registry. |
| `with_capacity(capacity)` | `capacity: usize` | Creates an empty registry with key capacity. |
| `with_json_field::<T>(key)` | consumes registry; `key: impl Into<String>`; `T: DeserializeOwned + Serialize + Clone + Send + 'static` | Adds a Serde JSON decoder and returns the registry. |
| `register_for_field::<T, D>(key, decoder)` | `&mut self`; exact key; `D: JsonPayloadDecoder<T>` | Registers one custom typed decoder. Empty or duplicate keys fail. |
| `len()`, `is_empty()` | `&self` | Inspect registry size. |
| `has_decoder_for_field(key)` | `key: &str` | Tests exact registration. |
| `registered_field_names()` | `&self` | Iterates keys in unspecified hash-map order. |
| `StoredStateSeriesReader::open_completed_recording(root, decoders)` | `root: &Path`; owned registry | Synchronously validates completed `metadata.json` and retains the decoder registry. |
| `recording_directory()` | `&self` | Borrows the supplied recording root. |
| `stream_names()` / `format_version()` | `&self` | Iterates stream names in metadata order or returns the format version. |
| `user_metadata()` / `terminal_metadata()` | `&self` | Borrows creation-time or completion-time JSON metadata maps. |
| `recording_timing()` | `&self` | Borrows verified `RecordingTiming`. |
| `stream_record_count(stream)` | `stream: &str` | Returns checked declared record count. |
| `stream_encoded_bytes(stream)` | `stream: &str` | Returns checked declared encoded bytes. |
| `read_stream_as_state_series(stream)` | `stream: &str` | Verifies and reconstructs one complete ordered `StateSeries`. |
| `read_all_streams_as_state_series()` | `&self` | Returns every stream as `Vec<(String, StateSeries)>`, with no partial success. |
| `read_latest_state_from_stream(stream)` | `stream: &str` | Fully verifies every record and descriptor fact in the newest chunk, then reconstructs its final `SystemState`. |
| `RecordingTiming::created_at_utc()` / `finalized_at_utc()` | `&self` | Borrows RFC 3339 UTC timestamps. |
| `active_duration()` | `&self` | Returns the persisted active duration. |
`PersistenceError` is non-exhaustive. Its current variants are
`Observation`, `RecordingDirectoryExists`, `InvalidConfiguration`,
`DuplicateStateStream`, `UnknownStateStream`, `StateWriterClosed`,
`RecordingFinished`, `RecordingDirectoryInUse`, `NoRecordedState`,
`OperationalTimestamp`, `OperationalDurationOverflow`, `UnsupportedVersion`,
`InvalidMetadata`, `RecordingNotComplete`, `MissingChunk`,
`ChunkSizeMismatch`, `ChecksumMismatch`, `InvalidRecord`, `DuplicateDecoder`,
`MissingDecoder`, `DecodeField`, `StateSeriesInvariant`, `Io`, `Json`,
`ByteCountOverflow`, `RecordTooLarge`, `OutOfOrderIteration`,
`WriterQueueDisconnected`, `StateWriterTerminated`, and `StateWriterPanicked`.
Reader users normally encounter the metadata, integrity, decoder, state-series,
IO, and JSON families; write-only variants remain public so Runtime can retain
complete source chains, not to expose writer control.
For exhaustive invariants, failure atomicity, thread-safety, and examples, use
the subsystem contracts linked at the end of this guide.
## Complete user procedure
### 1. Define an execution unit
The execution unit directly owns its canonical `SystemState`. Its associated constants
type is the complete typed form of one expanded section selected from
`wf_configs/parameters.json` by the execution unit's registration key.
In the fixed-duration example below, `StateTime::iteration()` is the current
completed iteration, while `target_iteration` retains the configured stopping
target; it is not a second progress counter.
`ExecutionUnit` is a Rust trait: a behavioral contract that lists what Workflow
must be able to ask a scientific model to do. Writing
`impl ExecutionUnit for PopulationUnit` promises that `PopulationUnit` supplies
that lifecycle. The separate `#[execution_unit("population")]` attribute only
registers the implementation under the JSON key `population`; it does not
generate the model, state fields, or method bodies.
```rust,no_run
use serde::Deserialize;
use scientific_workflow::prelude::*;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Constants {
initial_population: u64,
steps: u64,
}
struct PopulationUnit {
state: SystemState,
target_iteration: u64,
}
#[scientific_workflow::execution_unit("population")]
impl ExecutionUnit for PopulationUnit {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = Constants;
fn initialize(
constants: Constants,
schema: &SystemStateSchema,
_context: &InitializationContext,
) -> UnitResult<Self> {
let mut state = schema.create_empty_state(StateTime::from_iteration(0));
state.initialize_payload("population", constants.initial_population)?;
state.initialize_payload("cumulative_births", 0_u64)?;
Ok(Self {
state,
target_iteration: constants.steps,
})
}
fn member_count(&self) -> usize { 1 }
fn member(&self, index: usize) -> Option<MemberView<'_>> {
(index == 0).then(|| MemberView::new(
"population",
&self.state,
(self.state.time().iteration() >= self.target_iteration)
.then_some(MemberCompletion::without_reason()),
Some(self.target_iteration),
))
}
fn step(&mut self) -> UnitResult {
let (population, cumulative_births) = self
.state
.borrow_payloads_mut::<(u64, u64)>(
("population", "cumulative_births"),
)?;
*population += 1;
*cumulative_births += 1;
self.state.advance_time(None)?;
Ok(())
}
}
```
`ExecutionUnit::preflight` defaults to
`ObservationPlan::all_fields()`. Override it only
when domain validation or selected fields, named streams, cadence, or units
carry scientific meaning. The preflight function may inspect constants and
the selected schema but must be deterministic and side-effect-free.
The execution unit is an ordinary Rust owner: its single `MemberView` returns a direct
borrow of its `SystemState`, and coupled field access uses a typed tuple expansion. The
attribute does not define the execution unit or generate field access. Its stable key is
only the automatic bridge from `wf_configs/study.json` to compiled Rust behavior, so there
is no separate registry list in `main`.
For an ensemble, the registered implementor owns a stable collection of members:
```text
Task -> ExecutionUnit (ensemble; one coordinated lifecycle)
+-- MemberView[0] -> SystemState A -> recording A
`-- MemberView[1] -> SystemState B -> recording B
```
Its `member_count()` returns the collection length, `member(index)` reports each
member's independent completion and target, and `step()` owns all shared inputs,
synchronization, and internal parallelism. Workflow does not inspect or control
that parallelism. Member count/order/identity and state addresses remain stable;
completed members stay in the collection and are skipped internally rather than
removed or reordered.
Standalone executable and Python tasks require no Rust trait or wrapper.
Declare them in `wf_configs/study.json`; they receive the same captured central project
configuration and dependency results at runtime. A Python task declares its
environment locally inside its nested `python` object—there is no global
environment registry. Either external-task form may declare one optional
`seed: {"purpose":"..."}` request. Workflow derives a task-scoped value from
the study master seed, passes only that value as `WORKFLOW_TASK_SEED`, and
records the request in `program.json`.
### 2. Write project JSON
```text
project/
├── scripts/
│ └── plot.py
└── wf_configs/
├── study.json
├── parameters.json
└── states/
└── population.json
```
The `wf_configs/` directory is required and identifies the project root passed
to Workflow. Both `wf_configs/study.json` and
`wf_configs/parameters.json` are required. The `states/` directory is the
recommended organization, not a requirement: schemas may live anywhere beneath
`wf_configs/` when their exact project-root-relative paths are supplied in
`study.json.paths.states`. Paths outside `wf_configs/` are rejected. When a
receiving execution unit declares a linked standard provider, its task may
omit `state`; a project that uses only providers needs neither `paths.states`
nor project state-schema files. An empty `state` string is never equivalent to
omission.
`wf_configs/states/population.json`:
```json
{
"fields": [
{"name":"population"},
{"name":"cumulative_births"}
]
}
```
`wf_configs/parameters.json`:
```json
{
"population": {
"initial_population": 10,
"steps": {"$sweep":[100, 200]}
},
"plot": {
"output_directory": "output/plots",
"dpi": 180
}
}
```
`wf_configs/study.json`:
```json
{
"active_phases": [0,1],
"workflow_schema": 1,
"threads": 16,
"compute": {"mode": "auto"},
"seed": 42,
"paths": {
"states": {
"population": "wf_configs/states/population.json"
}
},
"phases": {
"simulate": {
"tasks": [
{"execution_unit":"population","state":"population"}
],
"max_concurrency": 2
},
"plot": {
"after": ["simulate"],
"tasks": [{
"python": {
"script": "scripts/plot.py",
"environment": {
"manager": "mamba",
"name": "DSES"
}
},
"seed": {"purpose":"plot-sampling"},
"resources": {"threads": 4}
}]
}
}
}
```
The top-level positive `threads` field is required and is the global compute
budget. Required `compute.mode` selects `auto`, which divides that budget
equally among working thread-count-invariant execution units, or `isolated`,
which requires fixed per-task `resources.threads`. Every working unit gets a
private Rayon pool; pending units get no automatic share. Program/Python tasks
optionally declare `resources.threads`, defaulting to one; Runtime admits them
against the same global ceiling and supplies the reserved value as
`WORKFLOW_THREADS` and `RAYON_NUM_THREADS`. External tasks do not overlap
execution-unit tasks. Environment variables cannot override the manifest. The
top-level `seed` is optional for deterministic projects. A stochastic
execution unit requests purpose-named derived seeds through its
`InitializationContext`; an external program or Python task declares one
task-level purpose as shown above. A program request without the top-level seed
is rejected during Config loading, while a unit request without it fails during
initialization. Derived values are stable across scheduling changes and are
recorded in the applicable member metadata or `program.json`.
Persistence is automatic. The omitted root `persistence` object infers the
local backend with a 64 MB decimal chunk target and queue capacity.
Projects that need explicit operational sizing may add:
```json
"persistence": {
"chunk_target_mb": 64,
"queue_capacity_mb": 64
}
```
All JSON persistence sizes are authored in decimal megabytes; one MB is
exactly 1,000,000 bytes. Config converts both settings into exact internal byte
counts.
Users never provide Rust recording paths, construct a backend, submit
observations, or finalize a recording. External programs may own a
project-relative domain output such as the Python plotter's `output/plots`.
UI is also automatic. No `ui` object or execution unit display fields are required.
Interactive stdin and stderr select the Ratatui dashboard with inferred task
rows for all active phase groups, progress, timing, lifecycle messages, and the
`exit` command. A Usage section beneath Messages reports CPU, RAM, and
execution-filesystem disk occupation. Completed groups disappear; Messages
retain their latest outcomes without scrolling, while the complete timestamped
history is flushed live to `<execution>/log.txt` for `tail -f` or later review.
Execution clocks freeze during pause; the Study Total time clock continues.
After success, failure, or cancellation, the interactive dashboard stays open
so the terminal outcome can be inspected; type exact lowercase `exit` and press
Enter to close it. `exit` during active work also requests cooperative
cancellation. Ctrl+C cancels active work but does not close the dashboard, so a
final `exit` is still required. Run inside `screen` or `tmux` for persistent
sessions. Noninteractive execution is rejected; the dashboard is required.
Failure of the dashboard
is fatal and returns `RuntimeError::Presentation` rather than silently
degrading or being reported as cooperative workflow cancellation. The
[UI reference](src/ui/api.md) details commands, live logging, usage sampling,
and pause boundaries.
Config alone reads `wf_configs/study.json`, every named project state document, and the complete
arbitrary `wf_configs/parameters.json` namespace once. A top-level section
whose name is selected by an execution-unit task is inferred as local to that
unit; every other top-level parameter is shared globally. Global choices clone
the complete phase graph, and local choices clone only their execution-unit
task. `$sweep` creates independent Cartesian choices. Since 0.13.8,
each sweep alternative can itself contain independent sweep axes: an outer
`[null, {"size":{"$sweep":[2,4]}, "strength":{"$sweep":[0.1,0.8]}}]` choice
produces one base plus four variants. Expansion preserves declared ordering;
`$cases` remains a terminal correlated selection, and ordinary arrays remain
literal. See the [Config contract](src/config/api.md#nested-alternatives-and-independent-axes). Users do not write a
scope marker, reference, or ordinal. Program arguments are optional opaque strings and executables are
started directly without a shell. Python-specific `script`, `environment`, and
`args` stay nested beneath `python`; generic timeout policy remains on the
containing task. Supported managers are `system`, `venv`, `mamba`, `conda`,
`uv`, and `poetry`, with manager-specific paths/names validated during Study
loading.
### 3. Run
```rust,no_run
fn main() -> Result<(), scientific_workflow::WorkflowError> {
scientific_workflow::run(std::path::Path::new("."))
}
```
That call loads all declarations, discovers execution units, validates typed constants,
binds each observation plan to its execution unit task's explicitly selected
project schema or linked standard provider, resolves program paths and Python
environments, creates immutable generic tasks and phases, compiles the
effective persistence plan, infers identities/output paths, schedules work,
and persists every exposed member automatically while publishing inferred
aggregate terminal progress.
Each program or Python script receives absolute `WORKFLOW_CONFIG_PATH` and
`WORKFLOW_DEPENDENCIES_PATH` snapshot files for its resolved global
configuration plus project, execution, replicate,
and task-output paths through `WORKFLOW_*` environment variables. It runs in an
isolated `artifacts/` working directory; Workflow captures stdout, stderr, and
terminal status. A seeded external task additionally receives the derived
decimal `WORKFLOW_TASK_SEED`; unseeded tasks do not receive that variable. A program may instead write domain outputs to a safe
project-relative destination it reads from `wf_configs/parameters.json`. Editing project
JSON after `Study::load` does not alter that execution.
Output is created beneath `<project-root>/output` only after Study preflight
succeeds.
### Advanced: standard upstream state providers
Use a provider when one upstream crate—not each application project—owns the
canonical state layout. The upstream embeds its JSON and exports a typed
descriptor; it does not know the receiver, dispatcher, or project root:
```rust,ignore
use scientific_workflow::state::StateSchemaProvider;
pub const fn ecological_state_schema() -> StateSchemaProvider {
StateSchemaProvider::new(
"ecological-state-toolkit.ecological-state.v1",
include_bytes!("../schemas/ecological_state.json"),
)
}
```
The downstream execution unit is the receiver and delegates its optional trait
hook to that upstream API:
```rust,ignore
impl ExecutionUnit for GlvUnit {
const THREAD_COUNT_INVARIANT: bool = true;
type Constants = GlvConstants;
fn standard_state_schema() -> Option<StateSchemaProvider> {
Some(ecological_state_toolkit::state_schema::ecological_state_schema())
}
// preflight, initialize, member_count, member, and step follow.
}
```
Its project task can then be `{"execution_unit":"glv"}` with no `state` and no
`paths.states`. Study validates and caches the embedded document, passes the
resulting `SystemStateSchema` to `preflight` and `initialize`, and records
`ecological-state-toolkit.ecological-state.v1` as state provenance. If a
project does declare `{"execution_unit":"glv","state":"experiment"}`, that
explicit schema wins. Omission without either an explicit selection or a
provider fails before output.
## Architecture at a glance
- `state`: canonical typed scientific state and schema;
- `observation`: observation meaning and borrowed encoding;
- `task`: generic scientific/program tasks (including Python), `ExecutionUnit`,
per-member `MemberView`, registration, and uniform invocation;
- `config`: sole all-JSON parser, immutable snapshot, executable/Python
environment resolver, and typed constants supplier;
- `study`: effect-free binding and immutable declared intent;
- `runtime`: active execution and output creation;
- `persistence`: automatic durable lifecycle and verified reading;
- `ui`: sole automatic terminal presentation of Runtime facts, with fatal
renderer-health enforcement;
- `error`: complete-workflow Study/Runtime error composition; and
- `prelude`: the ordinary execution-unit authoring imports.
The crate-level `run(&Path)` facade loads a Study and then invokes Runtime.
Study coordinates declared intent; runtime accepts that completed Study and
coordinates active execution.
Embedding consumers may use `Study::load` and `runtime::execute`, but
ordinary projects should not.
The repository's [`attractor_2d`](../examples/attractor_2d) project combines
these pieces end to end: six swept Rust execution unit tasks feed one directly declared
Python plotting phase that opens the verified recordings and emits an SVG in
the configured `output/plots` directory.
Each public subsystem owns one module-root API. The single prelude contains the
small execution-unit author surface. Persistence writing is automatic and
private; only verified reading is public.
See [`src/state/api.md`](src/state/api.md),
[`src/observation/api.md`](src/observation/api.md),
[`src/task/api.md`](src/task/api.md),
[`src/config/api.md`](src/config/api.md),
[`src/study/api.md`](src/study/api.md),
[`src/persistence/api.md`](src/persistence/api.md),
[`src/runtime/api.md`](src/runtime/api.md),
[`src/ui/api.md`](src/ui/api.md),
[`src/error/api.md`](src/error/api.md),
[`src/prelude/api.md`](src/prelude/api.md), and the repository
[`architecture.md`](https://github.com/dingyisun0101/Scientific-Workflow/blob/v0.15.0/docs/architecture.md).
## Validation
From the repository root:
```bash
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
cargo test --workspace --all-targets --all-features --locked
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --all-features --no-deps --locked
```
### Optional phase and execution-unit selection
Omitting `active_phases` selects every phase. To select a subset, set
`"active_phases": [0, 1, ...]`. 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.
Within a selected phase, an execution-unit task may set `"active": false`.
Inactive units retain their compiled identities and output ordinals but are not
run or reused. `active` defaults to `true` and is invalid on other task kinds.
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. Work-relevant inputs still must match: parameters,
schemas, seeds, programs/scripts, arguments, replicate count, and phase dependencies.
Compute/thread budgets, scheduling, timeouts, failure policy, persistence buffering,
disk policy, and Python environment-manager settings are operational provenance
and do not invalidate completed work. If a resource setting changes scientific
meaning, express that choice in scientific parameters.
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.
## Run cleanup and timestamps
The ordinary `run(&Path)` facade recognizes `--clean` before an optional `--`
argument delimiter, for example `cargo run -- --clean`. After complete study,
reuse, and Python preflight, it clears `<project-root>/output` before creating
the execution. Other arguments remain application-owned. `runtime::execute`
does not inspect process arguments and does not clean.
All runs hold shared advisory locks on the project and output directories; a
cleaning run holds both exclusively until execution and presentation finish. Cleanup rejects
an output-root symlink/file, a conflicting active run, or a target containing
configuration, a resolved executable/script, a selected reuse source, or any
imported task/member/NPY directory. Child symlinks are removed without following
them. Deletion errors abort startup; already removed entries are not restored.
The output directory itself is preserved. Older Workflow versions do not
participate in this project-lock protocol.
Execution directories use `execution-YYYYMMDDTHHMMSS.nnnnnnnnnZ`, UTC, with an
additional numeric suffix only on collision. Atomic directory creation prevents
reuse even if the clock repeats. Names are invocation identities; scientific
task identity is unchanged. Every physical `log.txt` line receives an absolute
RFC 3339 UTC timestamp when appended, including buffered and multiline messages.
Execution requires the dashboard; launch inside `screen` or `tmux` for long runs.
## Disk guard and NPY resource policy
`study.json` accepts optional `"disk": {"pause_at_percent": 95}`. The default
is 95; a finite numeric threshold must be greater than 0 and at most 100. Use
`null` as the threshold to explicitly bypass the guard. Unknown fields and
invalid values are rejected during Config preflight.
Runtime samples the output filesystem before admitting work and every 250 ms
of wall time. At the threshold it requests a disk pause and tells the user to
free space, then type `resume` and Enter. Usage must reach
`max(0, threshold - 2)` percent before that command can succeed. Recovery alone
never resumes work: a second reminder and the dashboard status indicate when
space is sufficient. The explicit command clears the disk and manual pauses;
an early command is rejected without being queued. The shared active clock
freezes while either pause holds. Cancellation wakes paused work. Sampling or monitor
startup failure produces `RuntimeError::DiskMonitor { path, source }`; an active
monitor failure cancels work and is returned after joining workers. The guard
is stopped before the terminal's final user-input wait.
Execution units pause between host calls; cooperative NPY tasks acknowledge
through control IPC. For non-cooperative Unix programs, disk pause sends SIGSTOP
to the owned process group and recovery sends SIGCONT. Cleanup resumes a stopped
group before terminating it. Disk enforcement is sampled and cooperative calls
may take time to return, so the threshold is a pause trigger, not reserved free
space or a guarantee that in-flight writes cannot fill the filesystem.
The `$npy` phase accepts `"threads": 4` and `"mode": "auto"` (or `"fixed"`).
Leave the worker limit unset unless reserving resources for other tasks requires
a lower limit. Threads default to `study.threads` and must be a positive integer no larger than
that global limit. Mode defaults to `auto`; these fields are invalid on ordinary
phases. Runtime reserves `min(phase.threads, study.threads, recording_count)`
permits through the existing shared budget, including across replicates. Each
conversion worker limits native numerical pools to one thread. Fixed mode admits
workers up to that allowance immediately; auto begins at one and increases the
admission limit by one every 250 ms of active time until the allowance is reached.
Short batches may finish before reaching the limit. This does not measure CPU
or RAM utilization, and the full allowance remains reserved during ramp-up.
Python's `convert_workflow_dependencies` adds the optional keyword
`worker_mode="auto"`; `"fixed"` selects immediate admission. Other values raise
`NpyConversionError` before output creation. The Workflow CLI accepts
`--worker-mode=fixed|auto` with `--workflow-dependencies`; ordinary single-recording
conversion rejects it. Mode does not change result or reuse identity.
## Thread display and task pages
Runtime publishes a complete snapshot of active task allocations, serialized
across replicate schedulers and sampled at most every 50 ms, with immediate
publication after activation and at phase/execution completion. Internal pools
report their actual current Rayon pool sizes, including automatic rebalancing;
external programs and NPY report their reserved compute allowance. One private
working-task registry ties display entries to resource-lease lifetime.
The task table includes a `threads` column. Usage shows `THREADS allocated/budget`
across all running tasks, including tasks on other pages and in other replicates.
These are allocated compute threads, not measured CPU activity or every OS
thread. Paused tasks retain their allocation; pending and completed tasks count
as zero. NPY auto ramp-up reports the reserved allowance. The private
`ThreadAllocations { allocations, budget }` event carries the whole allocation
set so UI never combines partial rebalancing updates into an inflated total.
PageUp/PageDown move by the task table's visible data-row capacity, excluding
borders and its header. The footer no longer replaces a task row. The title
shows the current page and page count. Resizing recalculates capacity and clamps
to a valid page; an existing first-row anchor is retained where possible, and a
disappearing active-group anchor resets to the first page. All rows on a full
page are usable, and the final page may contain fewer rows.