rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use rustsy_engine::adaptive::{Capacity, Memory};
use rustsy_process::{Artifact, Graph, Node, Policy};
use serde::Deserialize;
use sha2::{Digest, Sha256};
mod decision;
use std::{
    collections::{BTreeMap, BTreeSet},
    env,
    fs::{self, File},
    io::{self, BufReader, Write},
    path::{Path, PathBuf},
    process::ExitCode,
    sync::atomic::{AtomicBool, Ordering},
    time::Instant,
};

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Manifest {
    version: u32,
    workers: Option<usize>,
    fingerprint_workers: Option<usize>,
    ram_mib: Option<usize>,
    #[serde(default)]
    gpu_workers: usize,
    #[serde(default)]
    vram_mib: usize,
    cache_dir: Option<PathBuf>,
    tools: BTreeMap<String, Tool>,
    tasks: Vec<Task>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Tool {
    path: PathBuf,
    version: String,
    files: Option<Vec<PathBuf>>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Task {
    name: String,
    tool: String,
    cwd: Option<String>,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    depends_on: Vec<String>,
    #[serde(default)]
    inputs: Vec<Artifact>,
    #[serde(default)]
    outputs: Vec<Artifact>,
    #[serde(default)]
    env: BTreeMap<String, String>,
    #[serde(default)]
    inherit_env: Vec<String>,
    #[serde(default)]
    deterministic: bool,
    #[serde(default)]
    cache: Policy,
    timeout_ms: Option<u64>,
    estimate_ms: Option<u64>,
    ram_mib: Option<usize>,
    #[serde(default)]
    hard_ram_mib: usize,
    #[serde(default)]
    gpu: bool,
    #[serde(default)]
    vram_mib: usize,
}

struct Loaded {
    manifest: Manifest,
    root: PathBuf,
    cache: Option<PathBuf>,
    graph: Graph,
    capacity: Capacity,
    contract: String,
}

fn invalid(message: impl Into<String>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidInput, message.into())
}

fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<T> {
    Ok(serde_json::from_reader(BufReader::new(File::open(path)?))?)
}

fn mib(value: usize) -> io::Result<usize> {
    value
        .checked_mul(1024 * 1024)
        .ok_or_else(|| invalid("MiB value overflows"))
}

impl Loaded {
    fn read(path: &Path) -> io::Result<Self> {
        let path = fs::canonicalize(path)?;
        let root = path
            .parent()
            .ok_or_else(|| invalid("manifest has no project directory"))?
            .to_owned();
        let definition = fs::read(&path)?;
        let manifest: Manifest = serde_json::from_slice(&definition)?;
        let mut identity = Sha256::new();
        identity.update((root.as_os_str().as_encoded_bytes().len() as u64).to_le_bytes());
        identity.update(root.as_os_str().as_encoded_bytes());
        identity.update(&definition);
        if manifest.version != 1 || manifest.tasks.is_empty() {
            return Err(invalid("expected schema version 1 and at least one task"));
        }
        let names = manifest
            .tasks
            .iter()
            .enumerate()
            .map(|(id, task)| (task.name.as_str(), id))
            .collect::<BTreeMap<_, _>>();
        let mut nodes = Vec::with_capacity(manifest.tasks.len());
        let mut tool_files = Vec::with_capacity(manifest.tasks.len());
        let mut use_cache = false;
        let workers = manifest.workers.unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map_or(1, usize::from)
                .min(12)
        });
        if workers == 0 || workers > 64 || manifest.gpu_workers > 64 {
            return Err(invalid("worker limits: 1..=64 CPU, 0..=64 GPU"));
        }
        let capacity = Capacity {
            workers: [workers, manifest.gpu_workers, 0],
            memory: Memory {
                ram: mib(manifest.ram_mib.unwrap_or(2048))?,
                vram: mib(manifest.vram_mib)?,
            },
        };
        for task in &manifest.tasks {
            let tool = manifest
                .tools
                .get(&task.tool)
                .ok_or_else(|| invalid(format!("{}: unknown tool {}", task.name, task.tool)))?;
            let cache = match task.cache {
                Policy::Off => Policy::Off,
                Policy::Local if task.deterministic && tool.files.is_some() => {
                    use_cache = true;
                    Policy::Local
                }
                _ => {
                    return Err(invalid(format!(
                        "{}: cache requires local policy, deterministic: true and an explicit tool files list",
                        task.name
                    )));
                }
            };
            let mut environment = task.env.clone();
            let mut inherited = BTreeSet::new();
            for name in &task.inherit_env {
                if name.is_empty()
                    || name.contains(['=', '\0'])
                    || !inherited.insert(name)
                    || environment.contains_key(name)
                {
                    return Err(invalid(format!(
                        "{}: invalid or duplicate inherited environment key {name}",
                        task.name
                    )));
                }
                if let Ok(content) = env::var(name) {
                    environment.insert(name.clone(), content);
                } else if env::var_os(name).is_some() {
                    return Err(invalid(format!(
                        "{}: non-Unicode environment variable {name}",
                        task.name
                    )));
                }
            }
            let index = usize::from(task.gpu);
            let ram_bytes = mib(task.ram_mib.unwrap_or(64))?;
            let vram_bytes = mib(task.vram_mib)?;
            if capacity.workers[index] == 0
                || ram_bytes > capacity.memory.ram
                || vram_bytes > capacity.memory.vram
            {
                return Err(invalid(format!(
                    "{}: cannot be admitted within worker and memory limits",
                    task.name
                )));
            }
            let deps =
                task.depends_on
                    .iter()
                    .map(|name| {
                        names.get(name.as_str()).copied().ok_or_else(|| {
                            invalid(format!("{}: unknown dependency {name}", task.name))
                        })
                    })
                    .collect::<io::Result<_>>()?;
            nodes.push(Node {
                name: task.name.clone(),
                executable: root.join(&tool.path),
                tool_version: tool.version.clone(),
                cwd: task.cwd.clone().unwrap_or_else(|| ".".into()),
                args: task.args.clone(),
                inputs: task.inputs.clone(),
                outputs: task.outputs.clone(),
                dependencies: deps,
                env: environment,
                cache,
                ram_bytes,
                hard_ram_bytes: mib(task.hard_ram_mib)?,
                gpu: task.gpu,
                vram_bytes,
                timeout_ms: task.timeout_ms.unwrap_or(60_000),
                estimate_ns: task
                    .estimate_ms
                    .unwrap_or(100)
                    .checked_mul(1_000_000)
                    .ok_or_else(|| invalid("estimate_ms overflows"))?,
            });
            tool_files.push(
                tool.files
                    .iter()
                    .flatten()
                    .map(|path| root.join(path))
                    .collect(),
            );
        }
        let mut graph = Graph::new(nodes)?;
        if let Some(workers) = manifest.fingerprint_workers {
            graph = graph.fingerprint_workers(workers)?;
        }
        for (id, files) in tool_files.into_iter().enumerate() {
            graph = graph.external_tool_files(id, files)?;
        }
        let cache = use_cache.then(|| {
            root.join(
                manifest
                    .cache_dir
                    .as_deref()
                    .unwrap_or_else(|| Path::new(".rustsy-process/cache")),
            )
        });
        Ok(Self {
            manifest,
            root,
            cache,
            graph,
            capacity,
            contract: format!("{:x}", identity.finalize()),
        })
    }
}

