use std::collections::{BTreeMap, HashSet};
use std::num::{NonZeroU64, NonZeroUsize};
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::Deserialize;
use serde_json::{Map, Value};
use super::document::child_pointer;
use super::error::ConfigError;
use super::python::PythonTaskDeclaration;
pub(crate) const WORKFLOW_SCHEMA_VERSION: u64 = 1;
pub(crate) const NPY_PHASE_NAME: &str = "$npy";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ComputeMode {
Auto,
Isolated,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ReplicatePolicy {
count: u64,
scheduling: ReplicateScheduling,
failure_policy: FailurePolicy,
}
impl ReplicatePolicy {
pub(crate) const fn count(self) -> u64 {
self.count
}
pub(crate) const fn scheduling(self) -> ReplicateScheduling {
self.scheduling
}
pub(crate) const fn failure_policy(self) -> FailurePolicy {
self.failure_policy
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ReplicateScheduling {
Sequential,
Parallel,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum FailurePolicy {
FailFast,
FinishAll,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StudyManifest {
disk_pause_at: Option<f64>,
workflow_schema: u64,
active_phases: Box<[usize]>,
reuse_from: Option<PathBuf>,
threads: usize,
compute_mode: ComputeMode,
master_seed: Option<u64>,
replicates: ReplicatePolicy,
persistence: PersistenceSpecification,
}
impl StudyManifest {
pub(crate) const fn disk_pause_at(&self) -> Option<f64> {
self.disk_pause_at
}
pub(crate) fn active_phases(&self) -> &[usize] {
&self.active_phases
}
pub(crate) fn reuse_from(&self) -> Option<&Path> {
self.reuse_from.as_deref()
}
pub(crate) const fn workflow_schema(&self) -> u64 {
self.workflow_schema
}
pub(crate) const fn threads(&self) -> usize {
self.threads
}
pub(crate) const fn compute_mode(&self) -> ComputeMode {
self.compute_mode
}
pub(crate) const fn master_seed(&self) -> Option<u64> {
self.master_seed
}
pub(crate) const fn replicate_policy(&self) -> ReplicatePolicy {
self.replicates
}
pub(crate) const fn persistence(&self) -> PersistenceSpecification {
self.persistence
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct PersistenceSpecification {
chunk_target_bytes: NonZeroU64,
queue_capacity_bytes: NonZeroU64,
}
impl PersistenceSpecification {
pub(crate) const fn chunk_target_bytes(self) -> NonZeroU64 {
self.chunk_target_bytes
}
pub(crate) const fn queue_capacity_bytes(self) -> NonZeroU64 {
self.queue_capacity_bytes
}
}
pub(crate) struct ParsedManifest {
pub(crate) manifest: StudyManifest,
pub(crate) state_paths: BTreeMap<Box<str>, PathBuf>,
pub(crate) phases: Vec<ParsedPhase>,
}
#[derive(Clone)]
pub(crate) struct ParsedPhase {
pub(crate) auto_name_prefix: Option<Box<str>>,
pub(crate) name: Box<str>,
pub(crate) dependencies: Box<[Box<str>]>,
pub(crate) tasks: Vec<ParsedTask>,
pub(crate) max_concurrency: usize,
pub(crate) start_interval: Duration,
pub(crate) timeout: Option<Duration>,
pub(crate) failure_policy: FailurePolicy,
}
#[derive(Clone)]
pub(crate) enum ParsedTask {
ExecutionUnit {
execution_unit: Box<str>,
active: bool,
state: Option<Box<str>>,
timeout: Option<Duration>,
threads: Option<usize>,
},
Program {
program: PathBuf,
args: Box<[Box<str>]>,
seed_purpose: Option<Box<str>>,
timeout: Option<Duration>,
threads: usize,
},
Python {
declaration: PythonTaskDeclaration,
seed_purpose: Option<Box<str>>,
timeout: Option<Duration>,
threads: usize,
},
Npy {
exclude_streams: Box<[Box<str>]>,
threads: usize,
auto: bool,
},
}
pub(crate) fn parse(path: &Path, value: Value) -> Result<ParsedManifest, ConfigError> {
let raw: RawStudy = serde_json::from_value(value)
.map_err(|error| ConfigError::invalid(path, "/", error.to_string()))?;
if raw.workflow_schema != WORKFLOW_SCHEMA_VERSION {
return Err(ConfigError::invalid(
path,
"/workflow_schema",
format!(
"unsupported Workflow configuration schema {}; this release requires schema {}",
raw.workflow_schema, WORKFLOW_SCHEMA_VERSION
),
));
}
if raw.phases.is_empty() {
return Err(ConfigError::invalid(
path,
"/phases",
"at least one phase must be declared",
));
}
let active_phases = raw
.active_phases
.unwrap_or_else(|| (0..raw.phases.len()).collect());
let mut selected = HashSet::new();
for &index in &active_phases {
if index >= raw.phases.len() || !selected.insert(index) {
return Err(ConfigError::invalid(
path,
"/active_phases",
"phase indices must be distinct zero-based integers smaller than the phase count",
));
}
}
let reuse_from = raw
.reuse_from
.map(|authored| {
if authored.as_os_str().is_empty() {
return Err(ConfigError::invalid(
path,
"/reuse_from",
"source execution must be nonempty",
));
}
let source = if authored.is_absolute() {
authored
} else {
path.parent()
.and_then(Path::parent)
.expect("study.json is inside wf_configs")
.join(authored)
};
let source = std::fs::canonicalize(&source)
.map_err(|error| ConfigError::invalid(path, "/reuse_from", error.to_string()))?;
if !source.is_dir() || source.to_str().is_none() {
return Err(ConfigError::invalid(
path,
"/reuse_from",
"source must be a UTF-8 execution directory",
));
}
Ok(source)
})
.transpose()?;
if raw.threads == 0 {
return Err(ConfigError::invalid(
path,
"/threads",
"study thread count must be positive",
));
}
if raw.replicates.count == 0 {
return Err(ConfigError::invalid(
path,
"/replicates/count",
"replicate count must be positive",
));
}
let chunk_target_bytes = megabytes_to_bytes(
path,
"/persistence/chunk_target_mb",
raw.persistence.chunk_target_mb,
)?;
let queue_capacity_bytes = megabytes_to_bytes(
path,
"/persistence/queue_capacity_mb",
raw.persistence.queue_capacity_mb,
)?;
if raw
.disk
.pause_at_percent
.is_some_and(|value| !value.is_finite() || value <= 0.0 || value > 100.0)
{
return Err(ConfigError::invalid(
path,
"/disk/pause_at_percent",
"disk pause threshold must be greater than 0 and at most 100, or null to bypass",
));
}
let manifest = StudyManifest {
disk_pause_at: raw.disk.pause_at_percent,
workflow_schema: raw.workflow_schema,
active_phases: active_phases.into_boxed_slice(),
reuse_from,
threads: raw.threads,
compute_mode: raw.compute.mode.into(),
master_seed: raw.seed,
replicates: ReplicatePolicy {
count: raw.replicates.count,
scheduling: raw.replicates.scheduling.into(),
failure_policy: raw.replicates.failure_policy.into(),
},
persistence: PersistenceSpecification {
chunk_target_bytes,
queue_capacity_bytes,
},
};
let mut state_paths = BTreeMap::new();
for (name, state_path) in raw.paths.states {
let pointer = child_pointer("/paths/states", &name);
validate_identifier(path, &pointer, &name, "state")?;
if state_path.as_os_str().is_empty() {
return Err(ConfigError::invalid(
path,
&pointer,
"state schema path must be nonempty",
));
}
if state_path.is_absolute() {
return Err(ConfigError::invalid(
path,
&pointer,
"state schema path must be relative to the project root",
));
}
if state_path.extension().and_then(std::ffi::OsStr::to_str) != Some("json") {
return Err(ConfigError::invalid(
path,
pointer,
"state schema path must use the `.json` extension",
));
}
state_paths.insert(name.into_boxed_str(), state_path);
}
let declared_names = raw.phases.keys().cloned().collect::<HashSet<_>>();
let mut phases = Vec::with_capacity(raw.phases.len());
for (name, value) in raw.phases {
let phase_pointer = child_pointer("/phases", &name);
validate_identifier(path, &phase_pointer, &name, "phase")?;
let exclusions_authored = value.get("exclude_streams").is_some();
let npy_resources_authored = value.get("threads").is_some() || value.get("mode").is_some();
let raw: RawPhase = serde_json::from_value(value)
.map_err(|error| ConfigError::invalid(path, &phase_pointer, error.to_string()))?;
let npy_phase = name == NPY_PHASE_NAME;
if npy_resources_authored && !npy_phase {
return Err(ConfigError::invalid(
path,
&phase_pointer,
"phase threads and mode are valid only on `$npy`",
));
}
let npy_threads = raw.threads.map_or(manifest.threads(), NonZeroUsize::get);
if npy_threads > manifest.threads() {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/threads"),
"NPY thread limit must not exceed study threads",
));
}
if exclusions_authored && !npy_phase {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/exclude_streams"),
"exclude_streams is valid only on the reserved `$npy` phase",
));
}
let mut excluded = HashSet::new();
for stream in &raw.exclude_streams {
validate_identifier(
path,
&format!("{phase_pointer}/exclude_streams"),
stream,
"excluded stream",
)?;
if !excluded.insert(stream) {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/exclude_streams"),
"excluded stream names must be distinct",
));
}
}
if !npy_phase && raw.tasks.is_empty() {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/tasks"),
"a phase must declare at least one task",
));
}
if npy_phase && !raw.tasks.is_empty() {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/tasks"),
"the reserved `$npy` phase synthesizes its task and must not declare `tasks`",
));
}
if npy_phase && raw.after.is_empty() {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/after"),
"the reserved `$npy` phase requires at least one prerequisite phase",
));
}
if raw.max_concurrency == 0 {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/max_concurrency"),
"maximum concurrency must be positive",
));
}
let mut dependencies = Vec::with_capacity(raw.after.len());
let mut seen_dependencies = HashSet::with_capacity(raw.after.len());
for dependency in raw.after {
validate_identifier(
path,
&format!("{phase_pointer}/after"),
&dependency,
"phase dependency",
)?;
if dependency == name {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/after"),
"a phase cannot depend on itself",
));
}
if !declared_names.contains(&dependency) {
return Err(ConfigError::UnknownDependency {
phase: name.clone(),
dependency,
});
}
if !seen_dependencies.insert(dependency.clone()) {
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/after"),
format!("dependency `{dependency}` is repeated"),
));
}
dependencies.push(dependency.into_boxed_str());
}
let mut tasks = Vec::with_capacity(raw.tasks.len());
for (index, task) in raw.tasks.into_iter().enumerate() {
let pointer = format!("{phase_pointer}/tasks/{index}");
let timeout = task.timeout_ms.map(Duration::from_millis);
let requested_threads = task
.resources
.as_ref()
.map_or(1, |resources| resources.threads.get());
let seed_purpose = task
.seed
.map(|seed| {
validate_identifier(
path,
&format!("{pointer}/seed/purpose"),
&seed.purpose,
"seed purpose",
)?;
if manifest.master_seed().is_none() {
return Err(ConfigError::invalid(
path,
format!("{pointer}/seed"),
"a program seed request requires top-level `seed`",
));
}
Ok(seed.purpose.into_boxed_str())
})
.transpose()?;
match (task.execution_unit, task.program, task.python) {
(Some(execution_unit), None, None)
if task.args.is_empty() && seed_purpose.is_none() =>
{
validate_identifier(
path,
&format!("{pointer}/execution_unit"),
&execution_unit,
"execution unit",
)?;
if let Some(state) = task.state.as_deref() {
validate_identifier(path, &format!("{pointer}/state"), state, "state")?;
}
let threads = task.resources.map(|resources| resources.threads.get());
match manifest.compute_mode() {
ComputeMode::Auto if threads.is_some() => {
return Err(ConfigError::invalid(
path,
format!("{pointer}/resources"),
"automatic compute allocation does not accept a fixed task thread count",
));
}
ComputeMode::Isolated if threads.is_none() => {
return Err(ConfigError::invalid(
path,
format!("{pointer}/resources"),
"isolated compute allocation requires resources.threads on every execution-unit task",
));
}
ComputeMode::Isolated => validate_task_threads(
path,
&pointer,
threads.expect("checked isolated allocation"),
manifest.threads(),
)?,
ComputeMode::Auto => {}
}
tasks.push(ParsedTask::ExecutionUnit {
execution_unit: execution_unit.into_boxed_str(),
active: task.active.unwrap_or(true),
state: task.state.map(String::into_boxed_str),
timeout,
threads,
});
}
(None, Some(program), None) if task.state.is_none() && task.active.is_none() => {
validate_task_threads(path, &pointer, requested_threads, manifest.threads())?;
if program.as_os_str().is_empty() {
return Err(ConfigError::invalid(
path,
format!("{pointer}/program"),
"program path must be nonempty",
));
}
tasks.push(ParsedTask::Program {
program,
args: task.args.into_iter().map(String::into_boxed_str).collect(),
seed_purpose,
timeout,
threads: requested_threads,
});
}
(None, None, Some(declaration))
if task.state.is_none() && task.args.is_empty() && task.active.is_none() =>
{
validate_task_threads(path, &pointer, requested_threads, manifest.threads())?;
tasks.push(ParsedTask::Python {
declaration,
seed_purpose,
timeout,
threads: requested_threads,
});
}
_ => {
return Err(ConfigError::invalid(
path,
pointer,
"a task must declare exactly `execution_unit`, `program`, or `python`; optional `active` and `state` are valid only for an execution unit, top-level `args` only for a program, and `seed` only for a program or Python task",
));
}
}
}
if npy_phase {
tasks.push(ParsedTask::Npy {
threads: npy_threads,
auto: matches!(raw.mode, RawNpyMode::Auto),
exclude_streams: raw
.exclude_streams
.into_iter()
.map(String::into_boxed_str)
.collect(),
});
}
if let Some(naming) = &raw.task_names
&& naming.prefix.chars().any(char::is_control)
{
return Err(ConfigError::invalid(
path,
format!("{phase_pointer}/task_names/prefix"),
"task name prefix must not contain control characters",
));
}
phases.push(ParsedPhase {
auto_name_prefix: raw.task_names.map(|naming| {
let RawTaskNameMode::Auto = naming.mode;
naming.prefix.trim().into()
}),
name: name.into_boxed_str(),
dependencies: dependencies.into_boxed_slice(),
tasks,
max_concurrency: raw.max_concurrency,
start_interval: Duration::from_millis(raw.start_interval_ms),
timeout: raw.timeout_ms.map(Duration::from_millis),
failure_policy: raw.failure_policy.into(),
});
}
validate_acyclic(path, &phases)?;
Ok(ParsedManifest {
manifest,
state_paths,
phases,
})
}
fn validate_task_threads(
path: &Path,
pointer: &str,
requested: usize,
available: usize,
) -> Result<(), ConfigError> {
if requested > available {
return Err(ConfigError::invalid(
path,
format!("{pointer}/resources/threads"),
format!(
"task thread request {requested} exceeds the study-wide thread budget {available}"
),
));
}
Ok(())
}
fn megabytes_to_bytes(
path: &Path,
pointer: &'static str,
megabytes: NonZeroU64,
) -> Result<NonZeroU64, ConfigError> {
megabytes
.get()
.checked_mul(BYTES_PER_MEGABYTE)
.and_then(NonZeroU64::new)
.ok_or_else(|| {
ConfigError::invalid(
path,
pointer,
"persistence size is too large to represent as a byte count",
)
})
}
fn validate_identifier(
path: &Path,
pointer: &str,
value: &str,
kind: &str,
) -> Result<(), ConfigError> {
if value.is_empty() || value.trim() != value {
return Err(ConfigError::invalid(
path,
pointer,
format!("{kind} must be nonempty and contain no surrounding whitespace"),
));
}
Ok(())
}
fn validate_acyclic(path: &Path, phases: &[ParsedPhase]) -> Result<(), ConfigError> {
fn visit(
index: usize,
phases: &[ParsedPhase],
by_name: &std::collections::HashMap<&str, usize>,
states: &mut [u8],
) -> Option<String> {
if states[index] == 1 {
return Some(phases[index].name.to_string());
}
if states[index] == 2 {
return None;
}
states[index] = 1;
for dependency in &phases[index].dependencies {
let dependency = by_name[dependency.as_ref()];
if let Some(phase) = visit(dependency, phases, by_name, states) {
return Some(phase);
}
}
states[index] = 2;
None
}
let by_name = phases
.iter()
.enumerate()
.map(|(index, phase)| (phase.name.as_ref(), index))
.collect::<std::collections::HashMap<_, _>>();
let mut states = vec![0_u8; phases.len()];
for index in 0..phases.len() {
if let Some(phase) = visit(index, phases, &by_name, &mut states) {
return Err(ConfigError::invalid(
path,
"/phases",
format!("phase dependency cycle includes `{phase}`"),
));
}
}
Ok(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawStudy {
#[serde(default)]
disk: RawDisk,
workflow_schema: u64,
#[serde(default)]
active_phases: Option<Vec<usize>>,
#[serde(default)]
reuse_from: Option<PathBuf>,
threads: usize,
compute: RawCompute,
#[serde(default)]
paths: RawPaths,
#[serde(default)]
seed: Option<u64>,
#[serde(default)]
replicates: RawReplicatePolicy,
#[serde(default)]
persistence: RawPersistence,
phases: Map<String, Value>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawCompute {
mode: RawComputeMode,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum RawComputeMode {
Auto,
Isolated,
}
impl From<RawComputeMode> for ComputeMode {
fn from(value: RawComputeMode) -> Self {
match value {
RawComputeMode::Auto => Self::Auto,
RawComputeMode::Isolated => Self::Isolated,
}
}
}
#[derive(Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPaths {
#[serde(default)]
states: BTreeMap<String, PathBuf>,
}
const BYTES_PER_MEGABYTE: u64 = 1_000_000;
const DEFAULT_PERSISTENCE_MB: u64 = 64;
#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawPersistence {
chunk_target_mb: NonZeroU64,
queue_capacity_mb: NonZeroU64,
}
impl Default for RawPersistence {
fn default() -> Self {
Self {
chunk_target_mb: NonZeroU64::new(DEFAULT_PERSISTENCE_MB)
.expect("the built-in persistence megabyte setting is positive"),
queue_capacity_mb: NonZeroU64::new(DEFAULT_PERSISTENCE_MB)
.expect("the built-in persistence megabyte setting is positive"),
}
}
}
#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawReplicatePolicy {
count: u64,
scheduling: RawReplicateScheduling,
failure_policy: RawFailurePolicy,
}
impl Default for RawReplicatePolicy {
fn default() -> Self {
Self {
count: 1,
scheduling: RawReplicateScheduling::default(),
failure_policy: RawFailurePolicy::default(),
}
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawPhase {
#[serde(default)]
task_names: Option<RawTaskNames>,
#[serde(default)]
threads: Option<NonZeroUsize>,
#[serde(default)]
mode: RawNpyMode,
#[serde(default)]
exclude_streams: Vec<String>,
#[serde(default)]
after: Vec<String>,
#[serde(default)]
tasks: Vec<RawTask>,
#[serde(default = "default_max_concurrency")]
max_concurrency: usize,
#[serde(default)]
start_interval_ms: u64,
#[serde(default)]
timeout_ms: Option<u64>,
#[serde(default)]
failure_policy: RawFailurePolicy,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawTaskNames {
mode: RawTaskNameMode,
#[serde(default)]
prefix: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum RawTaskNameMode {
Auto,
}
#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct RawDisk {
pause_at_percent: Option<f64>,
}
impl Default for RawDisk {
fn default() -> Self {
Self {
pause_at_percent: Some(95.0),
}
}
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum RawNpyMode {
Fixed,
#[default]
Auto,
}
const fn default_max_concurrency() -> usize {
1
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawTask {
#[serde(default)]
execution_unit: Option<String>,
#[serde(default)]
active: Option<bool>,
#[serde(default)]
state: Option<String>,
#[serde(default)]
program: Option<PathBuf>,
#[serde(default)]
python: Option<PythonTaskDeclaration>,
#[serde(default)]
args: Vec<String>,
#[serde(default)]
timeout_ms: Option<u64>,
#[serde(default)]
seed: Option<RawProgramSeed>,
#[serde(default)]
resources: Option<RawTaskResources>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawTaskResources {
threads: NonZeroUsize,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawProgramSeed {
purpose: String,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum RawReplicateScheduling {
#[default]
Sequential,
Parallel,
}
impl From<RawReplicateScheduling> for ReplicateScheduling {
fn from(value: RawReplicateScheduling) -> Self {
match value {
RawReplicateScheduling::Sequential => Self::Sequential,
RawReplicateScheduling::Parallel => Self::Parallel,
}
}
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "snake_case")]
enum RawFailurePolicy {
#[default]
FailFast,
FinishAll,
}
impl From<RawFailurePolicy> for FailurePolicy {
fn from(value: RawFailurePolicy) -> Self {
match value {
RawFailurePolicy::FailFast => Self::FailFast,
RawFailurePolicy::FinishAll => Self::FinishAll,
}
}
}