use std::process::{Command, Output};
use std::sync::{Arc, Barrier};
use std::thread;
use serde_json::Value;
use tempfile::{TempDir, tempdir};
struct Fixture {
binary: String,
home: TempDir,
runtime: TempDir,
}
impl Fixture {
fn new() -> Self {
Self {
binary: env!("CARGO_BIN_EXE_apoc").to_string(),
home: tempdir().unwrap(),
runtime: tempdir().unwrap(),
}
}
fn run_from(&self, cwd: &std::path::Path, args: &[&str]) -> Output {
Command::new(&self.binary)
.args(args)
.current_dir(cwd)
.env("APOC_HOME", self.home.path())
.env("APOC_RUNTIME_DIR", self.runtime.path())
.output()
.unwrap()
}
fn json_from(&self, cwd: &std::path::Path, args: &[&str]) -> Value {
let output = self.run_from(cwd, args);
assert!(
output.status.success(),
"command failed:\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = self.run_from(self.home.path(), &["daemon", "stop", "--format", "json"]);
}
}
#[test]
fn execution_inherits_the_invoking_directory_not_the_daemon_directory() {
let apoc = Fixture::new();
let daemon_cwd = tempdir().unwrap();
let caller_cwd = tempdir().unwrap();
apoc.json_from(
daemon_cwd.path(),
&["execution", "command", "/usr/bin/true", "--format", "json"],
);
let result = apoc.json_from(
caller_cwd.path(),
&["execution", "command", "/bin/pwd", "--format", "json"],
);
let expected = caller_cwd.path().canonicalize().unwrap();
assert_eq!(
result["execution"]["spec"]["workspace"]["cwd"],
expected.to_string_lossy().as_ref()
);
assert_eq!(
result["logs"]["stdout"].as_str().unwrap().trim(),
expected.to_string_lossy().as_ref()
);
assert_eq!(result["replayed"], false);
}
#[test]
fn relative_cwd_is_resolved_from_the_invoking_directory() {
let apoc = Fixture::new();
let caller_cwd = tempdir().unwrap();
let child = caller_cwd.path().join("child");
std::fs::create_dir(&child).unwrap();
let result = apoc.json_from(
caller_cwd.path(),
&[
"execution",
"command",
"/bin/pwd",
"--cwd",
"child",
"--format",
"json",
],
);
let expected = child.canonicalize().unwrap();
assert_eq!(
result["execution"]["spec"]["workspace"]["cwd"],
expected.to_string_lossy().as_ref()
);
assert_eq!(
result["logs"]["stdout"].as_str().unwrap().trim(),
expected.to_string_lossy().as_ref()
);
}
#[test]
fn synchronous_execution_returns_bounded_logs_and_the_managed_exit_code() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let output = apoc.run_from(
cwd.path(),
&[
"execution",
"command",
"/usr/bin/python3",
"--arg",
"-c",
"--arg",
"import sys; print('outcome'); print('diagnostic', file=sys.stderr); sys.exit(7)",
"--format",
"json",
],
);
assert_eq!(output.status.code(), Some(7));
let result: Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(result["execution"]["result"]["exit_code"], 7);
assert_eq!(result["logs"]["stdout"], "outcome\n");
assert_eq!(result["logs"]["stderr"], "diagnostic\n");
assert_eq!(result["logs"]["stdout_truncated"], false);
assert_eq!(result["logs"]["stderr_truncated"], false);
}
#[test]
fn synchronous_execution_marks_each_truncated_stream() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let result = apoc.json_from(
cwd.path(),
&[
"execution",
"command",
"/usr/bin/python3",
"--arg",
"-c",
"--arg",
"import sys; print('o' * 40000); print('e' * 40000, file=sys.stderr)",
"--format",
"json",
],
);
assert!(result["logs"]["stdout"].as_str().unwrap().len() <= 32 * 1024);
assert!(result["logs"]["stderr"].as_str().unwrap().len() <= 32 * 1024);
assert_eq!(result["logs"]["stdout_truncated"], true);
assert_eq!(result["logs"]["stderr_truncated"], true);
}
#[test]
fn invalid_working_directory_fails_before_accepting_an_execution() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let output = apoc.run_from(
cwd.path(),
&[
"execution",
"command",
"/usr/bin/true",
"--cwd",
"missing",
"--format",
"json",
],
);
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stdout).contains("INVALID_WORKSPACE")
|| String::from_utf8_lossy(&output.stderr).contains("INVALID_WORKSPACE")
);
}
#[test]
fn execution_idempotency_replays_one_side_effect_and_rejects_conflicts() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let side_effect = cwd.path().join("effect");
let script = format!("printf x >> '{}'", side_effect.display());
let args = [
"execution",
"command",
"/bin/zsh",
"--arg",
"-c",
"--arg",
script.as_str(),
"--idempotency-key",
"execution-contract/replay",
"--format",
"json",
];
let first = apoc.json_from(cwd.path(), &args);
let second = apoc.json_from(cwd.path(), &args);
assert_eq!(first["execution"]["id"], second["execution"]["id"]);
assert_eq!(first["replayed"], false);
assert_eq!(second["replayed"], true);
assert_eq!(std::fs::read_to_string(&side_effect).unwrap(), "x");
let conflict = apoc.run_from(
cwd.path(),
&[
"execution",
"command",
"/usr/bin/true",
"--idempotency-key",
"execution-contract/replay",
"--format",
"json",
],
);
assert!(!conflict.status.success());
let output = format!(
"{}{}",
String::from_utf8_lossy(&conflict.stdout),
String::from_utf8_lossy(&conflict.stderr)
);
assert!(
output.contains("EXECUTION_IDEMPOTENCY_CONFLICT"),
"{output}"
);
}
#[test]
fn command_group_idempotency_replays_the_original_parent() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let side_effect = cwd.path().join("batch-effect");
let file = cwd.path().join("batch.json");
std::fs::write(
&file,
serde_json::to_vec(&serde_json::json!({
"commands": [{
"id": "effect",
"argv": [
"/bin/zsh",
"-c",
format!("printf x >> '{}'", side_effect.display())
]
}]
}))
.unwrap(),
)
.unwrap();
let args = [
"execution",
"batch",
"--file",
file.to_str().unwrap(),
"--idempotency-key",
"execution-contract/batch",
"--format",
"json",
];
let first = apoc.json_from(cwd.path(), &args);
let second = apoc.json_from(cwd.path(), &args);
assert_eq!(first["execution"]["id"], second["execution"]["id"]);
assert_eq!(first["replayed"], false);
assert_eq!(second["replayed"], true);
assert_eq!(std::fs::read_to_string(&side_effect).unwrap(), "x");
}
#[test]
fn code_mode_retries_replay_nested_execution_idempotency() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let side_effect = cwd.path().join("code-retry-effect");
let code = format!(
"return await apoc.execution_command({{executable:'/bin/zsh',arg:['-c',\"printf x >> '{}'\"],idempotency_key:'execution-contract/code-retry'}});",
side_effect.display()
);
let args = ["code", "run", code.as_str(), "--format", "json"];
let first = apoc.json_from(cwd.path(), &args);
let second = apoc.json_from(cwd.path(), &args);
assert_eq!(first["status"], "completed", "{first:#}");
assert_eq!(second["status"], "completed", "{second:#}");
assert_eq!(first["result"]["replayed"], false);
assert_eq!(second["result"]["replayed"], true);
assert_eq!(
first["result"]["execution"]["id"],
second["result"]["execution"]["id"]
);
assert_eq!(std::fs::read_to_string(&side_effect).unwrap(), "x");
}
#[test]
fn concurrent_idempotent_launches_create_one_execution() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let side_effect = cwd.path().join("concurrent-effect");
let script = format!("printf x >> '{}'; sleep 0.1", side_effect.display());
let workers = 8;
let barrier = Arc::new(Barrier::new(workers));
let outputs = (0..workers)
.map(|_| {
let binary = apoc.binary.clone();
let home = apoc.home.path().to_path_buf();
let runtime = apoc.runtime.path().to_path_buf();
let cwd = cwd.path().to_path_buf();
let script = script.clone();
let barrier = Arc::clone(&barrier);
thread::spawn(move || {
barrier.wait();
Command::new(binary)
.args([
"execution",
"command",
"/bin/zsh",
"--arg",
"-c",
"--arg",
&script,
"--idempotency-key",
"execution-contract/concurrent",
"--format",
"json",
])
.current_dir(cwd)
.env("APOC_HOME", home)
.env("APOC_RUNTIME_DIR", runtime)
.output()
.unwrap()
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|worker| worker.join().unwrap())
.collect::<Vec<_>>();
assert!(outputs.iter().all(|output| output.status.success()));
let results = outputs
.iter()
.map(|output| serde_json::from_slice::<Value>(&output.stdout).unwrap())
.collect::<Vec<_>>();
assert!(
results
.iter()
.all(|result| result["execution"]["id"] == results[0]["execution"]["id"])
);
assert_eq!(
results
.iter()
.filter(|result| result["replayed"] == false)
.count(),
1
);
assert_eq!(std::fs::read_to_string(&side_effect).unwrap(), "x");
}
#[test]
fn execution_list_is_compact_bounded_and_cursor_paginated() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
for name in ["first", "second", "third"] {
apoc.json_from(
cwd.path(),
&[
"execution",
"command",
"/usr/bin/true",
"--name",
name,
"--format",
"json",
],
);
}
let first = apoc.json_from(
cwd.path(),
&["execution", "list", "--limit", "2", "--format", "json"],
);
let executions = first["executions"].as_array().unwrap();
assert_eq!(executions.len(), 2);
assert!(
executions
.iter()
.all(|execution| execution.get("spec").is_none())
);
assert!(
executions
.iter()
.all(|execution| execution.get("passes").is_none())
);
assert!(
executions
.iter()
.all(|execution| execution.get("program").is_some())
);
let cursor = first["next_cursor"].as_str().unwrap();
let second = apoc.json_from(
cwd.path(),
&[
"execution",
"list",
"--limit",
"2",
"--cursor",
cursor,
"--status",
"completed",
"--format",
"json",
],
);
assert_eq!(second["executions"].as_array().unwrap().len(), 1);
assert!(second["next_cursor"].is_null());
assert!(serde_json::to_vec(&first).unwrap().len() <= 128 * 1024);
}
#[test]
fn code_mode_inherits_and_preserves_the_invoking_directory() {
let apoc = Fixture::new();
let daemon_cwd = tempdir().unwrap();
let caller_cwd = tempdir().unwrap();
apoc.json_from(
daemon_cwd.path(),
&["execution", "command", "/usr/bin/true", "--format", "json"],
);
let state = apoc.json_from(
caller_cwd.path(),
&[
"code",
"run",
"return await apoc.execution_command({ executable: '/bin/pwd' });",
"--format",
"json",
],
);
let expected = caller_cwd.path().canonicalize().unwrap();
assert_eq!(
state["result"]["execution"]["spec"]["workspace"]["cwd"],
expected.to_string_lossy().as_ref()
);
assert_eq!(
state["result"]["logs"]["stdout"].as_str().unwrap().trim(),
expected.to_string_lossy().as_ref()
);
let execution = apoc.json_from(
daemon_cwd.path(),
&[
"execution",
"get",
state["id"].as_str().unwrap(),
"--format",
"json",
],
);
assert_eq!(
execution["spec"]["workspace"]["cwd"],
expected.to_string_lossy().as_ref()
);
}
#[test]
fn daemon_reports_its_runtime_contract_version() {
let apoc = Fixture::new();
let cwd = tempdir().unwrap();
let status = apoc.json_from(cwd.path(), &["daemon", "start", "--format", "json"]);
assert_eq!(status["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(status["execution_schema_version"], 4);
}