const DEMO: &str = "import sys\nwith open(sys.argv[1], encoding='utf-8') as f:\n    result = f.read().upper()\nwith open(sys.argv[2], 'w', newline='\\n', encoding='utf-8') as f:\n    f.write(result)\n";

fn init(tool: &Path) -> io::Result<()> {
    let python = fs::canonicalize(tool)?;
    if !python.is_file() {
        return Err(invalid("init expects the path to a Python 3 executable"));
    }
    let manifest = Path::new("rustsy.json");
    let script = Path::new("rustsy_demo.py");
    let input = Path::new("rustsy_input.txt");
    for path in [manifest, script, input, Path::new("rustsy_output.txt")] {
        match fs::symlink_metadata(path) {
            Ok(_) => {
                return Err(invalid(format!(
                    "{} already exists; use an empty directory",
                    path.display()
                )));
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
    }
    File::create_new(script)?.write_all(DEMO.as_bytes())?;
    File::create_new(input)?.write_all(b"Hello from RustSy\n")?;
    let config = serde_json::json!({
        "version": 1,
        "tools": {"python": {"path": python, "version": "Python 3"}},
        "tasks": [{"name": "uppercase", "tool": "python",
            "args": ["-I", "-S", "-B", "rustsy_demo.py", "rustsy_input.txt", "rustsy_output.txt"],
            "inherit_env": ["SystemRoot"],
            "inputs": [{"path":"rustsy_demo.py","kind":"file"},{"path":"rustsy_input.txt","kind":"file"}],
            "outputs": [{"path":"rustsy_output.txt","kind":"file"}]}]
    });
    serde_json::to_writer_pretty(File::create_new(manifest)?, &config)?;
    println!("Created rustsy.json. Run rustsy-process doctor, then rustsy-process run.");
    Ok(())
}

fn help() {
    println!(
        "RustSy Process Graph {}\n\
        Usage: rustsy-process init PYTHON_EXECUTABLE\n\
        \x20      rustsy-process <run|graph|doctor> [MANIFEST] [--json|--trace]\n\
        \x20      rustsy-process run [MANIFEST] --auto=COLD.json --auto=WARM.json [--json]\n\
        \x20      rustsy-process explain REPORT.json\n\
        Manifest defaults to rustsy.json. Format flags apply to run only.",
        env!("CARGO_PKG_VERSION")
    );
}

fn command() -> io::Result<bool> {
    let mut args = env::args_os().skip(1);
    let command = args.next().unwrap_or_else(|| "help".into());
    let start = Instant::now();
    match command.to_str() {
        Some("help" | "--help" | "-h") => {
            help();
            return Ok(true);
        }
        Some("--version" | "-V") => {
            println!("rustsy-process {}", env!("CARGO_PKG_VERSION"));
            return Ok(true);
        }
        _ => {}
    }
    let paths = args.collect::<Vec<_>>();
    if command == "init"
        && let [tool] = paths.as_slice()
    {
        init(Path::new(tool))?;
        return Ok(true);
    }
    if command == "explain"
        && let [report] = paths.as_slice()
    {
        let report: serde_json::Value = read_json(Path::new(report))?;
        let nodes = report
            .pointer("/execution/nodes")
            .unwrap_or(&report["nodes"]);
        for node in nodes
            .as_array()
            .ok_or_else(|| invalid("expected a run report"))?
        {
            println!(
                "{} · {}",
                node["name"].as_str().unwrap_or("unknown task"),
                node["reason"].as_str().unwrap_or("reason unavailable")
            );
            if let Some(error) = node["error"].as_str() {
                println!("  {error}");
            }
        }
        return Ok(true);
    }
    if !matches!(command.to_str(), Some("run" | "graph" | "doctor")) {
        return Err(invalid("invalid command or arguments; see --help"));
    }
    let mut manifest = None;
    let mut format = None;
    let mut history = Vec::new();
    for item in &paths {
        if let Some(path) = item.to_str().and_then(|s| s.strip_prefix("--auto=")) {
            if command != "run" || path.is_empty() || history.len() >= 16 {
                return Err(invalid(
                    "use up to 16 --auto=REPORT.json arguments with run",
                ));
            }
            history.push(Path::new(path));
        } else if item == "--json" || item == "--trace" {
            if command != "run" || format.replace(item).is_some() {
                return Err(invalid("choose one run output format"));
            }
        } else if item.to_string_lossy().starts_with('-') || manifest.replace(item).is_some() {
            return Err(invalid("expected one manifest path"));
        }
    }
    let mut loaded = Loaded::read(manifest.map_or(Path::new("rustsy.json"), Path::new))?;
    if command == "graph" {
        println!("digraph rustsy {{");
        for task in &loaded.manifest.tasks {
            let label = serde_json::to_string(&task.name)?;
            println!("  {label};");
            for dep in &task.depends_on {
                println!("  {} -> {label};", serde_json::to_string(dep)?);
            }
        }
        println!("}}");
        return Ok(true);
    }
    if command == "doctor" {
        loaded.graph.validate_tools()?;
        let (estimate, path) = loaded.graph.planned_critical_path();
        println!(
            "{} tasks · estimated path {:.2} ms · {}",
            loaded.manifest.tasks.len(),
            estimate as f64 / 1e6,
            path.collect::<Vec<_>>().join(" -> ")
        );
        println!(
            "Local cache: {}",
            loaded
                .cache
                .as_ref()
                .map_or_else(|| "disabled".into(), |p| p.display().to_string())
        );
        let interrupted = loaded.root.join(".rustsy-process/active");
        match fs::symlink_metadata(&interrupted) {
            Ok(_) => {
                return Err(invalid(format!(
                    "active or interrupted run marker at {}; see the recovery guide",
                    interrupted.display()
                )));
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
        println!(
            "Manifest and tool paths validated. Cache declarations are trusted user commitments."
        );
        return Ok(true);
    }
    install_cancel()?;
    let pick = if history.is_empty() {
        None
    } else {
        Some(decision::choose(
            &history,
            &loaded.contract,
            &loaded
                .manifest
                .tasks
                .iter()
                .map(|t| t.name.as_str())
                .collect::<Vec<_>>(),
            &loaded.graph,
        )?)
    };
    if pick.as_ref().is_some_and(|pick| pick.bypass) {
        loaded.graph = loaded.graph.bypass_cache();
    }
    let config_ns = start.elapsed().as_nanos();
    let report = loaded.graph.run(
        &loaded.root,
        loaded.cache.as_deref(),
        loaded.capacity,
        &CANCEL,
    )?;
    match format.and_then(|value| value.to_str()) {
        Some("--json") => {
            #[derive(serde::Serialize)]
            struct Run<'a> {
                schema: u8,
                config_ns: u128,
                contract: &'a str,
                decision: Option<&'a decision::Decision>,
                execution: &'a rustsy_process::Report,
            }
            serde_json::to_writer(
                io::stdout().lock(),
                &Run {
                    schema: 1,
                    config_ns,
                    contract: &loaded.contract,
                    decision: pick.as_ref(),
                    execution: &report,
                },
            )?;
        }
        Some("--trace") => serde_json::to_writer(io::stdout().lock(), &report.trace())?,
        _ => {
            if let Some(pick) = &pick {
                println!("Decision: {}", pick.rationale);
            }
            report.print_summary();
            println!("Logs: {}", report.path_to_logs.display());
        }
    }
    Ok(report.succeeded())
}

static CANCEL: AtomicBool = AtomicBool::new(false);

#[cfg(windows)]
fn install_cancel() -> io::Result<()> {
    use windows_sys::Win32::System::Console::{
        CTRL_BREAK_EVENT, CTRL_C_EVENT, SetConsoleCtrlHandler,
    };
    unsafe extern "system" fn on_signal(kind: u32) -> i32 {
        if matches!(kind, CTRL_C_EVENT | CTRL_BREAK_EVENT) {
            CANCEL.store(true, Ordering::Release);
            1
        } else {
            0
        }
    }
    // The callback is static and only changes a process-local atomic flag.
    if unsafe { SetConsoleCtrlHandler(Some(on_signal), 1) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(unix)]
fn install_cancel() -> io::Result<()> {
    extern "C" fn on_signal(_: libc::c_int) {
        CANCEL.store(true, Ordering::Release);
    }
    // The callback never allocates or accesses shared state other than the atomic.
    unsafe {
        let mut action: libc::sigaction = std::mem::zeroed();
        action.sa_sigaction = on_signal as *const () as usize;
        libc::sigemptyset(&mut action.sa_mask);
        if libc::sigaction(libc::SIGINT, &action, std::ptr::null_mut()) != 0
            || libc::sigaction(libc::SIGTERM, &action, std::ptr::null_mut()) != 0
        {
            return Err(io::Error::last_os_error());
        }
    }
    Ok(())
}

#[cfg(not(any(unix, windows)))]
fn install_cancel() -> io::Result<()> {
    Ok(())
}

fn main() -> ExitCode {
    match command() {
        Ok(true) => ExitCode::SUCCESS,
        Ok(false) => ExitCode::FAILURE,
        Err(e) => {
            eprintln!("rustsy-process: {e}");
            ExitCode::FAILURE
        }
    }
}