Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions docs/workflows.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,21 @@ calls matched to their answers anyway.
`timed_out`, `cancelled`), 20 unless `workflow-kept-runs` says otherwise; when
a run starts, older settled runs' folders are removed. A run still `running` is never removed, since it may be resumed.

**Who drives a run.** One engine process drives a run at a time, and stamps
the run's `driver.json` every 10 seconds with its owner id (the one delegate
links carry). A stamp younger than 45 seconds from another process means that
process drives it, so the app's engine and the background server, which share
one config folder, never drive the same run; a resume while it does is refused.
`<config>/workflows/running/<run id>` names the thread of every run still
`running`, so an engine finds them without reading every thread (#4387).

**When the engine starts** it looks at those runs, then again every minute, and
takes up each one no live process drives whose starting thread is at Full
access, through its own orchestration answers, with no app and without the
thread being opened. A run of a thread below Full access waits for its thread
as before. After a sleep or a clock jump nothing is taken up until the next
look.

**When a run resumes.** The engine resumes the runs a thread left `running`
when that thread registers with the engine's orchestrator hub (the thread is
opened or started on a harness with the orchestration tools). Until then
Expand Down
1 change: 1 addition & 0 deletions rustcode/engine/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,7 @@ impl AcpEngine {
crate::data_store::warm();
// Links an earlier engine was running when it died are not running now.
tokio::task::spawn_blocking(crate::data_store::interrupt_orphaned_links);
crate::workflow::keep_resuming();
let server = AcpServer::new(auto_approve)?;
// Apps connected through `rc mcp-connect` find this engine by its
// hub, so it listens from the start when any are connected.
Expand Down
6 changes: 6 additions & 0 deletions rustcode/engine/src/orchestration/local_threads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,12 @@ impl Access {
}
}

/// Whether `session_id` may start delegate threads with no app to approve
/// them: only at Full access (`delegation`).
pub(crate) fn starts_threads_without_app(session_id: &str) -> bool {
access_of(session_id) == Access::Full
}

/// The access a thread runs at, from the records the engine keeps: the access
/// of its last prompt (`sessions::save_session_access`), else its own `/yolo`,
/// else Settings › General › Default access, which the app seeds into
Expand Down
197 changes: 194 additions & 3 deletions rustcode/engine/src/workflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//! app reads a run's summary ([`run_summary`]), stops it and claims the one
//! wake that tells the starting thread it ended ([`claim_wake`]).

mod driver;
mod reply;
mod run;
mod sandbox;
Expand Down Expand Up @@ -305,20 +306,114 @@ fn announce(thread: &str, run_id: &str) {
/// Drive `record`'s run in the background until it ends.
fn spawn(store: Store, runner: Arc<dyn AgentRunner>, record: RunRecord, source: String) {
let id = record.id.clone();
let run = Run::new(store, runner, record);
let owner = crate::data_store::engine_owner();
driver::stamp(&store, &id, owner, driver::now());
if let Some(index) = driver::index() {
driver::mark_running(&index, &record.thread, &id);
}
let run = Run::new(store.clone(), runner, record);
let stopper = run.stopper();
ACTIVE
.lock()
.unwrap_or_else(|error| error.into_inner())
.insert(id.clone(), run.stopper());
.insert(id.clone(), stopper.clone());
let beat_store = store.clone();
let beat_id = id.clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = stopper.cancelled() => break,
_ = tokio::time::sleep(driver::BEAT_EVERY) => {}
}
if !active(&beat_id) {
break;
}
driver::stamp(&beat_store, &beat_id, owner, driver::now());
}
});
tokio::spawn(async move {
drive(run, source).await;
ACTIVE
.lock()
.unwrap_or_else(|error| error.into_inner())
.remove(&id);
if store
.load(&id)
.is_some_and(|record| record.status.settled())
&& let Some(index) = driver::index()
{
driver::unmark(&index, &id);
}
});
}

/// Take up, every [`driver::SWEEP_EVERY`] for the life of the engine, the
/// runs a restart left `running` that no live process drives, when their
/// thread may start workers without the app (Full access). Called once when
/// the engine starts (#4387).
pub(crate) fn keep_resuming() {
use std::sync::atomic::{AtomicBool, Ordering};
static SWEEPING: AtomicBool = AtomicBool::new(false);
if SWEEPING.swap(true, Ordering::SeqCst) || tokio::runtime::Handle::try_current().is_err() {
return;
}
tokio::spawn(async {
loop {
if !crate::data_store::clock_recently_jumped()
&& let Some(index) = driver::index()
{
let _ = tokio::task::spawn_blocking(move || {
sweep(
&index,
|thread| Store::for_thread(thread),
|thread| {
crate::orchestration::local_threads::starts_threads_without_app(thread)
},
|thread| ThreadRunner::new(thread, None, crate::orchestration::VERSION),
)
})
.await;
}
tokio::time::sleep(driver::SWEEP_EVERY).await;
}
});
}

