mod artifact;
mod cas;
mod fs_safety;
mod launch;
mod recovery;
#[cfg(feature = "lab")]
pub use artifact::profiling::{ContentProfile, exact_content, profile_content};
pub use artifact::{Artifact, Kind};
use artifact::{Hash, Tree};
use cas::Cache;
use fs_safety::{Scratch, invalid};
pub use rustsy_engine::adaptive::{Capacity, Memory};
use rustsy_engine::{
adaptive::{History, Operation, Route, Scheduler},
cache::ActionKey,
};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
fs, io,
path::{Path, PathBuf},
sync::{
OnceLock,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Policy {
#[default]
Off,
Local,
Portable,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Node {
pub name: String,
pub executable: PathBuf,
pub tool_version: String,
#[serde(default)]
pub args: Vec<String>,
pub cwd: String,
#[serde(default)]
pub inputs: Vec<Artifact>,
#[serde(default)]
pub outputs: Vec<Artifact>,
#[serde(default)]
pub dependencies: Vec<usize>,
#[serde(default)]
pub env: BTreeMap<String, String>,
#[serde(default)]
pub cache: Policy,
#[serde(default)]
pub ram_bytes: usize,
#[serde(default)]
pub hard_ram_bytes: usize,
#[serde(default)]
pub gpu: bool,
#[serde(default)]
pub vram_bytes: usize,
pub timeout_ms: u64,
pub estimate_ns: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
Executed,
Cached,
Failed,
Blocked,
Timeout,
Cancelled,
}
impl Status {
pub fn success(self) -> bool {
matches!(self, Self::Executed | Self::Cached)
}
}
impl NodeReport {
pub fn reason(&self) -> &'static str {
match (self.status, self.cache) {
(Status::Blocked, _) => "a declared dependency did not complete",
(Status::Cancelled, _) => "cancellation requested",
(Status::Timeout, _) => "process deadline exceeded",
(Status::Failed, _) => "command or artifact verification failed",
(Status::Cached, _) if self.restored_artifacts != 0 => {
"verified cache hit; restored declared outputs"
}
(Status::Cached, _) => "verified cache hit; local outputs match",
(Status::Executed, CacheStatus::Miss) => "action key absent; executed and stored",
(Status::Executed, CacheStatus::Corrupted) => {
"invalid cache data; executed and repaired"
}
_ => "cache disabled; executed",
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheStatus {
#[default]
Off,
Miss,
Hit,
Corrupted,
}
#[derive(Debug, Serialize)]
pub struct NodeReport {
pub name: String,
pub status: Status,
pub cache: CacheStatus,
pub reason: &'static str,
pub cache_payloads_verified: bool,
pub key: Option<String>,
pub exit_code: Option<i32>,
pub error: Option<String>,
pub restored_artifacts: usize,
pub restored_paths: Vec<String>,
pub hashing_ns: u64,
pub cache_lookup_restore_ns: u64,
pub cache_store_ns: u64,
pub process_ns: u64,
pub cpu_ns: Option<u64>,
pub peak_job_commit_bytes: Option<u64>,
pub ready_ns: u64,
pub started_ns: u64,
pub elapsed_ns: u64,
pub queue_delay_ns: u64,
#[serde(skip)]
outputs: Vec<Tree>,
}
impl NodeReport {
fn new(node: &Node) -> Self {
Self {
name: node.name.clone(),
status: Status::Failed,
cache: CacheStatus::Off,
reason: "",
cache_payloads_verified: false,
key: None,
exit_code: None,
error: None,
restored_artifacts: 0,
restored_paths: Vec::new(),
hashing_ns: 0,
cache_lookup_restore_ns: 0,
cache_store_ns: 0,
process_ns: 0,
cpu_ns: None,
peak_job_commit_bytes: None,
ready_ns: 0,
started_ns: 0,
elapsed_ns: 0,
queue_delay_ns: 0,
outputs: Vec::new(),
}
}
}
#[derive(Debug, Serialize)]
pub struct Report {
pub elapsed_ns: u64,
pub setup_ns: u64,
pub recovered_transactions: usize,
pub estimated_dependency_path_ns: u64,
pub observed_dependency_path_ns: u64,
pub estimated_dependency_path: Vec<usize>,
pub observed_dependency_path: Vec<usize>,
pub dispatch_ns: u64,
pub tool_hash_ns: u64,
pub memory_blocked_ns: u64,
pub peak_reserved_ram: usize,
pub peak_reserved_vram: usize,
pub average_worker_concurrency: f64,
pub peak_worker_concurrency: usize,
pub saved_work_estimate_ns: u64,
pub measured_cpu_ns: Option<u64>,
pub measured_cpu_average_cores: Option<f64>,
pub path_to_logs: PathBuf,
pub nodes: Vec<NodeReport>,
}
impl Report {
pub fn succeeded(&self) -> bool {
self.nodes.iter().all(|n| n.status.success())
}
pub fn print_summary(&self) {
let count = |status| self.nodes.iter().filter(|n| n.status == status).count();
println!(
"{:.3} ms wall · {:.3} ms dependency path · {} executed · {} cached · {} restored outputs · peak {} workers",
self.elapsed_ns as f64 / 1e6,
self.observed_dependency_path_ns as f64 / 1e6,
count(Status::Executed),
count(Status::Cached),
self.nodes
.iter()
.map(|n| n.restored_artifacts)
.sum::<usize>(),
self.peak_worker_concurrency
);
println!(
" observed path: {}",
self.observed_dependency_path
.iter()
.map(|&id| self.nodes[id].name.as_str())
.collect::<Vec<_>>()
.join(" -> ")
);
println!(
" estimated path {:.3} ms · memory admission wait {:.3} ms · tool hashing {:.3} ms · estimated skipped work {:.3} ms",
self.estimated_dependency_path_ns as f64 / 1e6,
self.memory_blocked_ns as f64 / 1e6,
self.tool_hash_ns as f64 / 1e6,
self.saved_work_estimate_ns as f64 / 1e6
);
for node in &self.nodes {
println!(
" {:<22} {:?} {:.3} ms · queue {:.3} ms · {}",
node.name,
node.status,
node.elapsed_ns as f64 / 1e6,
node.queue_delay_ns as f64 / 1e6,
node.reason,
);
if let Some(error) = &node.error {
println!(" {error}");
}
}
}
pub fn trace(&self) -> serde_json::Value {
let events: Vec<_> = self
.nodes
.iter()
.enumerate()
.map(|(id, n)| {
serde_json::json!({
"ph": "X", "name": n.name, "pid": 1, "tid": id,
"ts": n.started_ns as f64 / 1_000.0, "dur": n.elapsed_ns as f64 / 1_000.0,
"args": {"status": n.status, "cache": n.cache, "queue_ns": n.queue_delay_ns}
})
})
.collect();
serde_json::json!({"traceEvents": events})
}
}
pub struct Graph {
nodes: Vec<Node>,
schedule: Scheduler,
estimated_path: u64,
estimated_chain: Vec<usize>,
order: Vec<usize>,
shared_inputs: Vec<Vec<Option<usize>>>,
shared_input_count: usize,
reuse_shared_inputs: bool,
fingerprint_workers: Option<usize>,
parallel_large_inputs: bool,
packed_outputs: bool,
reuse_dependency_outputs: bool,
hash_uncached_outputs: bool,
verify_local_hit_payload: bool,
revalidate_cache_misses: bool,
external_tool_files: Vec<Vec<PathBuf>>,
cache_bypass: bool,
}
impl Graph {
pub fn new(mut nodes: Vec<Node>) -> io::Result<Self> {
let mut names = BTreeSet::new();
for node in &mut nodes {
if node.name.is_empty() || !names.insert(node.name.clone()) || node.timeout_ms == 0 {
return Err(invalid("empty or duplicate node name, or zero timeout"));
}
if node.hard_ram_bytes > node.ram_bytes || (!node.gpu && node.vram_bytes != 0) {
return Err(invalid(
"hard RAM and VRAM limits must agree with admission reservations",
));
}
fs_safety::relative(&node.cwd, true)?;
if node.cache != Policy::Off
&& (node.outputs.is_empty() || node.tool_version.is_empty())
{
return Err(invalid("cached actions require outputs and tool identity"));
}
let mut env_keys = BTreeSet::new();
if node.env.iter().any(|(key, val)| {
key.is_empty()
|| key.contains(['=', '\0'])
|| val.contains('\0')
|| !env_keys.insert(fs_safety::identity(key))
}) {
return Err(invalid("invalid or aliased environment key"));
}
for item in node.outputs.iter().chain(&node.inputs) {
fs_safety::relative(&item.path, false)?;
}
node.inputs.sort_unstable_by(|a, b| a.path.cmp(&b.path));
node.outputs.sort_unstable_by(|a, b| a.path.cmp(&b.path));
node.dependencies.sort_unstable();
node.dependencies.dedup();
}
let schedule = Scheduler::new(
nodes
.iter()
.enumerate()
.map(|(index, node)| {
let mut routes = [None; 3];
routes[usize::from(node.gpu)] = Some(Route {
estimate: Duration::from_nanos(node.estimate_ns),
memory: Memory {
ram: node.ram_bytes,
vram: node.vram_bytes,
},
});
Operation {
dependencies: node.dependencies.clone(),
class: index as u64,
bytes: 0,
routes,
}
})
.collect(),
)
.map_err(invalid)?;
let (order, dependencies) = analyze(&nodes);
let (estimated_path, estimated_chain) = longest(&nodes, &order, |id| nodes[id].estimate_ns);
let output_paths: Vec<_> = nodes
.iter()
.enumerate()
.flat_map(|(id, n)| {
n.outputs
.iter()
.map(move |item| (id, fs_safety::identity(&item.path)))
})
.collect();
for (index, (id, path)) in output_paths.iter().enumerate() {
if output_paths[..index]
.iter()
.any(|(_, prior)| overlap(path, prior))
{
return Err(invalid("output ownership overlaps another declaration"));
}
for (reader, job) in nodes.iter().enumerate() {
if job
.inputs
.iter()
.any(|input| overlap(path, &fs_safety::identity(&input.path)))
&& !dependencies[reader].contains(id)
{
return Err(invalid("an artifact reader must depend on the sole writer"));
}
}
}
if nodes.iter().enumerate().any(|(id, node)| {
node.cache != Policy::Off
&& dependencies[id]
.iter()
.any(|&dep| nodes[dep].outputs.is_empty())
}) {
return Err(invalid(
"cached task depends on a process without declared outputs",
));
}
let (shared_inputs, shared_input_count) = shared_layout(&nodes, &output_paths);
let external_tool_files = vec![Vec::new(); nodes.len()];
Ok(Self {
nodes,
schedule,
estimated_path,
estimated_chain,
order,
shared_inputs,
shared_input_count,
reuse_shared_inputs: true,
fingerprint_workers: None,
parallel_large_inputs: false,
packed_outputs: false,
reuse_dependency_outputs: true,
hash_uncached_outputs: true,
verify_local_hit_payload: true,
revalidate_cache_misses: true,
external_tool_files,
cache_bypass: false,
})
}
pub fn reuse_shared_inputs(mut self, enabled: bool) -> Self {
self.reuse_shared_inputs = enabled;
self
}
pub fn fingerprint_workers(mut self, workers: usize) -> io::Result<Self> {
if !(1..=64).contains(&workers) {
return Err(invalid("fingerprint_workers must be 1..=64"));
}
self.fingerprint_workers = Some(workers);
Ok(self)
}
#[cfg(feature = "lab")]
pub fn parallel_large_inputs(mut self, enabled: bool) -> Self {
self.parallel_large_inputs = enabled;
self
}
#[cfg(feature = "lab")]
pub fn packed_outputs(mut self, enabled: bool) -> Self {
self.packed_outputs = enabled;
self
}
pub fn reuse_dependency_outputs(mut self, enabled: bool) -> Self {
self.reuse_dependency_outputs = enabled;
self
}
#[cfg(feature = "lab")]
pub fn hash_uncached_outputs(mut self, enabled: bool) -> Self {
self.hash_uncached_outputs = enabled;
self
}
#[cfg(feature = "lab")]
pub fn verify_local_hit_payload(mut self, enabled: bool) -> Self {
self.verify_local_hit_payload = enabled;
self
}
#[cfg(feature = "lab")]
pub fn legacy_cache_publication(mut self) -> Self {
self.revalidate_cache_misses = false;
self
}
pub fn external_tool_files(mut self, node: usize, mut files: Vec<PathBuf>) -> io::Result<Self> {
let destination = self
.external_tool_files
.get_mut(node)
.ok_or_else(|| invalid("unknown node"))?;
files.sort_unstable();
files.dedup();
*destination = files;
Ok(self)
}
pub fn validate_tools(&self) -> io::Result<()> {
for node in &self.nodes {
check_tool(node)?;
}
for files in &self.external_tool_files {
for file in files {
check_tool_file(file)?;
}
}
Ok(())
}
#[doc(hidden)]
pub fn bypass_cache(mut self) -> Self {
self.cache_bypass = true;
self
}
pub fn planned_critical_path(&self) -> (u64, impl Iterator<Item = &str>) {
(
self.estimated_path,
self.estimated_chain
.iter()
.map(|&id| self.nodes[id].name.as_str()),
)
}
#[doc(hidden)]
pub fn cost_path(&self, costs_ns: &[u64]) -> Option<u64> {
(costs_ns.len() == self.nodes.len())
.then(|| longest(&self.nodes, &self.order, |i| costs_ns[i]).0)
}
pub fn run(
&self,
workspace: &Path,
cache: Option<&Path>,
limits: Capacity,
cancel: &AtomicBool,
) -> io::Result<Report> {
let wall = Instant::now();
if !self.cache_bypass
&& self.revalidate_cache_misses
&& cache.is_none()
&& self.nodes.iter().any(|job| job.cache != Policy::Off)
{
return Err(invalid("a cache policy requires a cache directory"));
}
let root = fs_safety::absolute(workspace)?;
let internal = fs_safety::private_dir(&root, ".rustsy-process")?;
let lease = Lease::new(&internal, &root)?;
let cache = cache
.filter(|_| !self.cache_bypass)
.map(|p| -> io::Result<_> {
let local = p == workspace.join(".rustsy-process/cache");
let absolute = if local {
fs_safety::private_dir(&internal, "cache")?
} else {
fs_safety::absolute(p)?
};
if !local && (root.starts_with(&absolute) || absolute.starts_with(&root)) {
return Err(invalid("workspace and shared cache must not overlap"));
}
Cache::new(
&absolute,
self.packed_outputs,
self.verify_local_hit_payload,
)
})
.transpose()?;
let log_path = lease.logs.clone();
let previous: Vec<OnceLock<NodeReport>> =
(0..self.nodes.len()).map(|_| OnceLock::new()).collect();
let shared_hashes: Vec<OnceLock<SharedTree>> = (0..self.shared_input_count)
.map(|_| OnceLock::new())
.collect();
let tools = self
.nodes
.iter()
.map(check_tool)
.collect::<io::Result<Vec<_>>>()?;
let mut tool_digests = BTreeMap::new();
let mut tool_hash_ns = BTreeMap::new();
let mut resource_digests = BTreeMap::new();
let mut resources = vec![Vec::new(); self.nodes.len()];
let needs_pool = self.parallel_large_inputs
|| self.nodes.iter().any(|job| {
job.cache != Policy::Off
&& job
.inputs
.iter()
.chain(&job.outputs)
.any(|item| item.kind == Kind::Directory)
});
let hashing = (cache.is_some() && needs_pool)
.then_some(())
.map(|_| {
rayon::ThreadPoolBuilder::new()
.num_threads(self.fingerprint_workers.unwrap_or_else(|| {
std::thread::available_parallelism()
.map_or(1, usize::from)
.min(12)
}))
.build()
.map_err(io::Error::other)
})
.transpose()?;
if cache.is_some() {
for (id, (node, tool)) in self.nodes.iter().zip(&tools).enumerate() {
if node.cache != Policy::Off && !tool_digests.contains_key(tool) {
let start = Instant::now();
let digest = if self.parallel_large_inputs {
artifact::fingerprint_file(
tool,
hashing
.as_ref()
.ok_or_else(|| invalid("missing segment worker pool"))?,
)?
} else {
artifact::copy_hash(tool, io::sink())?
};
tool_digests.insert(tool.clone(), digest);
tool_hash_ns.insert(tool.clone(), ns(start.elapsed()));
}
if node.cache != Policy::Off {
for file in &self.external_tool_files[id] {
let path = check_tool_file(file)?;
let digest = match resource_digests.entry(path.clone()) {
std::collections::btree_map::Entry::Occupied(entry) => *entry.get(),
std::collections::btree_map::Entry::Vacant(entry) => {
let start = Instant::now();
let digest = artifact::copy_hash(&path, io::sink())?;
*tool_hash_ns.entry(path.clone()).or_default() +=
ns(start.elapsed());
*entry.insert(digest)
}
};
resources[id].push((path, digest));
}
}
}
}
let aggregate_tool_hash_ns = tool_hash_ns
.values()
.copied()
.fold(0u64, u64::saturating_add);
let mut required_hashes = vec![self.hash_uncached_outputs; self.nodes.len()];
if cache.is_some() && !self.hash_uncached_outputs {
for &id in self.order.iter().rev() {
if required_hashes[id] || self.nodes[id].cache != Policy::Off {
required_hashes[id] = true;
for &dep in &self.nodes[id].dependencies {
required_hashes[dep] = true;
}
}
}
}
let setup_ns = ns(wall.elapsed());
let result = self
.schedule
.execute(
limits,
&mut History::default(),
|_| Ok(()),
|_, id, _| {
let job = &self.nodes[id];
let mut report = NodeReport::new(job);
if cancel.load(Ordering::Acquire) {
report.status = Status::Cancelled;
} else if job
.dependencies
.iter()
.any(|&p| !previous[p].get().unwrap().status.success())
{
report.status = Status::Blocked;
} else {
let context = Context {
root: &root,
internal: &lease.transactions,
cache: cache.as_ref(),
cancel,
log_path: &log_path,
previous: &previous,
hashing: hashing.as_ref(),
shared_slots: &self.shared_inputs[id],
shared_hashes: &shared_hashes,
reuse_shared_inputs: self.reuse_shared_inputs,
parallel_large_inputs: self.parallel_large_inputs,
packed_outputs: self.packed_outputs,
reuse_dependency_outputs: self.reuse_dependency_outputs,
hash_output: required_hashes[id],
revalidate_cache_misses: self.revalidate_cache_misses,
external_tool_files: &self.external_tool_files[id],
tool_resources: &resources[id],
};
if let Err(err) = context.node(
job,
id,
&tools[id],
tool_digests.get(&tools[id]),
&mut report,
) {
report.status = Status::Failed;
report.error = Some(err.to_string());
}
}
report.reason = report.reason();
previous[id]
.set(report)
.map_err(|_| "duplicate process completion".into())
},
)
.map_err(io::Error::other)?;
let mut nodes = previous
.into_iter()
.map(|n| n.into_inner().unwrap())
.collect::<Vec<_>>();
let mut endpoints = Vec::with_capacity(nodes.len() * 2);
let mut work = 0u64;
let mut saved_work = 0u64;
for sample in &result.samples {
let n = &mut nodes[sample.task];
n.ready_ns = ns(sample.ready_at);
n.started_ns = ns(sample.started_at);
n.elapsed_ns = ns(sample.elapsed);
n.queue_delay_ns = n.started_ns.saturating_sub(n.ready_ns);
if n.elapsed_ns > 0 {
endpoints.push((n.started_ns, true));
endpoints.push((n.started_ns.saturating_add(n.elapsed_ns), false));
}
work = work.saturating_add(n.elapsed_ns);
if n.status == Status::Cached {
saved_work = saved_work.saturating_add(
self.nodes[sample.task]
.estimate_ns
.saturating_sub(n.elapsed_ns),
);
}
}
endpoints.sort_unstable();
let mut peak = 0;
let mut live = 0;
for (_, add) in endpoints {
if add {
live += 1;
peak = peak.max(live);
} else {
live -= 1;
}
}
let elapsed = ns(wall.elapsed());
let (observed_dependency_path_ns, observed_dependency_path) =
longest(&self.nodes, &self.order, |id| nodes[id].elapsed_ns);
let measured_cpu_ns = nodes
.iter()
.filter_map(|node| node.cpu_ns)
.reduce(u64::saturating_add);
Ok(Report {
elapsed_ns: elapsed,
setup_ns,
recovered_transactions: lease.recovered,
estimated_dependency_path_ns: self.estimated_path,
observed_dependency_path_ns,
estimated_dependency_path: self.estimated_chain.clone(),
observed_dependency_path,
dispatch_ns: ns(result.dispatch_time),
tool_hash_ns: aggregate_tool_hash_ns,
memory_blocked_ns: ns(result.memory_blocked),
peak_reserved_ram: result.peak.ram,
peak_reserved_vram: result.peak.vram,
average_worker_concurrency: work as f64 / elapsed.max(1) as f64,
peak_worker_concurrency: peak,
saved_work_estimate_ns: saved_work,
measured_cpu_ns,
measured_cpu_average_cores: measured_cpu_ns
.map(|time| time as f64 / elapsed.max(1) as f64),
path_to_logs: log_path,
nodes,
})
}
}
fn overlap(a: &str, b: &str) -> bool {
a == b
|| a.strip_prefix(b).is_some_and(|rest| rest.starts_with('/'))
|| b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
}
fn shared_layout(nodes: &[Node], outputs: &[(usize, String)]) -> (Vec<Vec<Option<usize>>>, usize) {
let mut counts = BTreeMap::new();
for job in nodes.iter().filter(|job| job.cache != Policy::Off) {
for input in &job.inputs {
*counts.entry((&input.path, input.kind)).or_insert(0usize) += 1;
}
}
let identities: BTreeMap<_, _> = counts
.into_iter()
.filter_map(|(key, count)| (count > 1).then_some(key))
.filter(|(path, _)| {
let path = fs_safety::identity(path);
!outputs.iter().any(|(_, out)| overlap(&path, out))
})
.enumerate()
.map(|(slot, key)| (key, slot))
.collect();
let layout = nodes
.iter()
.map(|job| {
job.inputs
.iter()
.map(|input| identities.get(&(&input.path, input.kind)).copied())
.collect()
})
.collect();
(layout, identities.len())
}
fn analyze(nodes: &[Node]) -> (Vec<usize>, Vec<BTreeSet<usize>>) {
let mut pending: Vec<_> = nodes.iter().map(|n| n.dependencies.len()).collect();
let mut successors = vec![Vec::new(); nodes.len()];
for (id, node) in nodes.iter().enumerate() {
for &dep in &node.dependencies {
successors[dep].push(id);
}
}
let mut queue: Vec<_> = pending
.iter()
.enumerate()
.filter_map(|(i, &n)| (n == 0).then_some(i))
.collect();
let mut seen = 0;
let mut deps = vec![BTreeSet::new(); nodes.len()];
while let Some(&id) = queue.get(seen) {
seen += 1;
let node = &nodes[id];
for &dep in &node.dependencies {
let ancestors = deps[dep].clone();
deps[id].extend(ancestors);
deps[id].insert(dep);
}
for &next in &successors[id] {
pending[next] -= 1;
if pending[next] == 0 {
queue.push(next);
}
}
}
(queue, deps)
}
fn longest(nodes: &[Node], order: &[usize], cost: impl Fn(usize) -> u64) -> (u64, Vec<usize>) {
let mut best = vec![0u64; nodes.len()];
let mut parents = vec![None; nodes.len()];
for &id in order {
let parent = nodes[id]
.dependencies
.iter()
.copied()
.max_by_key(|&dep| best[dep]);
parents[id] = parent;
best[id] = cost(id).saturating_add(parent.map_or(0, |dep| best[dep]));
}
let mut tip = order.iter().copied().max_by_key(|&id| best[id]);
let duration = tip.map_or(0, |id| best[id]);
let mut chain = Vec::new();
while let Some(id) = tip {
chain.push(id);
tip = parents[id];
}
chain.reverse();
(duration, chain)
}
fn check_tool(job: &Node) -> io::Result<PathBuf> {
let tool = check_tool_file(&job.executable)?;
#[cfg(windows)]
if !tool
.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| value.eq_ignore_ascii_case("exe"))
{
return Err(invalid("use an explicit .exe for direct Windows launch"));
}
Ok(tool)
}
fn check_tool_file(path: &Path) -> io::Result<PathBuf> {
let path = fs_safety::absolute(path)?;
if !fs_safety::node_md(&path)?.is_file() {
return Err(invalid("expected a regular tool file"));
}
Ok(path)
}
fn ns(time: Duration) -> u64 {
time.as_nanos().min(u128::from(u64::MAX)) as u64
}
struct Lease {
_file: fs::File,
marker: PathBuf,
logs: PathBuf,
transactions: PathBuf,
recovered: usize,
}
impl Lease {
fn new(internal: &Path, workspace: &Path) -> io::Result<Self> {
let path = internal.join("active.lock");
match fs_safety::node_md(&path) {
Ok(md) if md.is_file() => {}
Ok(_) => return Err(invalid("workspace lock must be a regular file")),
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
options.share_mode(3).custom_flags(0x0020_0000); }
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = options.open(&path)?;
if !fs_safety::checked(&path, file.metadata()?)?.is_file() {
return Err(invalid("workspace lock must be a regular file"));
}
file.try_lock().map_err(|error| match error {
std::fs::TryLockError::WouldBlock => io::Error::new(
io::ErrorKind::WouldBlock,
"workspace already has an active RustSy run",
),
std::fs::TryLockError::Error(e) => e,
})?;
let legacy = internal.join("active");
let recovered = match fs::symlink_metadata(&legacy) {
Ok(_) => recovery::resume(internal, workspace, &legacy)?,
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
Err(e) => return Err(e),
};
let logs = Scratch::new(internal)?.persist();
let transactions = fs_safety::private_dir(&logs, "transactions")?;
use std::io::Write;
let staged = logs.join("run-marker");
let mut marker = fs::File::create_new(&staged)?;
writeln!(
marker,
"rustsy-7:{}",
logs.file_name().unwrap().to_string_lossy()
)?;
marker.sync_all()?;
drop(marker);
fs::hard_link(staged, &legacy)?;
Ok(Self {
_file: file,
marker: legacy,
logs,
transactions,
recovered,
})
}
}
impl Drop for Lease {
fn drop(&mut self) {
if !recovery::requires_recovery(&self.transactions) {
let _ = fs::remove_file(&self.marker);
}
}
}
struct Context<'a> {
root: &'a Path,
internal: &'a Path,
cache: Option<&'a Cache>,
cancel: &'a AtomicBool,
log_path: &'a Path,
previous: &'a [OnceLock<NodeReport>],
hashing: Option<&'a rayon::ThreadPool>,
shared_slots: &'a [Option<usize>],
shared_hashes: &'a [OnceLock<SharedTree>],
reuse_shared_inputs: bool,
parallel_large_inputs: bool,
packed_outputs: bool,
reuse_dependency_outputs: bool,
hash_output: bool,
revalidate_cache_misses: bool,
external_tool_files: &'a [PathBuf],
tool_resources: &'a [(PathBuf, Hash)],
}
type SharedTree = Result<Vec<u8>, (io::ErrorKind, String)>;
impl Context<'_> {
fn node(
&self,
job: &Node,
id: usize,
tool: &Path,
digest: Option<&Hash>,
report: &mut NodeReport,
) -> io::Result<()> {
let cwd = fs_safety::path(self.root, &job.cwd, false)?;
if !fs_safety::node_md(&cwd)?.is_dir() {
return Err(invalid("cwd is not a directory"));
}
let selected = self.cache.filter(|_| job.cache != Policy::Off);
let action = match selected {
Some(cache) => {
let start = Instant::now();
let hash = self.key(
job,
tool,
digest.ok_or_else(|| invalid("missing tool hash"))?,
false,
)?;
report.hashing_ns = ns(start.elapsed());
report.key = Some(artifact::text(&hash));
let lookup = Instant::now();
let restored =
cache.restore(self.root, self.internal, hash, &job.outputs, self.hashing);
report.cache_lookup_restore_ns = ns(lookup.elapsed());
match restored {
Ok((outputs, restored, payloads_verified)) => {
report.status = Status::Cached;
report.cache = CacheStatus::Hit;
report.cache_payloads_verified = payloads_verified;
report.outputs = outputs;
report.restored_artifacts = restored.len();
report.restored_paths = restored;
return Ok(());
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
report.cache = CacheStatus::Miss
}
Err(e) if e.kind() == io::ErrorKind::InvalidData => {
report.cache = CacheStatus::Corrupted
}
Err(e) => return Err(e),
}
Some((cache, hash))
}
None => None,
};
for out in &job.outputs {
let path = fs_safety::path(self.root, &out.path, true)?;
match fs_safety::node_md(&path) {
Ok(_) => {
artifact::describe(self.root, out, |_| Ok([0; 32]))?;
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
let log = fs_safety::private_dir(self.log_path, &format!("node-{id}"))?;
if self.cancel.load(Ordering::Acquire) {
report.status = Status::Cancelled;
return Ok(());
}
let mut outputs = if job.cache == Policy::Off {
None
} else {
Some(Quarantine::new(self.internal, self.root, &job.outputs)?)
};
let launch_scope = Scratch::new(self.internal)?;
let busy = launch_scope.0.join("child-active");
fs::File::create_new(&busy)?;
let start = Instant::now();
let execution = launch::run(job, tool, &cwd, &log, self.cancel);
if let Err(err) = fs::remove_file(&busy) {
launch_scope.persist();
return Err(err);
}
let execution = execution?;
report.process_ns = ns(start.elapsed());
report.status = execution.status;
report.exit_code = execution.exit_code;
report.cpu_ns = execution.cpu_ns;
report.peak_job_commit_bytes = execution.peak_job_commit_bytes;
if !execution.status.success() {
return Ok(());
}
let start = Instant::now();
report.outputs = if let Some((cache, hash)) = action {
if self.revalidate_cache_misses {
let current_tool = check_tool(job)?;
let current_digest = if self.parallel_large_inputs {
artifact::fingerprint_file(
¤t_tool,
self.hashing
.ok_or_else(|| invalid("missing fingerprint pool"))?,
)?
} else {
artifact::copy_hash(¤t_tool, io::sink())?
};
let current = self.key(job, ¤t_tool, ¤t_digest, true)?;
report.hashing_ns = report.hashing_ns.saturating_add(ns(start.elapsed()));
if current != hash {
return Err(invalid(
"declared inputs or tools changed during the action; cache publication refused",
));
}
}
if self.cancel.load(Ordering::Acquire) {
report.status = Status::Cancelled;
return Ok(());
}
let store = Instant::now();
let outputs = cache.capture(self.root, &job.outputs, hash, self.hashing)?;
report.cache_store_ns = ns(store.elapsed());
outputs
} else if !self.hash_output {
for output in &job.outputs {
artifact::describe(self.root, output, |_| Ok([0; 32]))?;
}
Vec::new()
} else {
job.outputs
.iter()
.map(|out| {
artifact::describe(self.root, out, |p| artifact::copy_hash(p, io::sink()))
})
.collect::<io::Result<_>>()?
};
if selected.is_none() && self.hash_output {
report.hashing_ns = report.hashing_ns.saturating_add(ns(start.elapsed()));
}
if let Some(guard) = &mut outputs {
recovery::commit(&guard.staged.as_ref().unwrap().0)?;
guard.committed = true;
}
Ok(())
}
fn key(&self, job: &Node, tool: &Path, digest: &Hash, fresh: bool) -> io::Result<Hash> {
let mut action = ActionKey::default();
action.include(
b"schema",
if self.parallel_large_inputs {
b"process-artifacts-segmented-1"
} else {
b"process-artifacts-1"
},
);
if self.packed_outputs {
action.include(b"cas-layout", b"indexed-pack-v1");
}
if self.revalidate_cache_misses {
action.include(b"publication", b"revalidated-v1");
}
action.include(
b"platform",
format!("{}/{}", std::env::consts::OS, std::env::consts::ARCH).as_bytes(),
);
action.include(
b"path-scope",
if job.cache == Policy::Portable {
b"portable".as_slice()
} else {
self.root.as_os_str().as_encoded_bytes()
},
);
action.include(b"cwd", job.cwd.as_bytes());
action.include(b"tool", tool.as_os_str().as_encoded_bytes());
action.include(b"tool-bytes", digest);
action.include(b"tool-version", job.tool_version.as_bytes());
if fresh {
for file in self.external_tool_files {
let file = check_tool_file(file)?;
action.include(b"external-tool-file", file.as_os_str().as_encoded_bytes());
action.include(
b"external-tool-bytes",
&artifact::copy_hash(&file, io::sink())?,
);
}
} else {
for (file, digest) in self.tool_resources {
action.include(b"external-tool-file", file.as_os_str().as_encoded_bytes());
action.include(b"external-tool-bytes", digest);
}
}
action.include(b"args", &serde_json::to_vec(&job.args)?);
action.include(b"env", &serde_json::to_vec(&job.env)?);
action.include(
b"resource-contract",
&serde_json::to_vec(&(job.gpu, job.ram_bytes, job.hard_ram_bytes, job.vram_bytes))?,
);
action.include(b"declared-outputs", &serde_json::to_vec(&job.outputs)?);
for &dep in &job.dependencies {
let previous = &self.previous[dep].get().unwrap().outputs;
if fresh {
for tree in previous {
let declaration = Artifact {
path: tree.path.clone(),
kind: if tree.entries[0].file.is_some() {
Kind::File
} else {
Kind::Directory
},
};
if artifact::hash_tree(self.root, &declaration, self.hashing)? != *tree {
return Err(invalid("a dependency artifact changed during the action"));
}
}
}
action.include(b"dependency-artifacts", &serde_json::to_vec(previous)?);
}
for (item, &slot) in job.inputs.iter().zip(self.shared_slots) {
if (fresh || self.reuse_dependency_outputs)
&& !(self.parallel_large_inputs && item.kind == Kind::File)
&& let Some(tree) = job
.dependencies
.iter()
.flat_map(|&id| &self.previous[id].get().unwrap().outputs)
.find(|tree| {
tree.path == item.path
&& tree.entries[0].file.is_some() == (item.kind == Kind::File)
})
{
action.include(b"input", &serde_json::to_vec(tree)?);
continue;
}
let encode = || -> io::Result<Vec<u8>> {
let tree = artifact::hash_input(
self.root,
item,
self.hashing,
self.parallel_large_inputs,
)?;
Ok(serde_json::to_vec(&tree)?)
};
if !fresh
&& self.reuse_shared_inputs
&& let Some(slot) = slot
{
let encoded = self.shared_hashes[slot]
.get_or_init(|| encode().map_err(|e| (e.kind(), e.to_string())))
.as_ref()
.map_err(|(kind, message)| io::Error::new(*kind, message.clone()))?;
action.include(b"input", encoded);
} else {
action.include(b"input", &encode()?);
}
}
Ok(action.finish())
}
}
struct Quarantine {
staged: Option<Scratch>,
items: Vec<(PathBuf, Option<PathBuf>)>,
committed: bool,
}
impl Quarantine {
fn new(internal: &Path, root: &Path, outputs: &[Artifact]) -> io::Result<Self> {
let mut guard = Self {
staged: Some(Scratch::new(internal)?),
items: Vec::new(),
committed: false,
};
recovery::prepare(
&guard.staged.as_ref().unwrap().0,
root,
outputs
.iter()
.enumerate()
.map(|(index, output)| (index, output.path.as_str())),
)?;
for (index, output) in outputs.iter().enumerate() {
let path = fs_safety::path(root, &output.path, true)?;
let backup = match fs_safety::node_md(&path) {
Ok(_) => {
let target = guard
.staged
.as_ref()
.unwrap()
.0
.join(format!("old-{index}"));
fs::rename(&path, &target)?;
Some(target)
}
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
guard.items.push((path, backup));
}
Ok(guard)
}
}
impl Drop for Quarantine {
fn drop(&mut self) {
if self.committed {
return;
}
let scratch = self.staged.as_ref().unwrap();
for (index, (out, backup)) in self.items.iter().enumerate().rev() {
let displaced = scratch.0.join(format!("failed-{index}"));
let replaced = match fs::rename(out, displaced) {
Ok(()) => true,
Err(e) => e.kind() == io::ErrorKind::NotFound,
};
if !replaced
|| backup
.as_ref()
.is_some_and(|old| fs::rename(old, out).is_err())
{
if let Some(staged) = self.staged.take() {
eprintln!(
"process output recovery needed at {}",
staged.persist().display()
);
}
return;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_snapshots_exclude_any_declared_writer() {
let parse = |name: &str| -> Node {
serde_json::from_value(serde_json::json!({
"name": name, "executable": "/tool", "tool_version": "1", "cwd": ".",
"inputs": [{"path":"src","kind":"directory"},
{"path":"generated","kind":"directory"}],
"cache": "portable", "timeout_ms": 1, "estimate_ns": 1
}))
.unwrap()
};
let nodes = [parse("one"), parse("two")];
let (slots, count) = shared_layout(&nodes, &[(2, fs_safety::identity("generated/value"))]);
assert_eq!(count, 1);
assert_eq!(slots, [vec![Some(0), None], vec![Some(0), None]]);
}
}