From 311feb2fffb9dd0178b45db2e8e4331415ef4afa Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Wed, 25 Nov 2026 23:31:46 +0100 Subject: [PATCH] fix(engine): resume running workflow runs when the engine starts --- docs/workflows.md | 15 ++ rustcode/engine/src/acp.rs | 1 + .../engine/src/orchestration/local_threads.rs | 6 + rustcode/engine/src/workflow.rs | 197 +++++++++++++++- rustcode/engine/src/workflow/driver.rs | 210 ++++++++++++++++++ 5 files changed, 426 insertions(+), 3 deletions(-) create mode 100644 rustcode/engine/src/workflow/driver.rs diff --git a/docs/workflows.md b/docs/workflows.md index 7431bde5f..2874281ff 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -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. +`/workflows/running/` 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 diff --git a/rustcode/engine/src/acp.rs b/rustcode/engine/src/acp.rs index 28658ac30..15b7e014b 100644 --- a/rustcode/engine/src/acp.rs +++ b/rustcode/engine/src/acp.rs @@ -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. diff --git a/rustcode/engine/src/orchestration/local_threads.rs b/rustcode/engine/src/orchestration/local_threads.rs index 173cfc57d..f92ecb7b9 100644 --- a/rustcode/engine/src/orchestration/local_threads.rs +++ b/rustcode/engine/src/orchestration/local_threads.rs @@ -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 diff --git a/rustcode/engine/src/workflow.rs b/rustcode/engine/src/workflow.rs index c21760829..2cd063d45 100644 --- a/rustcode/engine/src/workflow.rs +++ b/rustcode/engine/src/workflow.rs @@ -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; @@ -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, 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, + may_start: impl Fn(&str) -> bool, + runner_for: impl Fn(&str) -> Arc, +) -> 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 @@ -423,10 +518,31 @@ fn resume_in(store: &Store, runner: &Arc) -> 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) { + 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(()); @@ -479,6 +595,15 @@ fn resume_one(store: &Store, run_id: &str, runner: Arc) -> 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}"))?; @@ -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(); diff --git a/rustcode/engine/src/workflow/driver.rs b/rustcode/engine/src/workflow/driver.rs new file mode 100644 index 000000000..f9803c2da --- /dev/null +++ b/rustcode/engine/src/workflow/driver.rs @@ -0,0 +1,210 @@ +//! Who drives a workflow run, and which runs are waiting for a driver (#4387). +//! +//! A run is driven by one engine process at a time. That process stamps the +//! run's `driver.json` every [`BEAT_EVERY`] with its owner id +//! (`data_store::engine_owner`), the same id delegate links carry, so the +//! app's engine and the background server, which share one config folder, +//! can tell a run another process drives from one whose process died. A +//! stamp older than [`STALE_MS`] is a dead driver's. +//! +//! The beat is kept beside `run.json`, not in it: the run's driver replaces +//! `run.json` whole on every change, and a beat written into it by a second +//! writer would be undone by the next change. +//! +//! `/workflows/running/` holds the id of the thread that +//! started each run still `running`, so an engine that starts can find the +//! runs a restart left behind without reading every thread's folder. A marker +//! whose run settled or disappeared is removed by the next sweep. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use super::store::{Store, now_ms}; + +/// How often a driving process stamps its runs. +pub(super) const BEAT_EVERY: Duration = Duration::from_secs(10); +/// How old a stamp may be before the run counts as undriven. +pub(super) const STALE_MS: i64 = 45_000; +/// How often an engine looks for undriven runs it may take up. +pub(super) const SWEEP_EVERY: Duration = Duration::from_secs(60); + +const DRIVER_FILE: &str = "driver.json"; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct Driver { + pub owner: String, + pub beat_ms: i64, +} + +/// Whether `driver` is a live process other than `me`. +pub(super) fn held_elsewhere(driver: Option<&Driver>, me: &str, at: i64) -> bool { + driver.is_some_and(|driver| driver.owner != me && at - driver.beat_ms <= STALE_MS) +} + +pub(super) fn load(store: &Store, run_id: &str) -> Option { + let path = store.run_dir(run_id)?.join(DRIVER_FILE); + serde_json::from_slice(&std::fs::read(path).ok()?).ok() +} + +pub(super) fn stamp(store: &Store, run_id: &str, owner: &str, at: i64) { + let Some(dir) = store.run_dir(run_id) else { + return; + }; + let driver = Driver { + owner: owner.to_owned(), + beat_ms: at, + }; + if let Ok(text) = serde_json::to_vec(&driver) { + let _ = crate::worktrees::write_atomic(&dir.join(DRIVER_FILE), &text); + } +} + +/// The folder of running-run markers under `config`. +pub(super) fn index_at(config: &Path) -> PathBuf { + config.join("workflows").join("running") +} + +/// The index in the user's config folder. Unit tests pass a folder of their +/// own to [`index_at`] and never write the user's. +pub(super) fn index() -> Option { + if cfg!(test) { + return None; + } + crate::config::get_config_dir().map(|config| index_at(&config)) +} + +/// Note that `thread`'s run `run_id` is running. +pub(super) fn mark_running(index: &Path, thread: &str, run_id: &str) { + if !super::store::valid_run_id(run_id) || std::fs::create_dir_all(index).is_err() { + return; + } + let _ = crate::worktrees::write_atomic(&index.join(run_id), thread.as_bytes()); +} + +pub(super) fn unmark(index: &Path, run_id: &str) { + if super::store::valid_run_id(run_id) { + let _ = std::fs::remove_file(index.join(run_id)); + } +} + +/// Every `(thread, run id)` the index names. +pub(super) fn marked(index: &Path) -> Vec<(String, String)> { + let Ok(entries) = std::fs::read_dir(index) else { + return Vec::new(); + }; + let mut runs: Vec<(String, String)> = entries + .flatten() + .filter_map(|entry| { + let run_id = entry.file_name().to_str()?.to_owned(); + if !super::store::valid_run_id(&run_id) { + return None; + } + let thread = std::fs::read_to_string(entry.path()).ok()?; + let thread = thread.trim().to_owned(); + rustcode_session::valid_session_id(&thread).then_some((thread, run_id)) + }) + .collect(); + runs.sort(); + runs +} + +/// What a sweep should do with one marked run. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Verdict { + /// The run settled or is gone: drop its marker. + Forget, + /// Driven here or by a live process, or its thread cannot start workers + /// without the app: leave it. + Leave, + /// Undriven and its thread may start workers: take it up. + Resume, +} + +pub(super) fn verdict( + store: &Store, + run_id: &str, + me: &str, + at: i64, + driven_here: bool, + may_start_workers: bool, +) -> Verdict { + let Some(record) = store.load(run_id) else { + return Verdict::Forget; + }; + if record.status.settled() { + return Verdict::Forget; + } + if driven_here || held_elsewhere(load(store, run_id).as_ref(), me, at) || !may_start_workers { + return Verdict::Leave; + } + Verdict::Resume +} + +pub(super) fn now() -> i64 { + now_ms() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn driver(owner: &str, beat_ms: i64) -> Driver { + Driver { + owner: owner.to_owned(), + beat_ms, + } + } + + #[test] + fn only_another_process_with_a_fresh_stamp_holds_a_run() { + let at = 1_000_000; + assert!(!held_elsewhere(None, "me", at)); + assert!(!held_elsewhere(Some(&driver("me", at)), "me", at)); + assert!(held_elsewhere( + Some(&driver("other", at - 10_000)), + "me", + at + )); + assert!(held_elsewhere( + Some(&driver("other", at - STALE_MS)), + "me", + at + )); + assert!(!held_elsewhere( + Some(&driver("other", at - STALE_MS - 1)), + "me", + at + )); + } + + #[test] + fn a_stamp_is_read_back_from_the_run_folder() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::at(dir.path().to_path_buf()); + std::fs::create_dir_all(dir.path().join("wf-1-2")).unwrap(); + assert_eq!(load(&store, "wf-1-2"), None); + stamp(&store, "wf-1-2", "owner-a", 42); + assert_eq!(load(&store, "wf-1-2"), Some(driver("owner-a", 42))); + } + + #[test] + fn the_index_names_each_marked_run_with_its_thread_until_unmarked() { + let dir = tempfile::tempdir().unwrap(); + let index = index_at(dir.path()); + assert!(marked(&index).is_empty()); + mark_running(&index, "1784626803679", "wf-2-b"); + mark_running(&index, "1784626803679", "wf-1-a"); + mark_running(&index, "1784626803679", "../escape"); + assert_eq!( + marked(&index), + vec![ + ("1784626803679".to_owned(), "wf-1-a".to_owned()), + ("1784626803679".to_owned(), "wf-2-b".to_owned()), + ] + ); + unmark(&index, "wf-1-a"); + assert_eq!(marked(&index).len(), 1); + } +}