mod client;
mod coordinator;
mod transport;
pub(crate) use client::{cancel_run, submit_run};
pub(crate) use coordinator::{Coordinator, EngineClaim, ExecutionLease};
use std::{path::Path, sync::Arc, time::Duration};
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use crate::{
platform, process,
runs::{CancelAcknowledgement, Control, observe, worker},
store::{self, Receipts},
types::{FailureCode, RunId},
};
use transport::{
ClientFrame, EngineEndpoint, ServerFrame, Stream, VERSION, read_frame, validate_peer,
write_frame,
};
const IDLE_DRAIN: Duration = Duration::from_millis(150);
const HELLO_TIMEOUT: Duration = Duration::from_secs(5);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_CLIENTS: usize = 64;
const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_millis(50);
const STATE_CHECK: Duration = Duration::from_millis(500);
pub async fn serve(state: &Path) -> Result<(), String> {
serve_with_hook(state, None).await
}
#[doc(hidden)]
pub type BeforeRunHook = Arc<
dyn Fn(
&Path,
&RunId,
)
-> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
+ Send
+ Sync,
>;
const TAKEOVER_WAIT: Duration = Duration::from_secs(2);
const TAKEOVER_POLL: Duration = Duration::from_millis(20);
fn state_identities(state: &Path) -> Option<(platform::FileIdentity, platform::FileIdentity)> {
let dir = platform::open_directory(state).ok()?;
let db = platform::open_regular(&state.join(store::DATABASE)).ok()?;
Some((
platform::file_identity(&dir).ok()?,
platform::file_identity(&db).ok()?,
))
}
#[doc(hidden)]
pub async fn serve_with_hook(
state: &Path,
before_run: Option<BeforeRunHook>,
) -> Result<(), String> {
let state = crate::workspace::canonical_target(&store::state_dir(Some(state))?)
.map_err(|error| error.to_string())?;
platform::create_private_dir_all(&state).map_err(|error| error.to_string())?;
let endpoint = EngineEndpoint::new(&state).map_err(|error| error.to_string())?;
let takeover_deadline = tokio::time::Instant::now() + TAKEOVER_WAIT;
let _owner_lock = loop {
if let Some(lock) = endpoint.take_owner().map_err(|error| error.to_string())? {
break lock;
}
if endpoint.connect().await.is_ok() || tokio::time::Instant::now() >= takeover_deadline {
return Ok(());
}
tokio::time::sleep(TAKEOVER_POLL).await;
};
let owner = process::child_identity(std::process::id()).map_err(|error| error.to_string())?;
if platform::paths::target_is_file(&state.join(store::DATABASE)) {
crate::runs::reconcile_open(&state).await;
}
let receipts = Receipts::open_state(&state).await?;
let baseline_identities = state_identities(&state);
let listener = endpoint.listen().map_err(|error| error.to_string())?;
let coordinator = Coordinator::new(state.clone(), owner, receipts.clone());
let shutdown = CancellationToken::new();
let result = run_server(
listener,
endpoint,
coordinator.clone(),
baseline_identities,
before_run,
shutdown.clone(),
)
.await;
let _ = receipts.checkpoint_truncate().await;
let closed = receipts.close().await;
result.and(closed)
}
async fn run_server(
mut listener: transport::Listener,
endpoint: EngineEndpoint,
coordinator: Arc<Coordinator>,
baseline_identities: Option<(platform::FileIdentity, platform::FileIdentity)>,
before_run: Option<BeforeRunHook>,
shutdown: CancellationToken,
) -> Result<(), String> {
let mut clients = JoinSet::new();
let mut run_tasks = JoinSet::new();
let (run_tx, mut run_rx) = tokio::sync::mpsc::unbounded_channel::<SpawnedRun>();
let client_shutdown = CancellationToken::new();
let mut state_check = tokio::time::interval(STATE_CHECK);
state_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
state_check.tick().await;
let mut idle_since: Option<tokio::time::Instant> = Some(tokio::time::Instant::now());
loop {
let activity = coordinator.activity_notified();
tokio::pin!(activity);
activity.as_mut().enable();
if coordinator.is_idle() {
if idle_since.is_none() {
idle_since = Some(tokio::time::Instant::now());
}
} else {
idle_since = None;
}
let idle_deadline = idle_since.map(|since| since + IDLE_DRAIN);
if let Some(deadline) = idle_deadline
&& tokio::time::Instant::now() >= deadline
&& coordinator.try_begin_shutdown()
{
break;
}
tokio::select! {
_ = shutdown.cancelled() => {
coordinator.begin_draining();
break;
}
Some(spawned) = run_rx.recv() => {
idle_since = None;
let coord = coordinator.clone();
let hook = before_run.clone();
run_tasks.spawn(async move {
execute_managed_run(coord, spawned, hook).await;
});
}
Some(joined) = run_tasks.join_next(), if !run_tasks.is_empty() => {
let _ = crate::task::joined(joined);
}
Some(joined) = clients.join_next(), if !clients.is_empty() => {
let _ = crate::task::joined(joined);
}
accepted = listener.accept(), if clients.len() < MAX_CLIENTS => {
match accepted {
Ok(stream) => {
let coord = coordinator.clone();
let id = endpoint.identity.clone();
let tx = run_tx.clone();
let stop = shutdown.clone();
let client_stop = client_shutdown.clone();
clients.spawn(async move {
let _ = handle_client(stream, id, coord, tx, stop, client_stop).await;
});
}
Err(error) => {
use std::io::Write;
let _ = writeln!(
std::io::stderr().lock(),
"Verify engine transient accept error: {error}"
);
tokio::time::sleep(ACCEPT_ERROR_BACKOFF).await;
}
}
}
_ = &mut activity => {}
_ = tokio::time::sleep_until(idle_deadline.unwrap_or_else(tokio::time::Instant::now)),
if idle_deadline.is_some() => {}
_ = state_check.tick() => {
let missing_or_replaced = !platform::paths::target_is_dir(coordinator.state_dir())
|| baseline_identities
.is_some_and(|expected| state_identities(coordinator.state_dir()) != Some(expected));
if missing_or_replaced {
coordinator.begin_draining();
coordinator.cancel_all_active();
break;
}
}
}
}
drop(listener);
client_shutdown.cancel();
while let Some(joined) = clients.join_next().await {
let _ = crate::task::joined(joined);
}
drop(run_tx);
run_rx.close();
while let Some(spawned) = run_rx.recv().await {
let coord = coordinator.clone();
let hook = before_run.clone();
run_tasks.spawn(async move {
execute_managed_run(coord, spawned, hook).await;
});
}
while let Some(joined) = run_tasks.join_next().await {
let _ = crate::task::joined(joined);
}
Ok(())
}
struct SpawnedRun {
run: store::Run,
caller_env: Arc<std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>>,
cancellation: CancellationToken,
}
async fn write_bounded(stream: &mut Stream, frame: &ServerFrame) -> std::io::Result<()> {
tokio::time::timeout(WRITE_TIMEOUT, write_frame(stream, frame))
.await
.map_err(|_| std::io::ErrorKind::TimedOut)?
}
async fn handle_client(
mut stream: Stream,
expected_identity: crate::config::EndpointId,
coordinator: Arc<Coordinator>,
run_tx: tokio::sync::mpsc::UnboundedSender<SpawnedRun>,
shutdown: CancellationToken,
client_shutdown: CancellationToken,
) -> std::io::Result<()> {
validate_peer(&stream)?;
let hello: ClientFrame = tokio::select! {
_ = client_shutdown.cancelled() => return Ok(()),
result = tokio::time::timeout(HELLO_TIMEOUT, read_frame(&mut stream)) => result??,
};
let ClientFrame::Hello { version, identity } = hello else {
return Err(std::io::ErrorKind::InvalidData.into());
};
if identity != expected_identity {
return Err(std::io::ErrorKind::PermissionDenied.into());
}
if version != VERSION {
write_bounded(
&mut stream,
&ServerFrame::Incompatible {
server_version: VERSION,
},
)
.await?;
let follow = tokio::select! {
_ = client_shutdown.cancelled() => return Ok(()),
result = tokio::time::timeout(HELLO_TIMEOUT, read_frame::<_, ClientFrame>(&mut stream)) => result,
};
if let Ok(Ok(ClientFrame::ShutdownIfIdle)) = follow {
let reply = if coordinator.try_begin_shutdown() {
shutdown.cancel();
ServerFrame::Ack
} else {
ServerFrame::Busy
};
let _ = write_bounded(&mut stream, &reply).await;
}
return Ok(());
}
if coordinator.is_shutting_down() {
write_bounded(&mut stream, &ServerFrame::ShuttingDown).await?;
return Ok(());
}
write_bounded(
&mut stream,
&ServerFrame::Welcome {
version: VERSION,
owner: coordinator.owner(),
},
)
.await?;
let request: ClientFrame = tokio::select! {
_ = client_shutdown.cancelled() => return Ok(()),
result = tokio::time::timeout(REQUEST_TIMEOUT, read_frame(&mut stream)) => result??,
};
let response = match request {
ClientFrame::SubmitRun {
repo,
selection,
options,
env,
request_key,
request_args_hash,
origin,
} => {
let Some(_guard) = coordinator.begin_submission() else {
write_bounded(&mut stream, &ServerFrame::ShuttingDown).await?;
return Ok(());
};
let caller_env = Arc::new(platform::environment::from_text(&env));
match handle_submit(
&coordinator,
&run_tx,
&repo,
&selection,
&options,
caller_env,
request_key.as_ref(),
request_args_hash.as_deref(),
&origin,
)
.await
{
Ok((run, accepted)) => ServerFrame::Submitted {
run,
accepted,
owner: coordinator.owner(),
},
Err(message) => ServerFrame::Error(message),
}
}
ClientFrame::CancelRun { repo, run_id } => {
match handle_cancel(&coordinator, &repo, &run_id).await {
Ok(ack) => ServerFrame::Cancelled(ack),
Err(message) => ServerFrame::Error(message),
}
}
ClientFrame::ShutdownIfIdle => {
if coordinator.try_begin_shutdown() {
shutdown.cancel();
ServerFrame::Ack
} else {
ServerFrame::Busy
}
}
ClientFrame::Hello { .. } => ServerFrame::Error("Unexpected duplicate Hello.".into()),
};
write_bounded(&mut stream, &response).await
}
#[expect(
clippy::too_many_arguments,
reason = "forwarding all SubmitRun RPC fields into reservation"
)]
async fn handle_submit(
coordinator: &Arc<Coordinator>,
run_tx: &tokio::sync::mpsc::UnboundedSender<SpawnedRun>,
repo: &Path,
selection: &crate::project::selection::Selection,
options: &crate::project::VerifyOptions,
caller_env: Arc<std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>>,
request_key: Option<&crate::types::RequestKey>,
request_args_hash: Option<&str>,
origin: &crate::runs::Origin,
) -> Result<(RunId, bool), String> {
if let Some(key) = request_key
&& let Some(existing) = coordinator
.receipts()
.keyed_run(repo, key, request_args_hash)
.await?
{
return Ok((existing, false));
}
let reserved = crate::project::verify::reserve_in(
repo,
coordinator.state_dir(),
coordinator.receipts(),
selection,
options,
request_key,
request_args_hash,
origin,
Some(caller_env.as_ref()),
Some(coordinator.owner()),
)
.await?;
let (run, accepted) = match reserved {
crate::project::verify::Reserved::Accepted(run) => (*run, true),
crate::project::verify::Reserved::Existing(id) => return Ok((id, false)),
};
let id = run.id.clone();
if let Err(error) = process::ensure_worker_stderr(coordinator.state_dir(), &id) {
let message = error.to_string();
let _ = coordinator
.receipts()
.retire_worker(&id, FailureCode::PreparationFailed)
.await;
let _ = worker::fail(
coordinator.receipts(),
&id,
FailureCode::PreparationFailed,
message.clone(),
)
.await;
return Err(message);
}
let cancellation = CancellationToken::new();
coordinator.register_run(id.clone(), cancellation.clone());
if let Ok(saved) = store::run_control::observe(coordinator.state_dir(), &id).await
&& saved.control.as_ref().is_some_and(Control::is_cancelling)
{
cancellation.cancel();
}
if run_tx
.send(SpawnedRun {
run,
caller_env,
cancellation,
})
.is_err()
{
coordinator.finish_run(&id);
let message = "Verify engine stopped before accepting Run.".to_owned();
let _ = coordinator
.receipts()
.retire_worker(&id, FailureCode::OwnerDied)
.await;
let _ = worker::fail(
coordinator.receipts(),
&id,
FailureCode::OwnerDied,
message.clone(),
)
.await;
return Err(message);
}
Ok((id, accepted))
}
async fn handle_cancel(
coordinator: &Arc<Coordinator>,
repo: &Path,
id: &RunId,
) -> Result<CancelAcknowledgement, String> {
let saved = store::run_control::observe(coordinator.state_dir(), id).await?;
if !platform::paths_equal(&saved.repo, repo) {
return Err("Run not found in this repository.".into());
}
if super::owner_died(saved.status, saved.control.as_ref())? {
let view = store::read_run(coordinator.state_dir(), id).await?;
worker::recover_in(coordinator.receipts(), coordinator.state_dir(), &view).await?;
let reconciled = store::run_control::observe(coordinator.state_dir(), id).await?;
let counts = observe::counts(reconciled.counts);
return Ok(CancelAcknowledgement {
run: id.clone(),
state: observe::state_for(reconciled.status, reconciled.control.as_ref(), &counts),
cancellation_requested: reconciled
.control
.as_ref()
.is_some_and(Control::is_cancelling),
});
}
let (status, control) = coordinator.receipts().request_cancel(id).await?;
coordinator.cancel_active(id);
let counts = observe::counts(saved.counts);
Ok(CancelAcknowledgement {
run: id.clone(),
state: observe::state_for(status, control.as_ref(), &counts),
cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
})
}
async fn watch_db_cancellation(state: &Path, id: &RunId, cancellation: CancellationToken) {
let mut changes = crate::changes::Subscription::new(state).await;
loop {
if let Ok(saved) = store::run_control::observe(state, id).await
&& (!saved.status.is_open()
|| saved.control.as_ref().is_some_and(Control::is_cancelling))
{
cancellation.cancel();
break;
}
tokio::select! {
_ = cancellation.cancelled() => break,
_ = changes.next_state() => {}
}
}
let _ = changes.close().await;
}
async fn execute_managed_run(
coordinator: Arc<Coordinator>,
spawned: SpawnedRun,
before_run: Option<BeforeRunHook>,
) {
let id = spawned.run.id.clone();
let watcher_stop = spawned.cancellation.child_token();
let db_watch_state = coordinator.state_dir().to_path_buf();
let db_watch_id = id.clone();
let db_watch_cancel = spawned.cancellation.clone();
let watcher = tokio::spawn(async move {
tokio::select! {
_ = watcher_stop.cancelled() => {}
_ = watch_db_cancellation(&db_watch_state, &db_watch_id, db_watch_cancel) => {}
}
});
let result = async {
if let Some(hook) = before_run {
hook(coordinator.state_dir(), &id).await?;
}
if spawned.cancellation.is_cancelled() {
return Err(crate::project::verify::Error::Preparation(
"Run was cancelled.".into(),
));
}
crate::project::verify::execute_in(
spawned.run,
coordinator.receipts(),
spawned.cancellation.clone(),
Some(spawned.caller_env),
Some(coordinator.clone()),
)
.await
}
.await;
watcher.abort();
let _ = watcher.await;
if let Err(error) = result {
let code = if spawned.cancellation.is_cancelled() {
FailureCode::Cancelled
} else {
error.code()
};
let message = error.to_string();
process::append_worker_diagnostic(coordinator.state_dir(), &id, &message);
let _ = coordinator.receipts().retire_worker(&id, code).await;
let _ = worker::fail(coordinator.receipts(), &id, code, message).await;
}
coordinator.finish_run(&id);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project::selection::Selection;
use crate::project::verify::VerifyOptions;
const TEST_TIMEOUT: Duration = Duration::from_secs(10);
async fn connect_when_ready(endpoint: &EngineEndpoint) -> Stream {
let deadline = tokio::time::Instant::now() + TEST_TIMEOUT;
loop {
match endpoint.connect().await {
Ok(stream) => return stream,
Err(_) if tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(20)).await;
}
Err(error) => panic!("engine failed to listen: {error}"),
}
}
}
#[tokio::test]
async fn incompatible_hello_accepts_shutdown_if_idle_and_exits_cleanly() {
let dir = crate::test_os::tempdir();
let state = dir.path().join("state");
std::fs::create_dir_all(&state).unwrap();
let engine_state = state.clone();
let server = tokio::spawn(async move { serve(&engine_state).await });
let endpoint = EngineEndpoint::new(&state).unwrap();
let mut stream = connect_when_ready(&endpoint).await;
write_frame(
&mut stream,
&ClientFrame::Hello {
version: VERSION + 1,
identity: endpoint.identity.clone(),
},
)
.await
.unwrap();
let reply: ServerFrame = read_frame(&mut stream).await.unwrap();
assert!(
matches!(
reply,
ServerFrame::Incompatible { server_version } if server_version == VERSION
),
"expected Incompatible, got {reply:?}"
);
write_frame(&mut stream, &ClientFrame::ShutdownIfIdle)
.await
.unwrap();
let ack: ServerFrame = read_frame(&mut stream).await.unwrap();
assert!(
matches!(ack, ServerFrame::Ack),
"expected Ack on idle engine, got {ack:?}"
);
drop(stream);
tokio::time::timeout(TEST_TIMEOUT, server)
.await
.expect("engine exits promptly after ShutdownIfIdle")
.unwrap()
.unwrap();
}
#[tokio::test]
async fn hung_post_hello_client_does_not_wedge_idle_shutdown() {
let dir = crate::test_os::tempdir();
let state = dir.path().join("state");
std::fs::create_dir_all(&state).unwrap();
let engine_state = state.clone();
let server = tokio::spawn(async move { serve(&engine_state).await });
let endpoint = EngineEndpoint::new(&state).unwrap();
let mut hung = connect_when_ready(&endpoint).await;
write_frame(
&mut hung,
&ClientFrame::Hello {
version: VERSION,
identity: endpoint.identity.clone(),
},
)
.await
.unwrap();
let reply: ServerFrame = read_frame(&mut hung).await.unwrap();
assert!(matches!(reply, ServerFrame::Welcome { .. }));
let mut control = endpoint.connect().await.unwrap();
write_frame(
&mut control,
&ClientFrame::Hello {
version: VERSION,
identity: endpoint.identity.clone(),
},
)
.await
.unwrap();
let ready: ServerFrame = read_frame(&mut control).await.unwrap();
assert!(matches!(ready, ServerFrame::Welcome { .. }));
write_frame(&mut control, &ClientFrame::ShutdownIfIdle)
.await
.unwrap();
let ack: ServerFrame = read_frame(&mut control).await.unwrap();
assert!(matches!(ack, ServerFrame::Ack));
drop(control);
tokio::time::timeout(TEST_TIMEOUT, server)
.await
.expect("hung client must not block engine shutdown")
.unwrap()
.unwrap();
drop(hung);
}
#[tokio::test]
async fn direct_db_cancellation_cancels_live_engine_run_and_incompatible_reports_busy() {
let dir = crate::test_os::tempdir();
let state = dir.path().join("state");
let repo = dir.path().join("repo");
std::fs::create_dir_all(&state).unwrap();
std::fs::create_dir_all(repo.join(".artifactize")).unwrap();
std::fs::write(repo.join("content.txt"), "hello").unwrap();
std::fs::write(
repo.join(".artifactize/index.artf"),
"artf app : files = {\n path = \"content.txt\"\n eval check : runtime(command = \"true\", args = []) = { title = \"Check\" }\n}\n",
)
.unwrap();
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel::<RunId>();
let entered_tx = Arc::new(std::sync::Mutex::new(Some(entered_tx)));
let gate = Arc::new(tokio::sync::Notify::new());
let gate_hook = gate.clone();
let hook: BeforeRunHook = Arc::new(move |_state, id| {
let id = id.clone();
let entered_tx = entered_tx.clone();
let gate = gate_hook.clone();
Box::pin(async move {
if let Some(tx) = entered_tx.lock().unwrap().take() {
let _ = tx.send(id);
}
gate.notified().await;
Ok(())
})
});
let engine_state = state.clone();
let server = tokio::spawn(async move { serve_with_hook(&engine_state, Some(hook)).await });
let endpoint = EngineEndpoint::new(&state).unwrap();
let mut client = connect_when_ready(&endpoint).await;
write_frame(
&mut client,
&ClientFrame::Hello {
version: VERSION,
identity: endpoint.identity.clone(),
},
)
.await
.unwrap();
assert!(matches!(
read_frame(&mut client).await.unwrap(),
ServerFrame::Welcome { .. }
));
write_frame(
&mut client,
&ClientFrame::SubmitRun {
repo: repo.clone(),
selection: Selection::All,
options: Box::new(VerifyOptions::default()),
request_key: None,
request_args_hash: None,
env: platform::environment::snapshot_text(),
origin: crate::runs::Origin::Cli,
},
)
.await
.unwrap();
let run_id = match read_frame(&mut client).await.unwrap() {
ServerFrame::Submitted { run, .. } => run,
other => panic!("expected Submitted, got {other:?}"),
};
drop(client);
let started_id = tokio::time::timeout(TEST_TIMEOUT, entered_rx)
.await
.expect("before_run hook fires")
.unwrap();
assert_eq!(started_id, run_id);
let mut peer = endpoint.connect().await.unwrap();
write_frame(
&mut peer,
&ClientFrame::Hello {
version: VERSION + 1,
identity: endpoint.identity.clone(),
},
)
.await
.unwrap();
assert!(matches!(
read_frame(&mut peer).await.unwrap(),
ServerFrame::Incompatible { .. }
));
write_frame(&mut peer, &ClientFrame::ShutdownIfIdle)
.await
.unwrap();
assert!(
matches!(read_frame(&mut peer).await.unwrap(), ServerFrame::Busy),
"active engine must refuse ShutdownIfIdle with Busy"
);
drop(peer);
let receipts = Receipts::open(&state, &repo).await.unwrap();
receipts.request_cancel(&run_id).await.unwrap();
receipts.close().await.unwrap();
tokio::time::sleep(Duration::from_millis(80)).await;
gate.notify_waiters();
tokio::time::timeout(TEST_TIMEOUT, server)
.await
.expect("engine drains after cancelled Run settles")
.unwrap()
.unwrap();
let view = store::read_run(&state, &run_id).await.unwrap();
assert_eq!(view.run.status(), crate::types::RunStatus::Error);
}
}