apoc 0.7.4

Agentic process control for LLMs
Documentation
use std::process::Command;
use std::time::{Duration, Instant};

use serde_json::Value;
use tempfile::{TempDir, tempdir};

const PURPOSE: &str = "Verify that completion wins over an outstanding timer.";
const PROMPT_RETURN: Duration = Duration::from_secs(15);

struct Fixture {
    home: TempDir,
    runtime: TempDir,
}

impl Fixture {
    fn new() -> Self {
        let fixture = Self {
            home: tempdir().unwrap(),
            runtime: tempdir().unwrap(),
        };
        // Exclude cold startup from the completion measurement.
        fixture.call(&["daemon", "start", "--idempotency-key", "completion-start"]);
        fixture
    }

    fn call(&self, args: &[&str]) -> Value {
        let output = Command::new(env!("CARGO_BIN_EXE_apoc"))
            .args(args)
            .args(["--purpose", PURPOSE, "--format", "json"])
            .env("APOC_HOME", self.home.path())
            .env("APOC_RUNTIME_DIR", self.runtime.path())
            .env("XDG_DATA_HOME", self.home.path().join("xdg"))
            .env_remove("APOC_PROFILE")
            .env_remove("APOC_VIEW")
            .env_remove("APOC_VERBOSITY")
            .output()
            .unwrap();
        // Error executions may exit nonzero, but must still return durable state.
        serde_json::from_slice(&output.stdout).unwrap_or_else(|error| panic!("{error}: {output:?}"))
    }

    fn run(&self, code: &str, key: &str, timeout: &str) -> Value {
        self.call(&[
            "code",
            "run",
            code,
            "--idempotency-key",
            key,
            "--timeout-ms",
            timeout,
        ])
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let _ = self.call(&["daemon", "stop", "--idempotency-key", "completion-stop"]);
    }
}

#[test]
fn completed_internal_commands_do_not_wait_for_command_or_outer_deadlines() {
    let fixture = Fixture::new();
    for (executable, expected) in [("/usr/bin/true", "passed"), ("/usr/bin/false", "failed")] {
        let code = format!(
            "return await apoc.execution_command({{executable: {executable:?}, \
             timeout_ms: 60000, purpose: {PURPOSE:?}, idempotency_key: {expected:?}}});"
        );
        let started = Instant::now();
        let state = fixture.run(&code, expected, "60000");
        assert_eq!(state["status"], "completed", "{state:#}");
        assert_eq!(state["result"]["outcome"], expected, "{state:#}");
        assert!(started.elapsed() < PROMPT_RETURN, "{state:#}");
    }
}

#[test]
fn settled_code_does_not_wait_for_a_losing_timer() {
    let fixture = Fixture::new();
    for (key, settle, expected) in [
        ("resolve", "return 'finished';", "completed"),
        ("reject", "throw new Error('finished-with-error');", "error"),
    ] {
        let code = format!(
            "const purpose = {PURPOSE:?}; \
             return await Promise.race([\
               apoc.wait({{ms: 25, purpose}}).then(() => {{ {settle} }}),\
               apoc.wait({{ms: 60000, purpose}}).then(() => 'timer')\
             ]);"
        );
        let started = Instant::now();
        let state = fixture.run(&code, key, "60000");
        assert_eq!(state["status"], expected, "{state:#}");
        if key == "resolve" {
            assert_eq!(state["result"], "finished", "{state:#}");
        } else {
            assert!(
                state["error"]
                    .as_str()
                    .unwrap()
                    .contains("finished-with-error")
            );
        }
        assert!(started.elapsed() < PROMPT_RETURN, "{state:#}");
    }
}

#[test]
fn an_expired_outer_wait_does_not_cancel_the_internal_call() {
    let fixture = Fixture::new();
    let code = format!("await apoc.wait({{ms: 5000, purpose: {PURPOSE:?}}}); return 'finished';");
    let started = Instant::now();
    let mut state = fixture.run(&code, "observation-boundary", "1");
    assert_eq!(state["status"], "running", "{state:#}");
    let id = state["id"].as_str().unwrap().to_owned();
    while state["status"] == "running" {
        assert!(started.elapsed() < PROMPT_RETURN, "{state:#}");
        std::thread::sleep(Duration::from_millis(25));
        state = fixture.call(&["code", "get", &id]);
    }
    assert_eq!(state["status"], "completed", "{state:#}");
    assert_eq!(state["result"], "finished", "{state:#}");
}