rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
Documentation
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Output, Stdio},
    sync::atomic::{AtomicUsize, Ordering},
    time::{Duration, Instant},
};

struct Fixture(PathBuf);
impl Fixture {
    fn new() -> Self {
        static NEXT: AtomicUsize = AtomicUsize::new(0);
        let parent = std::env::temp_dir().canonicalize().unwrap();
        loop {
            let id = NEXT.fetch_add(1, Ordering::Relaxed);
            let path = parent.join(format!("rustsy-cli-test-{}-{id}", std::process::id()));
            match fs::create_dir(&path) {
                Ok(()) => return Self(path),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(e) => panic!("{e}"),
            }
        }
    }

    fn default_manifest(&self) -> Value {
        self.write("src", "original\n");
        self.write("tool-resource", "initial tool resource\n");
        json!({
            "version": 1, "workers": 2,
            "tools": {"child":{"path":std::env::current_exe().unwrap(),"version":"test",
                                 "files":["tool-resource"]}},
            "tasks": [{"name":"build", "tool":"child", "args":["--exact", "fixture_child"],
                       "env":{"RUSTSY_TEST_ACTION":"copy"}, "cache":"local", "deterministic":true,
                       "inputs":[{"path":"src","kind":"file"}],
                       "outputs":[{"path":"artifact","kind":"file"}]}]
        })
    }

    fn write(&self, path: &str, contents: &str) {
        fs::write(self.0.join(path), contents).unwrap();
    }

    fn configure(&self, config: &Value) {
        self.write("rustsy.json", &config.to_string());
    }

    fn command(&self, command: &str) -> Command {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_rustsy-process"));
        cmd.current_dir(&self.0).arg(command);
        cmd
    }

    fn run(&self) -> (Output, Value) {
        let out = self.command("run").arg("--json").output().unwrap();
        let report: Value = serde_json::from_slice(&out.stdout)
            .unwrap_or_else(|e| panic!("{e}: {}", String::from_utf8_lossy(&out.stderr)));
        (out, report["execution"]["nodes"][0].clone())
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        fs::remove_dir_all(&self.0).unwrap();
    }
}

#[test]
fn fixture_child() {
    match std::env::var("RUSTSY_TEST_ACTION").as_deref() {
        Ok("copy") => {}
        Ok("mutate") => fs::write("src", "mutated source\n").unwrap(),
        Ok("wait") => {
            fs::write("artifact", "partial").unwrap();
            std::thread::sleep(Duration::from_secs(6));
        }
        Ok("interrupted-promotion") => {
            let internal = Path::new(".rustsy-process");
            let run = format!(".stage-{}-0", std::process::id());
            let transaction = internal.join(&run).join("transactions/.stage-1-0");
            fs::create_dir_all(&transaction).unwrap();
            let lock = fs::File::create_new(internal.join("active.lock")).unwrap();
            lock.try_lock().unwrap();
            fs::write(internal.join("active"), format!("rustsy-7:{run}\n")).unwrap();
            fs::write(
                transaction.join("journal.json"),
                br#"{"entries":[{"index":0,"path":"artifact","existed":true}]}"#,
            )
            .unwrap();
            fs::rename("artifact", transaction.join("old-0")).unwrap();
            fs::write("artifact", "incomplete promotion").unwrap();
            std::thread::sleep(Duration::from_secs(20));
            drop(lock);
            return;
        }
        _ => return,
    }
    let text = fs::read_to_string("src").unwrap();
    fs::write("artifact", text).unwrap();
}

#[test]
fn strict_hit_restore_repair_and_invalidate_tool_resource() {
    let f = Fixture::new();
    let manifest = f.default_manifest();
    f.configure(&manifest);
    assert!(f.command("doctor").output().unwrap().status.success());
    let first = f.run().1;
    assert_eq!(first["cache"], "miss");
    let same = f.run().1;
    assert_eq!(same["cache"], "hit");
    assert_eq!(same["cache_payloads_verified"], true);
    fs::rename(f.0.join("artifact"), f.0.join("held")).unwrap();
    let restored = f.run().1;
    assert_eq!(restored["restored_artifacts"], 1);
    assert_eq!(fs::read(f.0.join("artifact")).unwrap(), b"original\n");
    let digest = format!("{:x}", Sha256::digest(b"original\n"));
    let blob = f.0.join(".rustsy-process/cache/blobs").join(digest);
    fs::write(&blob, b"damaged!\n").unwrap();
    let repaired = f.run().1;
    assert_eq!(repaired["cache"], "corrupted");
    assert_eq!(fs::read(blob).unwrap(), b"original\n");
    f.write("tool-resource", "a new tool resource\n");
    let changed = f.run().1;
    assert_eq!(changed["cache"], "miss");
    assert_ne!(changed["key"], first["key"]);
    let file = fs::File::options()
        .write(true)
        .open(f.0.join("src"))
        .unwrap();
    let mtime = file.metadata().unwrap().modified().unwrap();
    f.write("src", "updated!\n");
    file.set_modified(mtime).unwrap();
    drop(file);
    let edited = f.run().1;
    assert_ne!(edited["key"], changed["key"]);
    assert_eq!(fs::read(f.0.join("artifact")).unwrap(), b"updated!\n");
}

