# Persistence API
This guide documents the `scientific-workflow` 0.16.0 subsystem contract.
The `persistence` subsystem owns every Workflow-managed durable task output and
verified member-state reconstruction. Config parses optional operational sizing,
Study retains the effective private plan, and Runtime constructs and drives one
private session for every exposed member. A standalone unit produces
one session; an ensemble produces one per member. A execution unit session records observed state; a
program session—including a Config-lowered Python invocation—prepares one
isolated bookkeeping workspace, snapshots inputs, captures logs, and commits
status. Execution units never receive a writer, destination, queue, flush operation, or
lifecycle handle. External programs own their domain-specific filesystem IO;
Rust Persistence manages only their workspace and launch evidence.
For execution unit tasks, Observation decides which scientific fields and cadences matter. Persistence
only stores the resulting encoded observations, lifecycle metadata, and
Workflow provenance. It does not parse project JSON, bind tasks, or schedule
execution.
The repository-level
[recording v7 protocol](https://github.com/dingyisun0101/Scientific-Workflow/blob/main/protocol/recording-v7.md) is the
normative language-neutral contract for member recordings. Its companion JSON
Schema covers structural constraints, while the protocol document defines
cross-field, filesystem, ordering, integrity, and transaction requirements.
The package support matrix is maintained separately in
[compatibility matrix](https://github.com/dingyisun0101/Scientific-Workflow/blob/main/protocol/compatibility.md). Program
workspaces are explicitly outside that wire protocol.
## Basic API
### Automatic persistence behavior
The ordinary user-facing surface is the optional root object in
`wf_configs/study.json`:
```json
"persistence": {
"chunk_target_mb": 64,
"queue_capacity_mb": 64
}
```
Both fields are optional positive integers. `chunk_target_mb` defaults to 64
decimal megabytes, where one MB is exactly 1,000,000 bytes, and is converted
once into the approximate encoded-byte chunk rollover target during Config
loading. `queue_capacity_mb` follows the same unit/default and becomes the
per-stream queued-data backpressure capacity. No JSON persistence-size field
accepts bytes. Conversion overflow and invalid settings fail during
Config/Study loading before output exists. The backend and all destinations
are inferred. These settings apply to member-state streams; external program
workspaces require no separate user setting.
Program persistence is equally automatic. Each program task gets this private
durable layout:
```text
task-NNNNNN/
├── program.json
├── workflow-config.json
├── workflow-dependencies.json
├── stdout.log
├── stderr.log
└── artifacts/
```
`program.json` uses `scientific-workflow-program-v2`, with required `inputs`
checksum references described below. It is atomically replaced from `running` to `complete` or `failed`
and records `kind` (`program`, `python`, or Workflow's synthesized `npy`), the resolved launcher executable,
arguments, the authoritative `threads` count, exit code/reason, format name,
and fixed workspace filenames. Each
fixed file is synchronized before publication, and each program-status rename
is followed by a workspace-directory synchronization. A failed-status update
remains best effort when reporting an already-authoritative task/process
failure. For Python, metadata additionally records the canonical
`python_script` and declared `python_environment_manager`; those fields are
null for a generic program. Runtime passes the other paths to the child.
When the task declared a seed request, `program.json.seed_derivation` records
the same versioned algorithm and master-seed provenance used for execution
units plus one task-scoped request containing its purpose and actual derived
`u64` value. The field is null for an unseeded program. It is written in the
initial `running` metadata and retained unchanged in either terminal state, so
failed subprocesses remain reproducible.
`artifacts/` is the default working directory and remains available for
temporary or task-scoped results.
Workflow's reserved `$npy` task is the standard exception to ordinary
program-owned artifact semantics: its workspace retains launch evidence, but
its bundled Python module verifies all transitive prerequisite member
recordings across the replicate and publishes C-contiguous arrays plus
conversion manifests at `<execution>/processed/replicate-NNNNNN`. The raw
recordings remain immutable.
An external program may instead read a project-relative destination from the
frozen `wf_configs/parameters.json` snapshot and write there directly. The bundled Python
plotter uses `output/plots`. Such files are program-owned: Persistence does not
move, publish, validate, or reconstruct them.
Scientific task layout depends only on execution-unit cardinality:
```text
task-NNNNNN/ one-member recording
task-NNNNNN/ multi-member execution-unit root
└── members/
├── member-000000/ first member recording
└── member-000001/ second member recording
```
Stable numeric indices—not application identities—form paths. Each recording's
`user_metadata.workflow` object retains `member_index` and `member_identity`
alongside the registered key, resolved state provenance, parameter provenance,
the resolved project `parameters`, the authoritative `threads` count, and effective
persistence plan. `workflow.compute` contains the selected `auto` or `isolated`
mode and the allocation history known when recording begins. On successful
completion, `terminal_metadata.compute` contains the final ordered allocation
history as `{epoch, threads}` objects, making every automatic rebalance or
fixed isolated allocation auditable without changing recording format. Failed
recordings retain the history known when failure is terminalized. If the
unit successfully requested Workflow-derived seeds,
the same object contains `seed_derivation`: its versioned `algorithm`, authored
`master_seed`, and deterministic `requests` array. Each entry stores `scope`,
`purpose`, the actual `seed`, and `member_identity` for member-scoped requests.
Every recording contains shared requests plus only those belonging to that
recording's member.
The `state` provenance value is the explicit semantic key from
`study.json.paths.states` when the task selected a project schema. When the
task omitted `state`, it is instead the stable ID of the unit's validated
`StateSchemaProvider`. Persistence does not distinguish their storage behavior;
both are already-resolved Study facts.
## Advanced API
The module root exposes only completed-recording readers, payload decoder
contracts, operational timing, and `PersistenceError`. It exposes no plan or
write construction.
### `StoredStateSeriesReader`
`StoredStateSeriesReader::open_completed_recording(root: &Path, decoders)`
consumes a `JsonPayloadDecoderRegistry`, reads `metadata.json`, validates the
format and successful terminal status, and retains one immutable metadata
snapshot. The reader is intentionally non-`Clone` because custom decoders may
not have meaningful clone semantics.
This reader opens only completed member recording directories. It does not
interpret program workspaces, `program.json`, logs, or arbitrary artifacts;
workspace results are ordinary files discovered from
`TaskRunSummary::output_directory()`; configured external destinations are
interpreted by the program that owns them.
Inspection and reconstruction methods:
- `recording_directory() -> &Path` returns the retained typed path;
- `stream_names()` iterates logical streams in metadata order;
- `format_version()` returns the validated wire-format version;
- `user_metadata()` borrows creation-time execution unit constants and Workflow
provenance, including stable execution-unit member identity/index and any
applicable actual seed derivations;
- `terminal_metadata()` borrows completion-time metadata. A structured
execution-unit completion reason appears as `completion_reason`; successful
Workflow 0.14 recordings also include the final `compute` allocation
history;
- `recording_timing() -> &RecordingTiming` returns verified host timing;
- `stream_record_count(stream)` and `stream_encoded_bytes(stream)` compute
checked metadata aggregates;
- `read_stream_as_state_series(stream)` verifies and reconstructs one complete
ordered `StateSeries`;
- `read_all_streams_as_state_series()` reconstructs every stream in metadata
order and returns no partial vector; and
- `read_latest_state_from_stream(stream)` verifies the newest chunk's complete
framing, checksum, record count, positional widths, iteration order, and
descriptor boundaries before reconstructing its final state.
Reads verify metadata invariants, declared file sizes, SHA-256 checksums, JSONL
framing, record counts, iteration ordering, schema shape, decoder coverage,
payload conversion, and StateSeries invariants. They perform synchronous
filesystem IO and allocate owned payloads, but start no worker and never mutate
the recording. Any failure returns no partial state/series.
On the private write side, failure to encode or admit the initial or terminal
execution unit observation triggers a best-effort transition from `running` to `failed`
before the original observation/persistence error is returned. Accepted data
is drained first; an inability to publish failed metadata never replaces the
authoritative triggering error.
### `RecordingTiming`
`RecordingTiming` is `Clone + Debug + Eq` operational provenance acquired
from a verified reader:
- `created_at_utc()` and `finalized_at_utc()` borrow RFC 3339 UTC strings;
- `active_duration()` returns the persisted duration as `Duration`.
Timing is host execution metadata, not scientific `StateTime`.
### Payload decoder contracts
`JsonPayloadDecoder<T>: Send + Sync + 'static` converts one borrowed complete
raw JSON value into an owned `T`. Its associated `Error` must implement
`Error + Send + Sync + 'static`. Compatible closures implement the trait.
The reader adds stream, iteration, and field context around decoder failures.
`JsonPayloadDecoderRegistry` owns at most one decoder per exact field name:
- `new()` and `with_capacity(capacity)` create empty registries;
- `with_json_field::<T>(field)` consumes and returns the registry with a
Serde-based decoder;
- `register_for_field::<T, D>(field, decoder)` mutates the registry with a
custom decoder;
- `len()`, `is_empty()`, and `has_decoder_for_field(field)` inspect it;
and
- `registered_field_names()` iterates keys in unspecified hash-map order.
Field keys must be nonempty and unique. A selected stream requires decoders for
all of its fields; unrelated extra registrations are allowed. Use
`with_json_field::<T>` for ordinary Serde payloads, including `String` and
`Vec<f64>`; named decoder types are needed only for custom conversion behavior.
### `PersistenceError`
`PersistenceError` is non-exhaustive and owns its paths and contextual names.
Its complete current variant set is:
- declaration/lifecycle: `Observation`, `RecordingDirectoryExists`,
`InvalidConfiguration`, `DuplicateStateStream`, `UnknownStateStream`,
`StateWriterClosed`, `RecordingFinished`, `RecordingDirectoryInUse`, and
`NoRecordedState`;
- operational metadata: `OperationalTimestamp`,
`OperationalDurationOverflow`, `UnsupportedVersion`, `InvalidMetadata`, and
`RecordingNotComplete`;
- integrity/framing: `MissingChunk`, `ChunkSizeMismatch`,
`ChecksumMismatch`, and `InvalidRecord`;
- decoding/state assembly: `DuplicateDecoder`, `MissingDecoder`,
`DecodeField`, and `StateSeriesInvariant`;
- filesystem/serialization/accounting: `Io`, `Json`, `ByteCountOverflow`,
`RecordTooLarge`, and `OutOfOrderIteration`; and
- worker lifecycle: `WriterQueueDisconnected`, `StateWriterTerminated`, and
`StateWriterPanicked`.
Reader code normally observes only the format, integrity, decoding, and
filesystem families. The same enum retains exact private write-path failures
so Runtime can preserve their source chains through `RuntimeError`; those
variants do not authorize application write control. Variants with a `source`
preserve observation, timestamp, IO, JSON, decoder, StateSeries, or shared
worker errors.
## Example
Ordinary persistence is automatic:
```rust,no_run
fn main() -> Result<(), scientific_workflow::WorkflowError> {
scientific_workflow::run(std::path::Path::new("."))
}
```
An analysis process can reconstruct a completed stream:
```rust,no_run
use std::path::Path;
use scientific_workflow::persistence::{
JsonPayloadDecoderRegistry, StoredStateSeriesReader,
};
# fn read() -> Result<(), Box<dyn std::error::Error>> {
let decoders = JsonPayloadDecoderRegistry::new()
.with_json_field::<Vec<f64>>("position")?;
let reader = StoredStateSeriesReader::open_completed_recording(
Path::new("output/execution-123-0/replicate-000000/task-000000"),
decoders,
)?;
let trajectory = reader.read_stream_as_state_series("trajectory")?;
println!("{}", trajectory.len());
# Ok(())
# }
```
The example path is discovered from the `TaskRunKind::ExecutionUnit` variant's
`members` in production; it is not supplied to execution-unit or Study code.
### Crate-visible write peer API
The automatic write path is a named closed contract through
the persistence module root:
- `PersistencePlan` carries the already-validated effective nonzero chunk and
queue byte limits.
- `MemberRecordingProvenance` owns semantic execution unit facts supplied by Runtime. It
does not accept an arbitrary metadata map; Persistence alone constructs the
exact `constants`, resolved-project `parameters`, `workflow`, backend, and
effective-setting JSON.
Runtime derives one member-specific value with a stable index and identity
before opening each recording. Every retained path is exact UTF-8 already guaranteed by Config preflight;
Persistence never substitutes replacement characters in provenance.
- `PersistenceSession` owns member-recording start, bounded observation
submission, successful completion, and best-effort failure terminalization.
- `ProgramLaunch` and `ProgramPersistenceSession` own external-program launcher
provenance, frozen config/dependency files, logs, artifacts, and terminal
status.
Observation supplies canonical owned `EncodedObservation` JSON bytes because
the mutable scientific state need not be `Sync` and cannot remain borrowed by
the asynchronous writer. Persistence consumes those bytes and exclusively owns
queueing, JSONL framing, chunks, checksums, filesystem publication, and durable
lifecycle. When reading, it reconstructs State schemas directly from decoded
ordered metadata through State's peer port; it does not serialize fields and
reparse them as JSON.
## Not API
Filesystem capacity sampling and directory leases use synchronous `fs4`.
Lock contention remains a distinct failure; leases explicitly unlock on drop.
Backend selection, `SystemStateWriter`,
stream storage/layout values, queue worker, chunk
publisher, metadata mutation, directory synchronization, directory lease,
filenames, and atomic temporary files are private. There is one internal
constructor consuming Study's
already-bound observation plan, provenance, destination, and shared storage
policy. There is no builder, resume/continuation API, per-stream storage
override, explicit flush, or public completion result.
`PersistencePlan`, `MemberRecordingProvenance`, `PersistenceSession`,
`ProgramPersistenceSession`, and `ProgramLaunch` are crate-visible peer API;
their backing layout and local mechanics remain replaceable. None is a
downstream writer API.
Future local or remote adapters belong behind the private session boundary; adding
one must not broaden the execution unit/task API. A replacement backend must preserve
observation order, bounded backpressure, program/Python input/log/status and
launcher-provenance capture,
failure evidence, terminal metadata, effective-setting provenance, and the
verified reader contract. A backend that emits v7 MUST satisfy the normative
repository protocol; an incompatible layout or semantic change MUST allocate a
new recording-format version and follow its coordinated bump checklist.
## Format compatibility
Readers accept formats 7 and 8. Writers retain format 7 for periodic streams and
use format 8 for initial-and-final sampling; see the repository format-8 protocol.
All framing, integrity, and ownership contracts remain unchanged.
Program logs remain Persistence-owned files; Runtime drains child pipes into them
and treats read/write/flush failures as fatal. Process-tree cleanup and pipe-reader
joins precede resource-lease release. Scientific integrity and record publication
remain Persistence-owned. File timestamp/durability metadata measures actual
wall time; paused execution budgets are separately owned by Runtime.
## Completed task reuse
Runtime's private `reuse` subsystem owns atomic current v2 completed-task
receipts. Persistence's private `TaskInputSnapshots` mechanism owns uniform
task-level config/dependency files and checksum evidence. Runtime supplies
semantic task identities and workload results only after phase success.
Receipts preserve original output paths and checksum references when a task is
reused; they do not copy scientific artifacts or reopen writers. Import verifies
both source snapshot files, compares scientific inputs separately from operational
settings, validates successful v2 program status, and uses
`StoredStateSeriesReader::open_completed_recording` to check member completion and
metadata provenance. Ordinary readers verify raw chunks on consumption. NPY reuse
fully verifies current v3 batches through the coordinated Python reader. Older,
missing, or unsupported receipts fail; there is no historical import adapter.
Only when the imported phase is neither `$npy` nor a transitive consumer may
comparison omit `study.phases.$npy.exclude_streams`. Scientific parameters,
schemas, seeds, ordinary executable/scientific-script paths, arguments, replicate
count, phase dependencies, and member provenance still must match. Allocation,
scheduling, timeouts, buffering, disk policy, and Python launcher/environment
settings remain operational provenance. Snapshot checksum verification is always
exact, even where parsed compatibility omits operational values.
## JSON lifecycle guarantees
Source configuration is captured once and source edits affect subsequent runs.
Every task records `workflow-config.json` and `workflow-dependencies.json`
at its task root. Program sessions write them before launch; execution units
write them when the first member recording starts, before steps and completion.
`workflow-inputs.json` has strict format `scientific-workflow-inputs.v1` and
`config`/`dependencies` descriptors of the form
`{"path":"workflow-config.json","checksum":"sha256:<64 lowercase hex>"}`.
The dependency descriptor uses `workflow-dependencies.json`. Descriptors permit
only these exact filenames, and reject malformed checksums/unknown fields.
Program-v2 metadata and task-result-v2 receipts require the same object under
`inputs`; receipts no longer embed an independent parsed snapshot authority.
`TaskInputSnapshots` retains creation-time descriptors in memory, checks them
against the durable sidecar, and verifies both files before completion. Program
monitoring also checks them during execution. Supported snapshot reads and reuse
verify bytes and consistency with current program/receipt references when present;
missing files, old metadata, or mismatched evidence fail. Authored project JSON
may change for subsequent runs and is never overwritten by these mechanisms.
This adds task sidecars, not raw metadata structural keys: recordings remain v7/v8.
Runtime control JSON is mutable IPC.
Active recording/program metadata may advance to one terminal state, which the
writer cannot subsequently replace. Completed task receipts and NPY batch
manifests use publication that refuses replacement. A verified matching NPY
batch is returned without changing its manifest; conflicting inputs or corruption
require a new output directory. These guarantees do not prevent external file
modification; input monitoring detects changes present at a check.