Skip to main content

rustsy_process/
lib.rs

1//! Declared process graphs. Commands and workspace owners are trusted.
2//! Cache inputs, tool versions and outputs form an explicit deterministic contract.
3
4mod artifact;
5mod cas;
6mod fs_safety;
7mod launch;
8mod recovery;
9
10#[cfg(feature = "lab")]
11pub use artifact::profiling::{ContentProfile, exact_content, profile_content};
12pub use artifact::{Artifact, Kind};
13use artifact::{Hash, Tree};
14use cas::Cache;
15use fs_safety::{Scratch, invalid};
16pub use rustsy_engine::adaptive::{Capacity, Memory};
17use rustsy_engine::{
18    adaptive::{History, Operation, Route, Scheduler},
19    cache::ActionKey,
20};
21use serde::{Deserialize, Serialize};
22use std::{
23    collections::{BTreeMap, BTreeSet},
24    fs, io,
25    path::{Path, PathBuf},
26    sync::{
27        OnceLock,
28        atomic::{AtomicBool, Ordering},
29    },
30    time::{Duration, Instant},
31};
32
33#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Policy {
36    #[default]
37    Off,
38    /// The caller declares a deterministic action with complete inputs.
39    Local,
40    /// Local semantics plus outputs that do not embed the absolute workspace path.
41    Portable,
42}
43
44#[derive(Clone, Debug, Deserialize)]
45#[serde(deny_unknown_fields)]
46pub struct Node {
47    pub name: String,
48    pub executable: PathBuf,
49    pub tool_version: String,
50    #[serde(default)]
51    pub args: Vec<String>,
52    pub cwd: String,
53    #[serde(default)]
54    pub inputs: Vec<Artifact>,
55    #[serde(default)]
56    pub outputs: Vec<Artifact>,
57    #[serde(default)]
58    pub dependencies: Vec<usize>,
59    #[serde(default)]
60    pub env: BTreeMap<String, String>,
61    #[serde(default)]
62    pub cache: Policy,
63    #[serde(default)]
64    pub ram_bytes: usize,
65    #[serde(default)]
66    pub hard_ram_bytes: usize,
67    #[serde(default)]
68    pub gpu: bool,
69    #[serde(default)]
70    pub vram_bytes: usize,
71    pub timeout_ms: u64,
72    pub estimate_ns: u64,
73}
74
75#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
76#[serde(rename_all = "snake_case")]
77pub enum Status {
78    Executed,
79    Cached,
80    Failed,
81    Blocked,
82    Timeout,
83    Cancelled,
84}
85
86impl Status {
87    pub fn success(self) -> bool {
88        matches!(self, Self::Executed | Self::Cached)
89    }
90}
91
92impl NodeReport {
93    pub fn reason(&self) -> &'static str {
94        match (self.status, self.cache) {
95            (Status::Blocked, _) => "a declared dependency did not complete",
96            (Status::Cancelled, _) => "cancellation requested",
97            (Status::Timeout, _) => "process deadline exceeded",
98            (Status::Failed, _) => "command or artifact verification failed",
99            (Status::Cached, _) if self.restored_artifacts != 0 => {
100                "verified cache hit; restored declared outputs"
101            }
102            (Status::Cached, _) => "verified cache hit; local outputs match",
103            (Status::Executed, CacheStatus::Miss) => "action key absent; executed and stored",
104            (Status::Executed, CacheStatus::Corrupted) => {
105                "invalid cache data; executed and repaired"
106            }
107            _ => "cache disabled; executed",
108        }
109    }
110}
111
112#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
113#[serde(rename_all = "snake_case")]
114pub enum CacheStatus {
115    #[default]
116    Off,
117    Miss,
118    Hit,
119    Corrupted,
120}
121
122#[derive(Debug, Serialize)]
123pub struct NodeReport {
124    pub name: String,
125    pub status: Status,
126    pub cache: CacheStatus,
127    pub reason: &'static str,
128    pub cache_payloads_verified: bool,
129    pub key: Option<String>,
130    pub exit_code: Option<i32>,
131    pub error: Option<String>,
132    pub restored_artifacts: usize,
133    pub restored_paths: Vec<String>,
134    pub hashing_ns: u64,
135    pub cache_lookup_restore_ns: u64,
136    pub cache_store_ns: u64,
137    pub process_ns: u64,
138    pub cpu_ns: Option<u64>,
139    pub peak_job_commit_bytes: Option<u64>,
140    pub ready_ns: u64,
141    pub started_ns: u64,
142    pub elapsed_ns: u64,
143    pub queue_delay_ns: u64,
144    #[serde(skip)]
145    outputs: Vec<Tree>,
146}
147
148impl NodeReport {
149    fn new(node: &Node) -> Self {
150        Self {
151            name: node.name.clone(),
152            status: Status::Failed,
153            cache: CacheStatus::Off,
154            reason: "",
155            cache_payloads_verified: false,
156            key: None,
157            exit_code: None,
158            error: None,
159            restored_artifacts: 0,
160            restored_paths: Vec::new(),
161            hashing_ns: 0,
162            cache_lookup_restore_ns: 0,
163            cache_store_ns: 0,
164            process_ns: 0,
165            cpu_ns: None,
166            peak_job_commit_bytes: None,
167            ready_ns: 0,
168            started_ns: 0,
169            elapsed_ns: 0,
170            queue_delay_ns: 0,
171            outputs: Vec::new(),
172        }
173    }
174}
175
176#[derive(Debug, Serialize)]
177pub struct Report {
178    pub elapsed_ns: u64,
179    pub setup_ns: u64,
180    pub recovered_transactions: usize,
181    pub estimated_dependency_path_ns: u64,
182    pub observed_dependency_path_ns: u64,
183    pub estimated_dependency_path: Vec<usize>,
184    pub observed_dependency_path: Vec<usize>,
185    pub dispatch_ns: u64,
186    pub tool_hash_ns: u64,
187    pub memory_blocked_ns: u64,
188    pub peak_reserved_ram: usize,
189    pub peak_reserved_vram: usize,
190    pub average_worker_concurrency: f64,
191    pub peak_worker_concurrency: usize,
192    pub saved_work_estimate_ns: u64,
193    /// CPU time summed across nodes with native OS accounting.
194    pub measured_cpu_ns: Option<u64>,
195    pub measured_cpu_average_cores: Option<f64>,
196    pub path_to_logs: PathBuf,
197    pub nodes: Vec<NodeReport>,
198}
199
200impl Report {
201    pub fn succeeded(&self) -> bool {
202        self.nodes.iter().all(|n| n.status.success())
203    }
204    pub fn print_summary(&self) {
205        let count = |status| self.nodes.iter().filter(|n| n.status == status).count();
206        println!(
207            "{:.3} ms wall · {:.3} ms dependency path · {} executed · {} cached · {} restored outputs · peak {} workers",
208            self.elapsed_ns as f64 / 1e6,
209            self.observed_dependency_path_ns as f64 / 1e6,
210            count(Status::Executed),
211            count(Status::Cached),
212            self.nodes
213                .iter()
214                .map(|n| n.restored_artifacts)
215                .sum::<usize>(),
216            self.peak_worker_concurrency
217        );
218        println!(
219            "  observed path: {}",
220            self.observed_dependency_path
221                .iter()
222                .map(|&id| self.nodes[id].name.as_str())
223                .collect::<Vec<_>>()
224                .join(" -> ")
225        );
226        println!(
227            "  estimated path {:.3} ms · memory admission wait {:.3} ms · tool hashing {:.3} ms · estimated skipped work {:.3} ms",
228            self.estimated_dependency_path_ns as f64 / 1e6,
229            self.memory_blocked_ns as f64 / 1e6,
230            self.tool_hash_ns as f64 / 1e6,
231            self.saved_work_estimate_ns as f64 / 1e6
232        );
233        for node in &self.nodes {
234            println!(
235                "  {:<22} {:?} {:.3} ms · queue {:.3} ms · {}",
236                node.name,
237                node.status,
238                node.elapsed_ns as f64 / 1e6,
239                node.queue_delay_ns as f64 / 1e6,
240                node.reason,
241            );
242            if let Some(error) = &node.error {
243                println!("    {error}");
244            }
245        }
246    }
247
248    /// Trace Event Format, importable in Perfetto. Timestamps are relative to the
249    /// scheduler start and represent host-side worker activity.
250    pub fn trace(&self) -> serde_json::Value {
251        let events: Vec<_> = self
252            .nodes
253            .iter()
254            .enumerate()
255            .map(|(id, n)| {
256                serde_json::json!({
257                    "ph": "X", "name": n.name, "pid": 1, "tid": id,
258                    "ts": n.started_ns as f64 / 1_000.0, "dur": n.elapsed_ns as f64 / 1_000.0,
259                    "args": {"status": n.status, "cache": n.cache, "queue_ns": n.queue_delay_ns}
260                })
261            })
262            .collect();
263        serde_json::json!({"traceEvents": events})
264    }
265}
266
267pub struct Graph {
268    nodes: Vec<Node>,
269    schedule: Scheduler,
270    estimated_path: u64,
271    estimated_chain: Vec<usize>,
272    order: Vec<usize>,
273    shared_inputs: Vec<Vec<Option<usize>>>,
274    shared_input_count: usize,
275    reuse_shared_inputs: bool,
276    fingerprint_workers: Option<usize>,
277    parallel_large_inputs: bool,
278    packed_outputs: bool,
279    reuse_dependency_outputs: bool,
280    hash_uncached_outputs: bool,
281    verify_local_hit_payload: bool,
282    revalidate_cache_misses: bool,
283    external_tool_files: Vec<Vec<PathBuf>>,
284    cache_bypass: bool,
285}
286impl Graph {
287    pub fn new(mut nodes: Vec<Node>) -> io::Result<Self> {
288        let mut names = BTreeSet::new();
289        for node in &mut nodes {
290            if node.name.is_empty() || !names.insert(node.name.clone()) || node.timeout_ms == 0 {
291                return Err(invalid("empty or duplicate node name, or zero timeout"));
292            }
293            if node.hard_ram_bytes > node.ram_bytes || (!node.gpu && node.vram_bytes != 0) {
294                return Err(invalid(
295                    "hard RAM and VRAM limits must agree with admission reservations",
296                ));
297            }
298            fs_safety::relative(&node.cwd, true)?;
299            if node.cache != Policy::Off
300                && (node.outputs.is_empty() || node.tool_version.is_empty())
301            {
302                return Err(invalid("cached actions require outputs and tool identity"));
303            }
304            let mut env_keys = BTreeSet::new();
305            if node.env.iter().any(|(key, val)| {
306                key.is_empty()
307                    || key.contains(['=', '\0'])
308                    || val.contains('\0')
309                    || !env_keys.insert(fs_safety::identity(key))
310            }) {
311                return Err(invalid("invalid or aliased environment key"));
312            }
313            for item in node.outputs.iter().chain(&node.inputs) {
314                fs_safety::relative(&item.path, false)?;
315            }
316            node.inputs.sort_unstable_by(|a, b| a.path.cmp(&b.path));
317            node.outputs.sort_unstable_by(|a, b| a.path.cmp(&b.path));
318            node.dependencies.sort_unstable();
319            node.dependencies.dedup();
320        }
321
322        let schedule = Scheduler::new(
323            nodes
324                .iter()
325                .enumerate()
326                .map(|(index, node)| {
327                    let mut routes = [None; 3];
328                    routes[usize::from(node.gpu)] = Some(Route {
329                        estimate: Duration::from_nanos(node.estimate_ns),
330                        memory: Memory {
331                            ram: node.ram_bytes,
332                            vram: node.vram_bytes,
333                        },
334                    });
335                    Operation {
336                        dependencies: node.dependencies.clone(),
337                        class: index as u64,
338                        bytes: 0,
339                        routes,
340                    }
341                })
342                .collect(),
343        )
344        .map_err(invalid)?;
345
346        let (order, dependencies) = analyze(&nodes);
347        let (estimated_path, estimated_chain) = longest(&nodes, &order, |id| nodes[id].estimate_ns);
348        let output_paths: Vec<_> = nodes
349            .iter()
350            .enumerate()
351            .flat_map(|(id, n)| {
352                n.outputs
353                    .iter()
354                    .map(move |item| (id, fs_safety::identity(&item.path)))
355            })
356            .collect();
357        for (index, (id, path)) in output_paths.iter().enumerate() {
358            if output_paths[..index]
359                .iter()
360                .any(|(_, prior)| overlap(path, prior))
361            {
362                return Err(invalid("output ownership overlaps another declaration"));
363            }
364            for (reader, job) in nodes.iter().enumerate() {
365                if job
366                    .inputs
367                    .iter()
368                    .any(|input| overlap(path, &fs_safety::identity(&input.path)))
369                    && !dependencies[reader].contains(id)
370                {
371                    return Err(invalid("an artifact reader must depend on the sole writer"));
372                }
373            }
374        }
375        if nodes.iter().enumerate().any(|(id, node)| {
376            node.cache != Policy::Off
377                && dependencies[id]
378                    .iter()
379                    .any(|&dep| nodes[dep].outputs.is_empty())
380        }) {
381            return Err(invalid(
382                "cached task depends on a process without declared outputs",
383            ));
384        }
385        let (shared_inputs, shared_input_count) = shared_layout(&nodes, &output_paths);
386        let external_tool_files = vec![Vec::new(); nodes.len()];
387        Ok(Self {
388            nodes,
389            schedule,
390            estimated_path,
391            estimated_chain,
392            order,
393            shared_inputs,
394            shared_input_count,
395            reuse_shared_inputs: true,
396            fingerprint_workers: None,
397            parallel_large_inputs: false,
398            packed_outputs: false,
399            reuse_dependency_outputs: true,
400            hash_uncached_outputs: true,
401            verify_local_hit_payload: true,
402            revalidate_cache_misses: true,
403            external_tool_files,
404            cache_bypass: false,
405        })
406    }
407
408    /// Expose the hash-read ablation without changing action keys.
409    pub fn reuse_shared_inputs(mut self, enabled: bool) -> Self {
410        self.reuse_shared_inputs = enabled;
411        self
412    }
413
414    /// Bound the number of parallel input fingerprints.
415    pub fn fingerprint_workers(mut self, workers: usize) -> io::Result<Self> {
416        if !(1..=64).contains(&workers) {
417            return Err(invalid("fingerprint_workers must be 1..=64"));
418        }
419        self.fingerprint_workers = Some(workers);
420        Ok(self)
421    }
422
423    /// Use ordered SHA-256 segments in an independent action-key namespace.
424    /// Directory entries and CAS blob identity keep ordinary SHA-256.
425    #[cfg(feature = "lab")]
426    pub fn parallel_large_inputs(mut self, enabled: bool) -> Self {
427        self.parallel_large_inputs = enabled;
428        self
429    }
430
431    #[cfg(feature = "lab")]
432    pub fn packed_outputs(mut self, enabled: bool) -> Self {
433        self.packed_outputs = enabled;
434        self
435    }
436
437    /// A producer's freshly verified tree can serve an exact declared input.
438    /// Disable this to benchmark a redundant second pass over the same bytes.
439    pub fn reuse_dependency_outputs(mut self, enabled: bool) -> Self {
440        self.reuse_dependency_outputs = enabled;
441        self
442    }
443
444    /// Keep path and file-kind checks even when hashes serve no cached descendant.
445    #[cfg(feature = "lab")]
446    pub fn hash_uncached_outputs(mut self, enabled: bool) -> Self {
447        self.hash_uncached_outputs = enabled;
448        self
449    }
450
451    /// On a single-output hit, a fully verified local copy can suffice.
452    /// The cache still verifies each archived byte before any restoration.
453    #[cfg(feature = "lab")]
454    pub fn verify_local_hit_payload(mut self, enabled: bool) -> Self {
455        self.verify_local_hit_payload = enabled;
456        self
457    }
458
459    /// Reproduce legacy measurements and cache keys in the lab runner.
460    #[cfg(feature = "lab")]
461    pub fn legacy_cache_publication(mut self) -> Self {
462        self.revalidate_cache_misses = false;
463        self
464    }
465
466    /// Add exact file identities for tool resources outside the workspace.
467    pub fn external_tool_files(mut self, node: usize, mut files: Vec<PathBuf>) -> io::Result<Self> {
468        let destination = self
469            .external_tool_files
470            .get_mut(node)
471            .ok_or_else(|| invalid("unknown node"))?;
472        files.sort_unstable();
473        files.dedup();
474        *destination = files;
475        Ok(self)
476    }
477
478    pub fn validate_tools(&self) -> io::Result<()> {
479        for node in &self.nodes {
480            check_tool(node)?;
481        }
482        for files in &self.external_tool_files {
483            for file in files {
484                check_tool_file(file)?;
485            }
486        }
487        Ok(())
488    }
489
490    /// Bypass cache reads and publication while retaining output transactions.
491    #[doc(hidden)]
492    pub fn bypass_cache(mut self) -> Self {
493        self.cache_bypass = true;
494        self
495    }
496
497    pub fn planned_critical_path(&self) -> (u64, impl Iterator<Item = &str>) {
498        (
499            self.estimated_path,
500            self.estimated_chain
501                .iter()
502                .map(|&id| self.nodes[id].name.as_str()),
503        )
504    }
505
506    #[doc(hidden)]
507    pub fn cost_path(&self, costs_ns: &[u64]) -> Option<u64> {
508        (costs_ns.len() == self.nodes.len())
509            .then(|| longest(&self.nodes, &self.order, |i| costs_ns[i]).0)
510    }
511
512    pub fn run(
513        &self,
514        workspace: &Path,
515        cache: Option<&Path>,
516        limits: Capacity,
517        cancel: &AtomicBool,
518    ) -> io::Result<Report> {
519        let wall = Instant::now();
520        if !self.cache_bypass
521            && self.revalidate_cache_misses
522            && cache.is_none()
523            && self.nodes.iter().any(|job| job.cache != Policy::Off)
524        {
525            return Err(invalid("a cache policy requires a cache directory"));
526        }
527        let root = fs_safety::absolute(workspace)?;
528        let internal = fs_safety::private_dir(&root, ".rustsy-process")?;
529        let lease = Lease::new(&internal, &root)?;
530        let cache = cache
531            .filter(|_| !self.cache_bypass)
532            .map(|p| -> io::Result<_> {
533                let local = p == workspace.join(".rustsy-process/cache");
534                let absolute = if local {
535                    fs_safety::private_dir(&internal, "cache")?
536                } else {
537                    fs_safety::absolute(p)?
538                };
539                if !local && (root.starts_with(&absolute) || absolute.starts_with(&root)) {
540                    return Err(invalid("workspace and shared cache must not overlap"));
541                }
542                Cache::new(
543                    &absolute,
544                    self.packed_outputs,
545                    self.verify_local_hit_payload,
546                )
547            })
548            .transpose()?;
549        let log_path = lease.logs.clone();
550        let previous: Vec<OnceLock<NodeReport>> =
551            (0..self.nodes.len()).map(|_| OnceLock::new()).collect();
552        let shared_hashes: Vec<OnceLock<SharedTree>> = (0..self.shared_input_count)
553            .map(|_| OnceLock::new())
554            .collect();
555        let tools = self
556            .nodes
557            .iter()
558            .map(check_tool)
559            .collect::<io::Result<Vec<_>>>()?;
560        let mut tool_digests = BTreeMap::new();
561        let mut tool_hash_ns = BTreeMap::new();
562        let mut resource_digests = BTreeMap::new();
563        let mut resources = vec![Vec::new(); self.nodes.len()];
564        let needs_pool = self.parallel_large_inputs
565            || self.nodes.iter().any(|job| {
566                job.cache != Policy::Off
567                    && job
568                        .inputs
569                        .iter()
570                        .chain(&job.outputs)
571                        .any(|item| item.kind == Kind::Directory)
572            });
573        let hashing = (cache.is_some() && needs_pool)
574            .then_some(())
575            .map(|_| {
576                rayon::ThreadPoolBuilder::new()
577                    .num_threads(self.fingerprint_workers.unwrap_or_else(|| {
578                        std::thread::available_parallelism()
579                            .map_or(1, usize::from)
580                            .min(12)
581                    }))
582                    .build()
583                    .map_err(io::Error::other)
584            })
585            .transpose()?;
586        if cache.is_some() {
587            for (id, (node, tool)) in self.nodes.iter().zip(&tools).enumerate() {
588                if node.cache != Policy::Off && !tool_digests.contains_key(tool) {
589                    let start = Instant::now();
590                    let digest = if self.parallel_large_inputs {
591                        artifact::fingerprint_file(
592                            tool,
593                            hashing
594                                .as_ref()
595                                .ok_or_else(|| invalid("missing segment worker pool"))?,
596                        )?
597                    } else {
598                        artifact::copy_hash(tool, io::sink())?
599                    };
600                    tool_digests.insert(tool.clone(), digest);
601                    tool_hash_ns.insert(tool.clone(), ns(start.elapsed()));
602                }
603                if node.cache != Policy::Off {
604                    for file in &self.external_tool_files[id] {
605                        let path = check_tool_file(file)?;
606                        let digest = match resource_digests.entry(path.clone()) {
607                            std::collections::btree_map::Entry::Occupied(entry) => *entry.get(),
608                            std::collections::btree_map::Entry::Vacant(entry) => {
609                                let start = Instant::now();
610                                let digest = artifact::copy_hash(&path, io::sink())?;
611                                *tool_hash_ns.entry(path.clone()).or_default() +=
612                                    ns(start.elapsed());
613                                *entry.insert(digest)
614                            }
615                        };
616                        resources[id].push((path, digest));
617                    }
618                }
619            }
620        }
621        let aggregate_tool_hash_ns = tool_hash_ns
622            .values()
623            .copied()
624            .fold(0u64, u64::saturating_add);
625        let mut required_hashes = vec![self.hash_uncached_outputs; self.nodes.len()];
626        if cache.is_some() && !self.hash_uncached_outputs {
627            for &id in self.order.iter().rev() {
628                if required_hashes[id] || self.nodes[id].cache != Policy::Off {
629                    required_hashes[id] = true;
630                    for &dep in &self.nodes[id].dependencies {
631                        required_hashes[dep] = true;
632                    }
633                }
634            }
635        }
636        let setup_ns = ns(wall.elapsed());
637        let result = self
638            .schedule
639            .execute(
640                limits,
641                &mut History::default(),
642                |_| Ok(()),
643                |_, id, _| {
644                    let job = &self.nodes[id];
645                    let mut report = NodeReport::new(job);
646                    if cancel.load(Ordering::Acquire) {
647                        report.status = Status::Cancelled;
648                    } else if job
649                        .dependencies
650                        .iter()
651                        .any(|&p| !previous[p].get().unwrap().status.success())
652                    {
653                        report.status = Status::Blocked;
654                    } else {
655                        let context = Context {
656                            root: &root,
657                            internal: &lease.transactions,
658                            cache: cache.as_ref(),
659                            cancel,
660                            log_path: &log_path,
661                            previous: &previous,
662                            hashing: hashing.as_ref(),
663                            shared_slots: &self.shared_inputs[id],
664                            shared_hashes: &shared_hashes,
665                            reuse_shared_inputs: self.reuse_shared_inputs,
666                            parallel_large_inputs: self.parallel_large_inputs,
667                            packed_outputs: self.packed_outputs,
668                            reuse_dependency_outputs: self.reuse_dependency_outputs,
669                            hash_output: required_hashes[id],
670                            revalidate_cache_misses: self.revalidate_cache_misses,
671                            external_tool_files: &self.external_tool_files[id],
672                            tool_resources: &resources[id],
673                        };
674                        if let Err(err) = context.node(
675                            job,
676                            id,
677                            &tools[id],
678                            tool_digests.get(&tools[id]),
679                            &mut report,
680                        ) {
681                            report.status = Status::Failed;
682                            report.error = Some(err.to_string());
683                        }
684                    }
685                    report.reason = report.reason();
686                    previous[id]
687                        .set(report)
688                        .map_err(|_| "duplicate process completion".into())
689                },
690            )
691            .map_err(io::Error::other)?;
692
693        let mut nodes = previous
694            .into_iter()
695            .map(|n| n.into_inner().unwrap())
696            .collect::<Vec<_>>();
697        let mut endpoints = Vec::with_capacity(nodes.len() * 2);
698        let mut work = 0u64;
699        let mut saved_work = 0u64;
700        for sample in &result.samples {
701            let n = &mut nodes[sample.task];
702            n.ready_ns = ns(sample.ready_at);
703            n.started_ns = ns(sample.started_at);
704            n.elapsed_ns = ns(sample.elapsed);
705            n.queue_delay_ns = n.started_ns.saturating_sub(n.ready_ns);
706            if n.elapsed_ns > 0 {
707                endpoints.push((n.started_ns, true));
708                endpoints.push((n.started_ns.saturating_add(n.elapsed_ns), false));
709            }
710            work = work.saturating_add(n.elapsed_ns);
711            if n.status == Status::Cached {
712                saved_work = saved_work.saturating_add(
713                    self.nodes[sample.task]
714                        .estimate_ns
715                        .saturating_sub(n.elapsed_ns),
716                );
717            }
718        }
719        endpoints.sort_unstable();
720        let mut peak = 0;
721        let mut live = 0;
722        for (_, add) in endpoints {
723            if add {
724                live += 1;
725                peak = peak.max(live);
726            } else {
727                live -= 1;
728            }
729        }
730        let elapsed = ns(wall.elapsed());
731        let (observed_dependency_path_ns, observed_dependency_path) =
732            longest(&self.nodes, &self.order, |id| nodes[id].elapsed_ns);
733        let measured_cpu_ns = nodes
734            .iter()
735            .filter_map(|node| node.cpu_ns)
736            .reduce(u64::saturating_add);
737        Ok(Report {
738            elapsed_ns: elapsed,
739            setup_ns,
740            recovered_transactions: lease.recovered,
741            estimated_dependency_path_ns: self.estimated_path,
742            observed_dependency_path_ns,
743            estimated_dependency_path: self.estimated_chain.clone(),
744            observed_dependency_path,
745            dispatch_ns: ns(result.dispatch_time),
746            tool_hash_ns: aggregate_tool_hash_ns,
747            memory_blocked_ns: ns(result.memory_blocked),
748            peak_reserved_ram: result.peak.ram,
749            peak_reserved_vram: result.peak.vram,
750            average_worker_concurrency: work as f64 / elapsed.max(1) as f64,
751            peak_worker_concurrency: peak,
752            saved_work_estimate_ns: saved_work,
753            measured_cpu_ns,
754            measured_cpu_average_cores: measured_cpu_ns
755                .map(|time| time as f64 / elapsed.max(1) as f64),
756            path_to_logs: log_path,
757            nodes,
758        })
759    }
760}
761
762fn overlap(a: &str, b: &str) -> bool {
763    a == b
764        || a.strip_prefix(b).is_some_and(|rest| rest.starts_with('/'))
765        || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
766}
767
768fn shared_layout(nodes: &[Node], outputs: &[(usize, String)]) -> (Vec<Vec<Option<usize>>>, usize) {
769    let mut counts = BTreeMap::new();
770    for job in nodes.iter().filter(|job| job.cache != Policy::Off) {
771        for input in &job.inputs {
772            *counts.entry((&input.path, input.kind)).or_insert(0usize) += 1;
773        }
774    }
775    let identities: BTreeMap<_, _> = counts
776        .into_iter()
777        .filter_map(|(key, count)| (count > 1).then_some(key))
778        .filter(|(path, _)| {
779            let path = fs_safety::identity(path);
780            !outputs.iter().any(|(_, out)| overlap(&path, out))
781        })
782        .enumerate()
783        .map(|(slot, key)| (key, slot))
784        .collect();
785    let layout = nodes
786        .iter()
787        .map(|job| {
788            job.inputs
789                .iter()
790                .map(|input| identities.get(&(&input.path, input.kind)).copied())
791                .collect()
792        })
793        .collect();
794    (layout, identities.len())
795}
796
797fn analyze(nodes: &[Node]) -> (Vec<usize>, Vec<BTreeSet<usize>>) {
798    let mut pending: Vec<_> = nodes.iter().map(|n| n.dependencies.len()).collect();
799    let mut successors = vec![Vec::new(); nodes.len()];
800    for (id, node) in nodes.iter().enumerate() {
801        for &dep in &node.dependencies {
802            successors[dep].push(id);
803        }
804    }
805    let mut queue: Vec<_> = pending
806        .iter()
807        .enumerate()
808        .filter_map(|(i, &n)| (n == 0).then_some(i))
809        .collect();
810    let mut seen = 0;
811    let mut deps = vec![BTreeSet::new(); nodes.len()];
812    // Scheduler::new already validates indices and cycles.
813    while let Some(&id) = queue.get(seen) {
814        seen += 1;
815        let node = &nodes[id];
816        for &dep in &node.dependencies {
817            let ancestors = deps[dep].clone();
818            deps[id].extend(ancestors);
819            deps[id].insert(dep);
820        }
821        for &next in &successors[id] {
822            pending[next] -= 1;
823            if pending[next] == 0 {
824                queue.push(next);
825            }
826        }
827    }
828    (queue, deps)
829}
830
831fn longest(nodes: &[Node], order: &[usize], cost: impl Fn(usize) -> u64) -> (u64, Vec<usize>) {
832    let mut best = vec![0u64; nodes.len()];
833    let mut parents = vec![None; nodes.len()];
834    for &id in order {
835        let parent = nodes[id]
836            .dependencies
837            .iter()
838            .copied()
839            .max_by_key(|&dep| best[dep]);
840        parents[id] = parent;
841        best[id] = cost(id).saturating_add(parent.map_or(0, |dep| best[dep]));
842    }
843    let mut tip = order.iter().copied().max_by_key(|&id| best[id]);
844    let duration = tip.map_or(0, |id| best[id]);
845    let mut chain = Vec::new();
846    while let Some(id) = tip {
847        chain.push(id);
848        tip = parents[id];
849    }
850    chain.reverse();
851    (duration, chain)
852}
853
854fn check_tool(job: &Node) -> io::Result<PathBuf> {
855    let tool = check_tool_file(&job.executable)?;
856    #[cfg(windows)]
857    if !tool
858        .extension()
859        .and_then(|value| value.to_str())
860        .is_some_and(|value| value.eq_ignore_ascii_case("exe"))
861    {
862        return Err(invalid("use an explicit .exe for direct Windows launch"));
863    }
864    Ok(tool)
865}
866
867fn check_tool_file(path: &Path) -> io::Result<PathBuf> {
868    let path = fs_safety::absolute(path)?;
869    if !fs_safety::node_md(&path)?.is_file() {
870        return Err(invalid("expected a regular tool file"));
871    }
872    Ok(path)
873}
874
875fn ns(time: Duration) -> u64 {
876    time.as_nanos().min(u128::from(u64::MAX)) as u64
877}
878
879struct Lease {
880    _file: fs::File,
881    marker: PathBuf,
882    logs: PathBuf,
883    transactions: PathBuf,
884    recovered: usize,
885}
886impl Lease {
887    fn new(internal: &Path, workspace: &Path) -> io::Result<Self> {
888        let path = internal.join("active.lock");
889        match fs_safety::node_md(&path) {
890            Ok(md) if md.is_file() => {}
891            Ok(_) => return Err(invalid("workspace lock must be a regular file")),
892            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
893            Err(e) => return Err(e),
894        }
895        let mut options = fs::OpenOptions::new();
896        options.read(true).write(true).create(true).truncate(false);
897        #[cfg(windows)]
898        {
899            use std::os::windows::fs::OpenOptionsExt;
900            options.share_mode(3).custom_flags(0x0020_0000); // no delete sharing, open reparse point
901        }
902        #[cfg(unix)]
903        {
904            use std::os::unix::fs::OpenOptionsExt;
905            options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
906        }
907        let file = options.open(&path)?;
908        if !fs_safety::checked(&path, file.metadata()?)?.is_file() {
909            return Err(invalid("workspace lock must be a regular file"));
910        }
911        file.try_lock().map_err(|error| match error {
912            std::fs::TryLockError::WouldBlock => io::Error::new(
913                io::ErrorKind::WouldBlock,
914                "workspace already has an active RustSy run",
915            ),
916            std::fs::TryLockError::Error(e) => e,
917        })?;
918        let legacy = internal.join("active");
919        let recovered = match fs::symlink_metadata(&legacy) {
920            Ok(_) => recovery::resume(internal, workspace, &legacy)?,
921            Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
922            Err(e) => return Err(e),
923        };
924        let logs = Scratch::new(internal)?.persist();
925        let transactions = fs_safety::private_dir(&logs, "transactions")?;
926        // The marker is published atomically and coordinates with older runners.
927        use std::io::Write;
928        let staged = logs.join("run-marker");
929        let mut marker = fs::File::create_new(&staged)?;
930        writeln!(
931            marker,
932            "rustsy-7:{}",
933            logs.file_name().unwrap().to_string_lossy()
934        )?;
935        marker.sync_all()?;
936        drop(marker);
937        fs::hard_link(staged, &legacy)?;
938        Ok(Self {
939            _file: file,
940            marker: legacy,
941            logs,
942            transactions,
943            recovered,
944        })
945    }
946}
947impl Drop for Lease {
948    fn drop(&mut self) {
949        if !recovery::requires_recovery(&self.transactions) {
950            let _ = fs::remove_file(&self.marker);
951        }
952    }
953}
954
955struct Context<'a> {
956    root: &'a Path,
957    internal: &'a Path,
958    cache: Option<&'a Cache>,
959    cancel: &'a AtomicBool,
960    log_path: &'a Path,
961    previous: &'a [OnceLock<NodeReport>],
962    hashing: Option<&'a rayon::ThreadPool>,
963    shared_slots: &'a [Option<usize>],
964    shared_hashes: &'a [OnceLock<SharedTree>],
965    reuse_shared_inputs: bool,
966    parallel_large_inputs: bool,
967    packed_outputs: bool,
968    reuse_dependency_outputs: bool,
969    hash_output: bool,
970    revalidate_cache_misses: bool,
971    external_tool_files: &'a [PathBuf],
972    tool_resources: &'a [(PathBuf, Hash)],
973}
974
975type SharedTree = Result<Vec<u8>, (io::ErrorKind, String)>;
976
977impl Context<'_> {
978    fn node(
979        &self,
980        job: &Node,
981        id: usize,
982        tool: &Path,
983        digest: Option<&Hash>,
984        report: &mut NodeReport,
985    ) -> io::Result<()> {
986        let cwd = fs_safety::path(self.root, &job.cwd, false)?;
987        if !fs_safety::node_md(&cwd)?.is_dir() {
988            return Err(invalid("cwd is not a directory"));
989        }
990        let selected = self.cache.filter(|_| job.cache != Policy::Off);
991        let action = match selected {
992            Some(cache) => {
993                let start = Instant::now();
994                let hash = self.key(
995                    job,
996                    tool,
997                    digest.ok_or_else(|| invalid("missing tool hash"))?,
998                    false,
999                )?;
1000                report.hashing_ns = ns(start.elapsed());
1001                report.key = Some(artifact::text(&hash));
1002                let lookup = Instant::now();
1003                let restored =
1004                    cache.restore(self.root, self.internal, hash, &job.outputs, self.hashing);
1005                report.cache_lookup_restore_ns = ns(lookup.elapsed());
1006                match restored {
1007                    Ok((outputs, restored, payloads_verified)) => {
1008                        report.status = Status::Cached;
1009                        report.cache = CacheStatus::Hit;
1010                        report.cache_payloads_verified = payloads_verified;
1011                        report.outputs = outputs;
1012                        report.restored_artifacts = restored.len();
1013                        report.restored_paths = restored;
1014                        return Ok(());
1015                    }
1016                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
1017                        report.cache = CacheStatus::Miss
1018                    }
1019                    Err(e) if e.kind() == io::ErrorKind::InvalidData => {
1020                        report.cache = CacheStatus::Corrupted
1021                    }
1022                    Err(e) => return Err(e),
1023                }
1024                Some((cache, hash))
1025            }
1026            None => None,
1027        };
1028
1029        // Hits already fully validate local paths or stage the restored outputs.
1030        // A miss still has to reject redirected paths before executing the tool.
1031        for out in &job.outputs {
1032            let path = fs_safety::path(self.root, &out.path, true)?;
1033            match fs_safety::node_md(&path) {
1034                Ok(_) => {
1035                    artifact::describe(self.root, out, |_| Ok([0; 32]))?;
1036                }
1037                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
1038                Err(e) => return Err(e),
1039            }
1040        }
1041
1042        let log = fs_safety::private_dir(self.log_path, &format!("node-{id}"))?;
1043        if self.cancel.load(Ordering::Acquire) {
1044            report.status = Status::Cancelled;
1045            return Ok(());
1046        }
1047        let mut outputs = if job.cache == Policy::Off {
1048            None
1049        } else {
1050            Some(Quarantine::new(self.internal, self.root, &job.outputs)?)
1051        };
1052        let launch_scope = Scratch::new(self.internal)?;
1053        let busy = launch_scope.0.join("child-active");
1054        fs::File::create_new(&busy)?;
1055        let start = Instant::now();
1056        let execution = launch::run(job, tool, &cwd, &log, self.cancel);
1057        if let Err(err) = fs::remove_file(&busy) {
1058            launch_scope.persist();
1059            return Err(err);
1060        }
1061        let execution = execution?;
1062        report.process_ns = ns(start.elapsed());
1063        report.status = execution.status;
1064        report.exit_code = execution.exit_code;
1065        report.cpu_ns = execution.cpu_ns;
1066        report.peak_job_commit_bytes = execution.peak_job_commit_bytes;
1067        if !execution.status.success() {
1068            return Ok(());
1069        }
1070        let start = Instant::now();
1071        report.outputs = if let Some((cache, hash)) = action {
1072            if self.revalidate_cache_misses {
1073                let current_tool = check_tool(job)?;
1074                let current_digest = if self.parallel_large_inputs {
1075                    artifact::fingerprint_file(
1076                        &current_tool,
1077                        self.hashing
1078                            .ok_or_else(|| invalid("missing fingerprint pool"))?,
1079                    )?
1080                } else {
1081                    artifact::copy_hash(&current_tool, io::sink())?
1082                };
1083                let current = self.key(job, &current_tool, &current_digest, true)?;
1084                report.hashing_ns = report.hashing_ns.saturating_add(ns(start.elapsed()));
1085                if current != hash {
1086                    return Err(invalid(
1087                        "declared inputs or tools changed during the action; cache publication refused",
1088                    ));
1089                }
1090            }
1091            if self.cancel.load(Ordering::Acquire) {
1092                report.status = Status::Cancelled;
1093                return Ok(());
1094            }
1095            let store = Instant::now();
1096            let outputs = cache.capture(self.root, &job.outputs, hash, self.hashing)?;
1097            report.cache_store_ns = ns(store.elapsed());
1098            outputs
1099        } else if !self.hash_output {
1100            for output in &job.outputs {
1101                artifact::describe(self.root, output, |_| Ok([0; 32]))?;
1102            }
1103            Vec::new()
1104        } else {
1105            job.outputs
1106                .iter()
1107                .map(|out| {
1108                    artifact::describe(self.root, out, |p| artifact::copy_hash(p, io::sink()))
1109                })
1110                .collect::<io::Result<_>>()?
1111        };
1112        if selected.is_none() && self.hash_output {
1113            report.hashing_ns = report.hashing_ns.saturating_add(ns(start.elapsed()));
1114        }
1115        if let Some(guard) = &mut outputs {
1116            recovery::commit(&guard.staged.as_ref().unwrap().0)?;
1117            guard.committed = true;
1118        }
1119        Ok(())
1120    }
1121
1122    fn key(&self, job: &Node, tool: &Path, digest: &Hash, fresh: bool) -> io::Result<Hash> {
1123        let mut action = ActionKey::default();
1124        action.include(
1125            b"schema",
1126            if self.parallel_large_inputs {
1127                b"process-artifacts-segmented-1"
1128            } else {
1129                b"process-artifacts-1"
1130            },
1131        );
1132        if self.packed_outputs {
1133            action.include(b"cas-layout", b"indexed-pack-v1");
1134        }
1135        if self.revalidate_cache_misses {
1136            action.include(b"publication", b"revalidated-v1");
1137        }
1138        action.include(
1139            b"platform",
1140            format!("{}/{}", std::env::consts::OS, std::env::consts::ARCH).as_bytes(),
1141        );
1142        action.include(
1143            b"path-scope",
1144            if job.cache == Policy::Portable {
1145                b"portable".as_slice()
1146            } else {
1147                self.root.as_os_str().as_encoded_bytes()
1148            },
1149        );
1150        action.include(b"cwd", job.cwd.as_bytes());
1151        action.include(b"tool", tool.as_os_str().as_encoded_bytes());
1152        action.include(b"tool-bytes", digest);
1153        action.include(b"tool-version", job.tool_version.as_bytes());
1154        if fresh {
1155            for file in self.external_tool_files {
1156                let file = check_tool_file(file)?;
1157                action.include(b"external-tool-file", file.as_os_str().as_encoded_bytes());
1158                action.include(
1159                    b"external-tool-bytes",
1160                    &artifact::copy_hash(&file, io::sink())?,
1161                );
1162            }
1163        } else {
1164            for (file, digest) in self.tool_resources {
1165                action.include(b"external-tool-file", file.as_os_str().as_encoded_bytes());
1166                action.include(b"external-tool-bytes", digest);
1167            }
1168        }
1169        action.include(b"args", &serde_json::to_vec(&job.args)?);
1170        action.include(b"env", &serde_json::to_vec(&job.env)?);
1171        action.include(
1172            b"resource-contract",
1173            &serde_json::to_vec(&(job.gpu, job.ram_bytes, job.hard_ram_bytes, job.vram_bytes))?,
1174        );
1175        action.include(b"declared-outputs", &serde_json::to_vec(&job.outputs)?);
1176        for &dep in &job.dependencies {
1177            let previous = &self.previous[dep].get().unwrap().outputs;
1178            if fresh {
1179                for tree in previous {
1180                    let declaration = Artifact {
1181                        path: tree.path.clone(),
1182                        kind: if tree.entries[0].file.is_some() {
1183                            Kind::File
1184                        } else {
1185                            Kind::Directory
1186                        },
1187                    };
1188                    if artifact::hash_tree(self.root, &declaration, self.hashing)? != *tree {
1189                        return Err(invalid("a dependency artifact changed during the action"));
1190                    }
1191                }
1192            }
1193            action.include(b"dependency-artifacts", &serde_json::to_vec(previous)?);
1194        }
1195        for (item, &slot) in job.inputs.iter().zip(self.shared_slots) {
1196            if (fresh || self.reuse_dependency_outputs)
1197                && !(self.parallel_large_inputs && item.kind == Kind::File)
1198                && let Some(tree) = job
1199                    .dependencies
1200                    .iter()
1201                    .flat_map(|&id| &self.previous[id].get().unwrap().outputs)
1202                    .find(|tree| {
1203                        tree.path == item.path
1204                            && tree.entries[0].file.is_some() == (item.kind == Kind::File)
1205                    })
1206            {
1207                action.include(b"input", &serde_json::to_vec(tree)?);
1208                continue;
1209            }
1210            let encode = || -> io::Result<Vec<u8>> {
1211                let tree = artifact::hash_input(
1212                    self.root,
1213                    item,
1214                    self.hashing,
1215                    self.parallel_large_inputs,
1216                )?;
1217                Ok(serde_json::to_vec(&tree)?)
1218            };
1219            if !fresh
1220                && self.reuse_shared_inputs
1221                && let Some(slot) = slot
1222            {
1223                let encoded = self.shared_hashes[slot]
1224                    .get_or_init(|| encode().map_err(|e| (e.kind(), e.to_string())))
1225                    .as_ref()
1226                    .map_err(|(kind, message)| io::Error::new(*kind, message.clone()))?;
1227                action.include(b"input", encoded);
1228            } else {
1229                action.include(b"input", &encode()?);
1230            }
1231        }
1232        Ok(action.finish())
1233    }
1234}
1235
1236struct Quarantine {
1237    staged: Option<Scratch>,
1238    items: Vec<(PathBuf, Option<PathBuf>)>,
1239    committed: bool,
1240}
1241impl Quarantine {
1242    fn new(internal: &Path, root: &Path, outputs: &[Artifact]) -> io::Result<Self> {
1243        let mut guard = Self {
1244            staged: Some(Scratch::new(internal)?),
1245            items: Vec::new(),
1246            committed: false,
1247        };
1248        recovery::prepare(
1249            &guard.staged.as_ref().unwrap().0,
1250            root,
1251            outputs
1252                .iter()
1253                .enumerate()
1254                .map(|(index, output)| (index, output.path.as_str())),
1255        )?;
1256        for (index, output) in outputs.iter().enumerate() {
1257            let path = fs_safety::path(root, &output.path, true)?;
1258            let backup = match fs_safety::node_md(&path) {
1259                Ok(_) => {
1260                    let target = guard
1261                        .staged
1262                        .as_ref()
1263                        .unwrap()
1264                        .0
1265                        .join(format!("old-{index}"));
1266                    fs::rename(&path, &target)?;
1267                    Some(target)
1268                }
1269                Err(e) if e.kind() == io::ErrorKind::NotFound => None,
1270                Err(e) => return Err(e),
1271            };
1272            guard.items.push((path, backup));
1273        }
1274        Ok(guard)
1275    }
1276}
1277impl Drop for Quarantine {
1278    fn drop(&mut self) {
1279        if self.committed {
1280            return;
1281        }
1282        let scratch = self.staged.as_ref().unwrap();
1283        for (index, (out, backup)) in self.items.iter().enumerate().rev() {
1284            let displaced = scratch.0.join(format!("failed-{index}"));
1285            let replaced = match fs::rename(out, displaced) {
1286                Ok(()) => true,
1287                Err(e) => e.kind() == io::ErrorKind::NotFound,
1288            };
1289            if !replaced
1290                || backup
1291                    .as_ref()
1292                    .is_some_and(|old| fs::rename(old, out).is_err())
1293            {
1294                // Retain backups for manual recovery if the underlying filesystem refused rollback.
1295                if let Some(staged) = self.staged.take() {
1296                    eprintln!(
1297                        "process output recovery needed at {}",
1298                        staged.persist().display()
1299                    );
1300                }
1301                return;
1302            }
1303        }
1304    }
1305}
1306
1307#[cfg(test)]
1308mod tests {
1309    use super::*;
1310
1311    #[test]
1312    fn shared_snapshots_exclude_any_declared_writer() {
1313        let parse = |name: &str| -> Node {
1314            serde_json::from_value(serde_json::json!({
1315                "name": name, "executable": "/tool", "tool_version": "1", "cwd": ".",
1316                "inputs": [{"path":"src","kind":"directory"},
1317                           {"path":"generated","kind":"directory"}],
1318                "cache": "portable", "timeout_ms": 1, "estimate_ns": 1
1319            }))
1320            .unwrap()
1321        };
1322        let nodes = [parse("one"), parse("two")];
1323        let (slots, count) = shared_layout(&nodes, &[(2, fs_safety::identity("generated/value"))]);
1324        assert_eq!(count, 1);
1325        assert_eq!(slots, [vec![Some(0), None], vec![Some(0), None]]);
1326    }
1327}