#[test]
fn revalidates_before_publication_and_rolls_back_failed_action() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    f.write("artifact", "previous artifact");
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("mutate");
    f.configure(&manifest);
    let (out, node) = f.run();
    assert!(!out.status.success());
    assert_eq!(node["status"], "failed");
    assert!(
        node["error"]
            .as_str()
            .unwrap()
            .contains("changed during the action")
    );
    assert_eq!(
        fs::read(f.0.join("artifact")).unwrap(),
        b"previous artifact"
    );
    assert_eq!(
        fs::read_dir(f.0.join(".rustsy-process/cache/actions"))
            .unwrap()
            .count(),
        0
    );
    assert!(!f.0.join(".rustsy-process/active").exists());
}

#[test]
fn product_manifest_refuses_unattested_cache_and_legacy_modes() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    manifest["tasks"][0]["deterministic"] = json!(false);
    f.configure(&manifest);
    let out = f.command("run").output().unwrap();
    assert!(!out.status.success());
    assert!(!f.0.join(".rustsy-process").exists());
    manifest["tasks"][0]["deterministic"] = json!(true);
    manifest["packed_outputs"] = json!(true);
    f.configure(&manifest);
    assert!(!f.command("doctor").output().unwrap().status.success());
}

#[test]
fn measured_policy_bypasses_cache_and_preserves_the_transaction() {
    let f = Fixture::new();
    let manifest = f.default_manifest();
    f.configure(&manifest);
    let (strict, node) = f.run();
    assert!(strict.status.success());
    let sample: Value = serde_json::from_slice(&strict.stdout).unwrap();
    let run = |name: &str, hit: bool| {
        let mut value = sample.clone();
        value["execution"]["tool_hash_ns"] = json!(200_000_000);
        let entry = &mut value["execution"]["nodes"][0];
        entry["process_ns"] = json!(if hit { 0 } else { 5_000_000 });
        entry["status"] = json!(if hit { "cached" } else { "executed" });
        entry["cache"] = json!(if hit { "hit" } else { "miss" });
        f.write(name, &value.to_string());
    };
    run("cold.json", false);
    run("warm.json", true);
    f.write("src", "changed\n");
    let report = f
        .command("run")
        .args(["--auto=cold.json", "--auto=warm.json", "--json"])
        .output()
        .unwrap();
    assert!(report.status.success());
    let actual: Value = serde_json::from_slice(&report.stdout).unwrap();
    assert_eq!(actual["decision"]["bypass"], true);
    assert_eq!(actual["execution"]["tool_hash_ns"], 0);
    assert_eq!(actual["execution"]["nodes"][0]["cache"], "off");
    assert_eq!(fs::read(f.0.join("artifact")).unwrap(), b"changed\n");
    f.write("src", "original\n");
    let restored = f.run().1;
    assert_eq!(restored["cache"], "hit");
    assert_eq!(restored["key"], node["key"]);
    assert_eq!(fs::read(f.0.join("artifact")).unwrap(), b"original\n");
}

#[test]
fn competing_run_times_out_and_keeps_previous_artifact() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    f.write("artifact", "previous artifact");
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("wait");
    manifest["tasks"][0]["timeout_ms"] = json!(1200);
    f.configure(&manifest);
    let child = f
        .command("run")
        .arg("--json")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    await_marker(&f.0);
    let overlap = f.command("run").output().unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(!overlap.status.success());
    assert!(String::from_utf8_lossy(&overlap.stderr).contains("active"));
    assert!(!out.status.success());
    let report: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["execution"]["nodes"][0]["status"], "timeout");
    assert_eq!(
        fs::read(f.0.join("artifact")).unwrap(),
        b"previous artifact"
    );
}

