# Runtime API
This guide documents the `scientific-workflow` 0.15.0 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.
Runtime gives each working execution-unit task a private Rayon pool governed
by required top-level `study.json.compute.mode`. In `auto`, the coordinator
divides `study.json.threads` as equally as possible among registered working
tasks; pending tasks receive no allocation. Starts and finishes request a
rebalance, active initialization/step calls finish, and new pools are installed
before the next call. Each registering task waits for its requested allocation
epoch, not for a later coincidental globally idle instant; once that epoch is
committed, already-running tasks may resume without starving the newcomer.
Stable replicate/task order receives any indivisible remainder. In `isolated`,
each task keeps its authored `resources.threads` pool. Dedicated pools prevent
one long-lived ensemble from occupying another ensemble's workers. Ambient
`RAYON_NUM_THREADS` does not override either mode.
The global count also initializes one process-wide permit budget shared by all
replicate schedulers. Auto mode admits at most one execution-unit task per
global thread; isolated tasks are admitted only while their fixed allocations
fit. External tasks reserve their configured thread count; `$npy` reserves
`min(phase.threads, study.threads, deduplicated recording count)`. External work and
in-process execution-unit work do not overlap, keeping 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 requires terminal stdin and stderr before Runtime may
create or clean output. Noninteractive launches return `RuntimeError::Presentation`
with instructions to use `screen` or `tmux`. Study contains no UI policy.
After output creation, UI starts the required Ratatui dashboard and live
`<execution>/log.txt`; renderer initialization/input/drawing and log failures
are fatal presentation errors. There is no headless or plain renderer and no
`terminal-ui` feature switch. Loading a Study or reading recordings remains
independent of execution and needs no terminal.
Typing `exit` while work is active or pressing Ctrl+C requests cooperative
cancellation. After any terminal outcome the dashboard remains visible until
the user types `exit`; Ctrl+C alone never closes it. Execution returns only
after cleanup and that explicit exit. Disk pauses require typing `resume`
after the recovery threshold is reached; the dashboard displays reminders.
An execution blocks until all admitted work has stopped and all successful
persistence sessions have durably completed. ExecutionUnit cancellation is cooperative
between steps, so blocking application code inside one step may delay return.
External programs, including Python interpreters/environment managers, are
polled and own Linux process groups which are terminated, killed after bounded escalation,
and reaped when cancellation or timeout is observed. Pipe readers are joined
before resource permits are released. Future macOS/Windows implementations require
separate qualification; Linux is the only supported platform.
Failure does not overwrite prior output. Execution that fails after output creation
retains its unique directory and any failed/running recording evidence for
diagnosis. The crate-level facade wraps an active `RuntimeError` in
`WorkflowError::Runtime`; the complete-workflow composition is documented by
`WorkflowError`.
## Advanced API
### `runtime::execute`
`execute(study: Study) -> Result<RunSummary, RuntimeError>` consumes one
clone-cheap immutable Study. It is Runtime's sole execution entry and cannot
accept a project root, manifest, execution unit catalog, or unresolved declarations.
It is the supported embedding seam for callers that loaded and optionally
inspected a Study first.
It performs the same output-producing work reached through the crate facade.
It never mutates the supplied
declaration; consuming the handle simply makes accidental double execution
less likely at the call site. A caller may explicitly clone Study before the
call when multiple independent runs are intended.
Replicates run sequentially or concurrently according to `ReplicatePolicy`.
Every replicate gets `replicate-XXXXXX` beneath the unique execution scope.
Parallel fail-fast observes replicate completion as it occurs: the first
reported failure requests cancellation of still-running sibling replicates,
and Runtime waits for their cleanup before returning that originating error.
Parallel finish-all never performs this policy cancellation and collects every
terminal outcome before returning the first observed failure. Successful
summary order remains independent of worker completion order.
Phases run in stable topological order. Within a phase, runtime respects
`max_concurrency`, the minimum `start_interval` between successive admissions,
the global resource budget, task timeout, phase timeout, and sibling failure
policy. A resource-blocked task remains pending and is not reported as started.
The first eligible
task has no artificial pre-admission wait. Fail-fast stops further admission
and requests cancellation of active siblings; finish-all continues admitting
declared siblings and returns an error after they finish.
Task/phase deadlines and admission delays use one Runtime-owned pause-aware
clock. It freezes immediately on pause request, including while an in-flight
call or arbitrary program is still running. Resume never charges that paused time.
Task deadline classification uses the worker's completion timestamp, rather
than the later instant at which the polling scheduler joins it. A task that
completed before its deadline is therefore not retroactively timed out. Phase
deadlines likewise apply only while pending or unfinished work remains.
An interactive `exit` submitted during execution stops further admission,
cancels active execution unit/program workers, waits for their cleanup, restores the
terminal, and returns `RuntimeError::ExecutionCancelled`. Ctrl+C performs the
cancellation but leaves the completed dashboard open until the required `exit`
command. If execution has already reached a successful or failed terminal outcome,
`exit` only closes the interface and does not change that outcome.
### `runtime::RunSummary`
Returned only after complete success. It is cloneable and owns paths/summaries.
- `output_directory() -> &Path` returns the unique generated execution path.
- `replicates() -> &[ReplicateRunSummary]` returns ascending replicate order.
The summary performs no IO and does not keep recording files open.
### `runtime::ReplicateRunSummary`
- `index() -> u64`: zero-based replicate index;
- `output_directory() -> &Path`: isolated replicate directory; and
- `phases() -> &[PhaseRunSummary]`: successful phases in dependency execution
order.
Parallel worker completion order is never exposed; summaries are sorted by
index.
### `runtime::PhaseRunSummary`
- `was_reused() -> bool`: true when this phase imported completed outputs without executing its tasks.
- `name() -> &str`: stable manifest phase key;
- `tasks() -> &[TaskRunSummary]`: successful tasks restored to deterministic
Study plan order, independent of concurrent completion order.
### `runtime::TaskRunKind`
`TaskRunKind` is a non-exhaustive data-bearing enum. `ExecutionUnit` contains
the registration key and stable `Box<[MemberRunSummary]>`; `Program` contains
the resolved launcher executable and optional canonical Python script; and
`Npy` contains the Python launcher used by Workflow's reserved converter and
the standard execution-level processed-data directory.
Callers matching it must retain a fallback for future workload kinds.
### `runtime::TaskRunSummary`
- `identity() -> &str`: Study-inferred task identity;
- `kind() -> &TaskRunKind`: borrows the variant-specific result; and
- `output_directory() -> &Path`: task output root or program workspace. For a
single-member unit this is also the recording directory; every recording
path is available from the execution-unit variant's `members`.
Summary paths are owned. The enum prevents irrelevant or contradictory fields.
A task-level final iteration is intentionally absent because members can finish
at different iterations; callers can compute a maximum when meaningful.
Summary values do not authorize append/resume and carry no live task, process,
execution unit, or state.
Summaries and `RuntimeError` are `Send + Sync`.
### `runtime::MemberRunSummary`
One immutable per-member result owned by its task summary:
- `identity() -> &str` returns the stable identity supplied through
`MemberView`;
- `final_iteration() -> u64` returns that member's terminal iteration; and
- `output_directory() -> &Path` returns that member's completed recording.
For a multi-member unit, directories are
`<task-output>/members/member-<index>` in stable member order. The identity is
metadata, not a filesystem fragment, so application identities cannot redirect
persistence. Summary borrows are tied to the owning summary and perform no IO.
### External program and Python contract
Runtime starts a resolved executable directly, without a shell, inside its
private `artifacts/` directory. Standard input is closed. Standard output and
error are captured as `stdout.log` and `stderr.log`. Runtime supplies absolute
paths through:
- `WORKFLOW_CONFIG_PATH`: immutable `workflow-config.json`, containing the
captured `study` value and all `wf_configs/` JSON documents, with global
parameter selections resolved for this task;
- `WORKFLOW_DEPENDENCIES_PATH`: immutable `workflow-dependencies.json`, with
completed task summaries from declared dependency phases, filtered to this
task's resolved global configuration;
- `WORKFLOW_PROJECT_ROOT`: canonical project root;
- `WORKFLOW_EXECUTION_ROOT`: unique execution directory;
- `WORKFLOW_REPLICATE_ROOT`: current replicate directory; and
- `WORKFLOW_TASK_OUTPUT`: the task's `artifacts/` directory, also its working
directory;
- `WORKFLOW_NPY_OUTPUT`: present only for `$npy` and naming the standard
`<execution>/processed/replicate-NNNNNN` destination;
- `WORKFLOW_THREADS`: decimal positive thread count reserved for this external
task (one when `resources` is omitted);
- `RAYON_NUM_THREADS`: the same task reservation for Rayon-based child
programs; and
- `WORKFLOW_TASK_SEED`: decimal unsigned 64-bit task seed, present only when
the program/Python task declared `seed: {"purpose":"..."}`.
Programs may read any central configuration keys they understand. The supplied
workspace is their default location for temporary or task-scoped artifacts,
but an external program owns its domain-specific IO and may resolve a
project-relative destination from `wf_configs/parameters.json`. For example, the bundled
Python plotter writes directly to the configured `output/plots`. Rust
Persistence does not relocate or publish those Python-owned files. A Study uses
its captured snapshot: editing JSON after `Study::load` cannot alter these
files.
On completion Runtime writes terminal `program.json`; nonzero exit status is a
task failure. A seeded program's metadata records its purpose and actual
derived seed even when the child fails. Dependency JSON is deterministic. Each task contains `identity`,
`output_directory`, and one `workload` object. An execution-unit workload
contains its kind, registration key, and member identity/iteration/recording
summaries. A program workload contains `kind` (`program` or `python`), its
launcher executable, and the optional canonical Python script. Dependency JSON
remains a data handoff, not a shell command protocol.
A reserved `$npy` task receives the complete transitive prerequisite phase
graph across all inferred global configurations in its replicate. It converts
every field in every unique execution-unit member recording to manifest-directed,
C-contiguous `.npy` data at `<execution>/processed/replicate-NNNNNN` and writes
a batch manifest there. Numeric fields map directly or use ragged components;
structured fields retain lossless JSON-byte fallback data and nested numeric
projections. No representation uses object dtype or pickle.
Its dependency workload kind is `npy` and includes `processed_directory`, so a
downstream task never reconstructs the path. Ordinary dependency snapshots
remain direct and configuration-correlated; the aggregate `$npy` summary is
visible to every downstream configuration.
A nested Python task follows this exact runtime contract after Config lowers
its environment to one invocation. Runtime has no Python-specific scheduler,
active-environment lookup, package installer, or import-path mutation. The
script reads the same `WORKFLOW_*` files/paths as any program. It may use
`WORKFLOW_TASK_OUTPUT` or a validated destination from its project parameters.
Its `.py` file need not be executable. The selected
manager/interpreter, manager arguments, canonical script, and script arguments
are fixed before output creation.
### `runtime::RuntimeError`
This non-exhaustive enum reports failures after a valid Study is available:
- `Reuse { phase: String, path: PathBuf, reason: String }`: required completed outputs are missing, failed, or incompatible; detected before output creation.
- `PythonPrerequisite { interpreter: PathBuf, reason: String }`: the active
interpreter cannot import the coordinated Python 0.5.0 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.
- `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,
compute-pool allocation, 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
Filesystem capacity sampling and directory leases use synchronous `fs4`.
Lock contention remains a distinct failure; leases explicitly unlock on drop.
Scheduler polling, worker thread names, active task handles, atomic cancellation
flags, completion channels/timestamps, bounded panic-payload formatting,
task output ordinals, the compute coordinator/leases/rebalancing barrier,
task-private Rayon pool construction, `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;
`workflow.compute` records the selected mode and creation-time allocation
history, while terminal metadata records the complete allocation history as
ordered `{epoch, threads}` entries;
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 through the shared resource coordinator and the
task's lifetime lease; concurrent replicates
cannot each independently consume the study ceiling. NumPy native pools are
limited to one thread per worker. The optional `$npy.threads` limit and `$npy.mode` policy are described below.
### 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.
Runtime admits only execution-unit tasks whose effective selection is active:
both their phase and their optional task-level `active` flag must be active.
Inactive units retain compiled identity but create no task output and are not
reuse candidates. A selected phase containing only inactive units completes
successfully with an empty task summary.
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.
## Ensemble progress and filtered conversion
Runtime reports the maximum current member iteration and maximum declared target,
not summed member-work. If any target is unknown, the task target stays unknown.
For a lockstep ensemble, twelve members at 100 of 36000 steps report 100/36000.
Early-completed members do not hold back the clock. Completion events already
use the maximum final member iteration. ETA uses this same task clock; member
recordings and completion policies are unchanged.
The reserved `$npy` phase passes exact stream exclusions as repeated
`--exclude-stream=NAME` arguments to Python 0.5.0. Filtering affects conversion
only. All included data retains ordinary validation, locking, cancellation,
worker limits, and atomic publication. Filter identity is checked before reusing
member outputs or an existing batch; different filters never silently reuse data.
## JSON lifecycle guarantees
Source configuration is captured once and source edits affect subsequent runs.
Generated `workflow-config.json` and `workflow-dependencies.json` are checked
against their captured byte digests during execution and before program success;
a changed or missing file fails the task. 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.
## 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.