/// One pass over the running-run index: forget settled runs, resume the
/// undriven ones `may_start` allows. How many were resumed.
fn sweep(
index: &std::path::Path,
store_of: impl Fn(&str) -> Option<Store>,
may_start: impl Fn(&str) -> bool,
runner_for: impl Fn(&str) -> Arc<dyn AgentRunner>,
) -> usize {
let me = crate::data_store::engine_owner();
let mut resumed = 0;
for (thread, run_id) in driver::marked(index) {
let Some(store) = store_of(&thread) else {
driver::unmark(index, &run_id);
continue;
};
match driver::verdict(
&store,
&run_id,
me,
driver::now(),
active(&run_id),
may_start(&thread),
) {
driver::Verdict::Forget => driver::unmark(index, &run_id),
driver::Verdict::Leave => {}
driver::Verdict::Resume => {
if resume_one(&store, &run_id, runner_for(&thread)).unwrap_or(false) {
resumed += 1;
}
}
}
}
resumed
}

/// Answer one workflow tool call made by `thread`: start, read or stop a run.
/// The engine's hub calls it for a harness's `rustcode` MCP server, and the
/// built-in harness for its own turn (#3943). Only a tool call from the owning
Expand Down Expand Up @@ -423,10 +518,31 @@ fn resume_in(store: &Store, runner: &Arc<dyn AgentRunner>) -> usize {
store
.list()
.into_iter()
.filter(|record| resume_one(store, &record.id, runner.clone()).unwrap_or(false))
.filter(
|record| match resume_one(store, &record.id, runner.clone()) {
Ok(resumed) => resumed,
Err(_) => {
retry_after_stale(store.clone(), record.id.clone(), runner.clone());
false
}
},
)
.count()
}

/// Try `run_id` again once a driver that died just before this engine started
/// has gone stale, so a thread that registers right after a restart still gets
/// its run back.
fn retry_after_stale(store: Store, run_id: String, runner: Arc<dyn AgentRunner>) {
if tokio::runtime::Handle::try_current().is_err() {
return;
}
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(driver::STALE_MS as u64 + 1_000)).await;
let _ = resume_one(&store, &run_id, runner);
});
}

// Serialize the transition between a saved run and a live driver.
static DRIVER_TRANSITION: Mutex<()> = Mutex::new(());

Expand Down Expand Up @@ -479,6 +595,15 @@ fn resume_one(store: &Store, run_id: &str, runner: Arc<dyn AgentRunner>) -> Resu
if record.status != RunStatus::Running || active(run_id) {
return Ok(false);
}
if driver::held_elsewhere(
driver::load(store, run_id).as_ref(),
crate::data_store::engine_owner(),
driver::now(),
) {
return Err(format!(
"run {run_id} is driven by another RustCode process on this computer"
));
}
let source = store
.script(run_id)
.ok_or_else(|| format!("no saved script for run {run_id}"))?;
Expand Down Expand Up @@ -1079,6 +1204,72 @@ mod tests {
assert_eq!(resume_version(false, 0), engine);
}

#[tokio::test]
async fn a_sweep_resumes_only_undriven_runs_its_thread_may_drive_and_forgets_settled_ones() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().join("workflows"));
let index = driver::index_at(&dir.path().join("config"));
let (echo, runner) = echo();
let limits = Limits {
concurrency: 1,
call_budget: 5,
timeout_secs: 30,
};
let thread = "1784626803679";
let record = new_record(thread, None, Value::Null, limits);
store
.create(&record, r#"return await agent("one");"#)
.unwrap();
driver::mark_running(&index, thread, &record.id);
let store_of = |_: &str| Some(store.clone());
let runner_for = |_: &str| runner.clone();

assert_eq!(sweep(&index, store_of, |_| false, runner_for), 0);
assert_eq!(driver::marked(&index).len(), 1);

driver::stamp(&store, &record.id, "another-process", driver::now());
assert_eq!(sweep(&index, store_of, |_| true, runner_for), 0);
assert_eq!(echo.started.load(Ordering::SeqCst), 0);

driver::stamp(
&store,
&record.id,
"another-process",
driver::now() - driver::STALE_MS - 1,
);
assert_eq!(sweep(&index, store_of, |_| true, runner_for), 1);
let finished = settled(&store, &record.id).await;
assert_eq!(finished.status, RunStatus::Done, "{:?}", finished.error);
assert_eq!(echo.started.load(Ordering::SeqCst), 1);

assert_eq!(sweep(&index, store_of, |_| true, runner_for), 0);
assert!(driver::marked(&index).is_empty());
}

#[tokio::test]
async fn a_resume_is_refused_while_another_process_drives_the_run() {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().join("workflows"));
let (echo, runner) = echo();
let record = new_record(
"1784626803679",
None,
Value::Null,
Limits {
concurrency: 1,
call_budget: 5,
timeout_secs: 30,
},
);
store
.create(&record, r#"return await agent("one");"#)
.unwrap();
driver::stamp(&store, &record.id, "another-process", driver::now());
let refused = resume_one(&store, &record.id, runner).unwrap_err();
assert!(refused.contains("another RustCode process"), "{refused}");
assert_eq!(echo.started.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn status_waits_for_a_run_to_end_and_answers_at_the_deadline_otherwise() {
let dir = tempfile::tempdir().unwrap();
Expand Down
Loading
Loading