fn await_marker(root: &Path) {
    let start = Instant::now();
    while !root.join(".rustsy-process/active").exists() {
        assert!(start.elapsed() < Duration::from_secs(4));
        std::thread::sleep(Duration::from_millis(5));
    }
}

#[test]
fn reacquires_abandoned_lock_and_rolls_back_promotion() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    f.write("artifact", "previous artifact");
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("mutate");
    f.configure(&manifest);
    let mut fixture = Command::new(std::env::current_exe().unwrap())
        .current_dir(&f.0)
        .args(["--exact", "fixture_child"])
        .env("RUSTSY_TEST_ACTION", "interrupted-promotion")
        .stdout(Stdio::null())
        .spawn()
        .unwrap();
    let start = Instant::now();
    while !fs::read_to_string(f.0.join("artifact")).is_ok_and(|b| b == "incomplete promotion") {
        if start.elapsed() >= Duration::from_secs(10) {
            let _ = fixture.kill();
            let _ = fixture.wait();
            panic!("interrupted promotion fixture did not start");
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    fixture.kill().unwrap();
    fixture.wait().unwrap();
    let resumed = f.command("run").arg("--json").output().unwrap();
    let report: Value = serde_json::from_slice(&resumed.stdout).unwrap();
    assert_eq!(report["execution"]["recovered_transactions"], 1);
    assert_eq!(report["execution"]["nodes"][0]["status"], "failed");
    assert_eq!(
        fs::read(f.0.join("artifact")).unwrap(),
        b"previous artifact"
    );
}

#[test]
fn killed_runner_refuses_to_reuse_outputs_while_child_is_unconfirmed() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    f.write("artifact", "previous artifact");
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("wait");
    f.configure(&manifest);
    let mut child = f
        .command("run")
        .arg("--json")
        .stdout(Stdio::null())
        .spawn()
        .unwrap();
    let now = Instant::now();
    loop {
        if fs::read(f.0.join("artifact")).is_ok_and(|b| b == b"partial") {
            break;
        }
        if now.elapsed() >= Duration::from_secs(15) {
            let _ = child.kill();
            let _ = child.wait();
            panic!("fixture child did not reach the interruption point");
        }
        std::thread::sleep(Duration::from_millis(10));
    }
    child.kill().unwrap();
    child.wait().unwrap();
    let result = f.command("run").output().unwrap();
    assert!(!result.status.success());
    assert!(String::from_utf8_lossy(&result.stderr).contains("may still be running"));
    #[cfg(unix)]
    {
        // The fixture's bounded child writes its valid result before returning.
        let start = Instant::now();
        while fs::read(f.0.join("artifact")).unwrap() != b"original\n" {
            assert!(start.elapsed() < Duration::from_secs(9));
            std::thread::sleep(Duration::from_millis(20));
        }
    }
    let internal = f.0.join(".rustsy-process");
    let marker = fs::read_to_string(internal.join("active")).unwrap();
    let run = internal.join(marker.trim().strip_prefix("rustsy-7:").unwrap());
    let scopes = fs::read_dir(run.join("transactions")).unwrap();
    for scope in scopes {
        let scope = scope.unwrap().path();
        if scope.join("child-active").exists() {
            fs::rename(scope.join("child-active"), scope.join("child-reviewed")).unwrap();
        }
    }
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("mutate");
    f.configure(&manifest);
    let output = f.command("run").arg("--json").output().unwrap();
    let report: Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(report["execution"]["recovered_transactions"], 1);
    assert_eq!(report["execution"]["nodes"][0]["status"], "failed");
    assert_eq!(
        fs::read(f.0.join("artifact")).unwrap(),
        b"previous artifact"
    );
}

#[cfg(unix)]
#[test]
fn sigint_cancels_the_active_run() {
    let f = Fixture::new();
    let mut manifest = f.default_manifest();
    f.write("artifact", "previous artifact");
    manifest["tasks"][0]["env"]["RUSTSY_TEST_ACTION"] = json!("wait");
    f.configure(&manifest);
    let child = f
        .command("run")
        .arg("--json")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    await_marker(&f.0);
    // The PID identifies the child owned by this fixture.
    assert_eq!(
        unsafe { libc::kill(child.id() as libc::pid_t, libc::SIGINT) },
        0
    );
    let out = child.wait_with_output().unwrap();
    assert!(!out.status.success());
    let report: Value = serde_json::from_slice(&out.stdout).unwrap();
    assert_eq!(report["execution"]["nodes"][0]["status"], "cancelled");
    assert_eq!(
        fs::read(f.0.join("artifact")).unwrap(),
        b"previous artifact"
    );
}