Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(workflow): scope cancellation handoffs

Steven Enamakel80de570a24cc
diff --git a/.sdd-progress.md b/.sdd-progress.md
index 3b65aa35bb..dbc714052f 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -60,6 +60,19 @@ OpenHuman lib test target still fails before workflow tests on unrelated
pre-existing fixture/API migration diagnostics; normal `cargo check -p
openhuman` is in progress on the shared build lock.
+O5 takeover-race follow-up: complete locally, pending commit/review. A new
+lease owner durably resets abandoned `running` phase state through its fenced
+CAS before scheduling, so crash recovery retries rather than declaring a
+dependency deadlock; registered child IDs remain deduplicated. Fenced engines
+now leave silently when a replacement owns the run and cannot emit/flush a
+false terminal failure. OpenHuman cancellation signals carry generations;
+start/resume loops retain their exact signal, cleanup only removes its matching
+generation, and stop only cancels the signal it observed before its successful
+lifecycle CAS. The SQLite ledger, orchestration engine, graph sink, registry
+interleaving, and scheduler-preview topology regressions are covered. Fresh
+`tinyagents-session` (63 + doctest) and `tinyagents-orchestration` (28) tests
+pass; the root check is running against the shared build lock.
+
Session extraction S1-S4: in progress. `tinyagents-session::transcript` owns
the neutral append-only JSONL codec, paths, display/model readers, metadata,
history and locator interfaces. Its public history API now stays entirely on
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
index 3472cff55f..435f9ed35d 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/cancel.rs
@@ -1,66 +1,131 @@
//! Process-wide cancellation registry for running workflow engine loops.
//!
-//! `stop_workflow_run` flips the flag; the engine loop checks it between
-//! phases and aborts in-flight child tasks via the orchestration session
-//! before marking the run `Interrupted`.
+//! A stop/resume hand-off replaces the per-run signal. Every loop retains its
+//! exact generation, so late cleanup from a fenced loop cannot erase or cancel
+//! the signal now owned by its replacement.
use std::collections::HashMap;
-use std::sync::atomic::AtomicBool;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use tinyagents_harness::CancellationToken;
-/// Per-run pair of legacy poll flag and crate-native cancellation token.
+/// One generation of a run's legacy poll flag and crate-native token.
#[derive(Clone)]
pub(super) struct WorkflowCancelSignal {
+ generation: u64,
pub(super) flag: Arc<AtomicBool>,
pub(super) token: CancellationToken,
}
-fn cancel_registry() -> &'static Mutex<HashMap<String, WorkflowCancelSignal>> {
- static REGISTRY: OnceLock<Mutex<HashMap<String, WorkflowCancelSignal>>> = OnceLock::new();
- REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
+#[derive(Default)]
+struct CancelRegistry {
+ next_generation: u64,
+ signals: HashMap<String, WorkflowCancelSignal>,
}
-/// Register (or reuse) a cancellation flag for `run_id`.
+fn cancel_registry() -> &'static Mutex<CancelRegistry> {
+ static REGISTRY: OnceLock<Mutex<CancelRegistry>> = OnceLock::new();
+ REGISTRY.get_or_init(|| Mutex::new(CancelRegistry::default()))
+}
+
+fn fresh_signal(registry: &mut CancelRegistry) -> WorkflowCancelSignal {
+ registry.next_generation = registry.next_generation.wrapping_add(1);
+ WorkflowCancelSignal {
+ generation: registry.next_generation,
+ flag: Arc::new(AtomicBool::new(false)),
+ token: CancellationToken::new(),
+ }
+}
+
+/// Register a signal for a new loop, preserving a stop intent that was
+/// recorded before that loop was scheduled.
pub(super) fn register_cancel_signal(run_id: &str) -> WorkflowCancelSignal {
- let mut map = cancel_registry().lock().expect("cancel registry poisoned");
- map.entry(run_id.to_string())
- .or_insert_with(|| WorkflowCancelSignal {
- flag: Arc::new(AtomicBool::new(false)),
- token: CancellationToken::new(),
- })
- .clone()
+ let mut registry = cancel_registry().lock().expect("cancel registry poisoned");
+ if let Some(signal) = registry.signals.get(run_id) {
+ return signal.clone();
+ }
+ let signal = fresh_signal(&mut registry);
+ registry.signals.insert(run_id.to_owned(), signal.clone());
+ signal
}
-/// Register (or reuse) a cancellation flag for `run_id`.
-pub(super) fn register_cancel_flag(run_id: &str) -> Arc<AtomicBool> {
- register_cancel_signal(run_id).flag
+/// Replace a completed or fenced loop's signal with a new generation. Resume
+/// calls this only after its durable lifecycle CAS has won.
+pub(super) fn replace_cancel_signal(run_id: &str) -> WorkflowCancelSignal {
+ let mut registry = cancel_registry().lock().expect("cancel registry poisoned");
+ let signal = fresh_signal(&mut registry);
+ registry.signals.insert(run_id.to_owned(), signal.clone());
+ signal
}
-/// Look up an existing cancellation signal for `run_id`, if one is registered.
+/// Look up the actual current signal for a run, if any.
pub(super) fn lookup_cancel_signal(run_id: &str) -> Option<WorkflowCancelSignal> {
cancel_registry()
.lock()
.expect("cancel registry poisoned")
+ .signals
.get(run_id)
.cloned()
}
-/// Look up an existing cancellation flag for `run_id`, if one is registered.
-pub(super) fn lookup_cancel_flag(run_id: &str) -> Option<Arc<AtomicBool>> {
- lookup_cancel_signal(run_id).map(|signal| signal.flag)
+/// Cancel this exact generation only while it remains current. Lifecycle
+/// callers retain the signal they observed before their durable CAS, so a
+/// losing stop cannot cancel a successor installed by resume.
+pub(super) fn cancel_signal_if_current(run_id: &str, signal: &WorkflowCancelSignal) -> bool {
+ let current = lookup_cancel_signal(run_id);
+ if !current
+ .as_ref()
+ .is_some_and(|current| current.generation == signal.generation)
+ {
+ return false;
+ }
+ signal.flag.store(true, Ordering::SeqCst);
+ signal.token.cancel();
+ true
}
-/// Look up an SDK cancellation token for `run_id`, if one is registered.
-pub(super) fn lookup_cancel_token(run_id: &str) -> Option<CancellationToken> {
- lookup_cancel_signal(run_id).map(|signal| signal.token)
+/// Whether this loop still owns the registry slot it was created with.
+pub(super) fn is_current_cancel_signal(run_id: &str, signal: &WorkflowCancelSignal) -> bool {
+ lookup_cancel_signal(run_id).is_some_and(|current| current.generation == signal.generation)
}
-/// Drop a run's cancellation flag once the engine loop is done with it.
-pub(super) fn clear_cancel_flag(run_id: &str) {
- cancel_registry()
- .lock()
- .expect("cancel registry poisoned")
- .remove(run_id);
+/// Drop a loop's signal only if no stop/resume hand-off has installed a newer
+/// generation in the meantime.
+pub(super) fn clear_cancel_signal(run_id: &str, signal: &WorkflowCancelSignal) {
+ let mut registry = cancel_registry().lock().expect("cancel registry poisoned");
+ if registry
+ .signals
+ .get(run_id)
+ .is_some_and(|current| current.generation == signal.generation)
+ {
+ registry.signals.remove(run_id);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resume_token_survives_old_cleanup_and_stop_cancels_the_successor() {
+ let run_id = format!("workflow-cancel-race-{}", uuid::Uuid::new_v4());
+ let old = register_cancel_signal(&run_id);
+ let successor = replace_cancel_signal(&run_id);
+
+ // Deterministic old-loop cleanup after resume must leave the newer
+ // generation installed.
+ clear_cancel_signal(&run_id, &old);
+ assert!(is_current_cancel_signal(&run_id, &successor));
+ assert!(!successor.token.is_cancelled());
+
+ // stop_workflow_run calls this helper after its lifecycle CAS; it
+ // reaches the current generation, not the old fenced-loop token.
+ assert!(cancel_signal_if_current(&run_id, &successor));
+ assert!(successor.token.is_cancelled());
+ assert!(successor.flag.load(Ordering::SeqCst));
+ assert!(!old.token.is_cancelled());
+
+ clear_cancel_signal(&run_id, &successor);
+ }
}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
index 806833efba..4ce684d3ba 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
@@ -17,7 +17,8 @@ use tinyagents_session::run_ledger::{
use super::super::ops::definition_by_id;
use super::cancel::{
- clear_cancel_flag, lookup_cancel_signal, register_cancel_flag, register_cancel_signal,
+ cancel_signal_if_current, clear_cancel_signal, is_current_cancel_signal, lookup_cancel_signal,
+ register_cancel_signal, replace_cancel_signal, WorkflowCancelSignal,
};
use super::LOG_TARGET;
use tinyagents_orchestration::workflow::WorkflowDefinition;
@@ -56,7 +57,7 @@ pub async fn start_workflow_run(
.initialise(run_id.clone(), &definition, input.clone(), parent_thread_id)
.context("persist initial workflow run")?;
- register_cancel_flag(&run_id);
+ let cancel = register_cancel_signal(&run_id);
// Spawn the engine loop. Clone what the task needs (the engine reloads
// config inside the task so it can build a real Agent without holding a
@@ -72,7 +73,7 @@ pub async fn start_workflow_run(
Ok(task_config) => {
crate::agent::turn_origin::with_inherited_origin(
inherited_origin,
- run_engine_loop(&task_config, &task_run_id, definition),
+ run_engine_loop(&task_config, &task_run_id, definition, cancel),
)
.await;
}
@@ -81,6 +82,7 @@ pub async fn start_workflow_run(
target: LOG_TARGET,
"[workflow_run_engine] start.config_load_failed run={task_run_id} err={err}"
);
+ clear_cancel_signal(&task_run_id, &cancel);
}
}
});
@@ -118,16 +120,10 @@ pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<Workf
return Ok(Some(run));
}
- if let Some(signal) = super::cancel::lookup_cancel_signal(id) {
- signal.flag.store(true, std::sync::atomic::Ordering::SeqCst);
- signal.token.cancel();
- } else {
- // No live loop (e.g. process restart) — register a flag anyway so a
- // future resume observes the stop intent.
- let signal = super::cancel::register_cancel_signal(id);
- signal.flag.store(true, std::sync::atomic::Ordering::SeqCst);
- signal.token.cancel();
- }
+ // Capture the exact live generation before fencing its durable row. If a
+ // concurrent resume wins instead, this stop's CAS fails and it must not
+ // cancel that successor's fresh token.
+ let cancel = lookup_cancel_signal(id);
let mut phase_states = run.phase_states.clone();
reset_running_phases(
@@ -154,6 +150,9 @@ pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<Workf
let updated = updated.ok_or_else(|| {
anyhow!("workflow run {id} changed while stop was being applied; reload and retry")
})?;
+ if let Some(cancel) = cancel.as_ref() {
+ let _ = cancel_signal_if_current(id, cancel);
+ }
log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.marked_interrupted run={id}");
Ok(Some(updated))
@@ -203,8 +202,7 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu
// Only replace the process-local signal after the durable hand-off won.
// Otherwise a losing resumer could erase the live driver's stop request.
- clear_cancel_flag(id);
- register_cancel_flag(id);
+ let cancel = replace_cancel_signal(id);
let task_run_id = id.to_string();
// Same inherit-only origin propagation as `start_workflow_run`: the resumed
@@ -215,7 +213,7 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu
Ok(task_config) => {
crate::agent::turn_origin::with_inherited_origin(
inherited_origin,
- run_engine_loop(&task_config, &task_run_id, definition),
+ run_engine_loop(&task_config, &task_run_id, definition, cancel),
)
.await;
}
@@ -224,6 +222,7 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu
target: LOG_TARGET,
"[workflow_run_engine] resume.config_load_failed run={task_run_id} err={err}"
);
+ clear_cancel_signal(&task_run_id, &cancel);
}
}
});
@@ -237,9 +236,12 @@ pub async fn resume_workflow_run(config: &Config, id: &str) -> Result<WorkflowRu
/// Separated from [`start_workflow_run`] so it can run on the spawned task with
/// an owned [`Config`]. Errors are recorded on the run row (status `Failed`)
/// rather than propagated — there is no caller to receive them.
-pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: WorkflowDefinition) {
- let cancel = lookup_cancel_signal(run_id).unwrap_or_else(|| register_cancel_signal(run_id));
-
+pub(crate) async fn run_engine_loop(
+ config: &Config,
+ run_id: &str,
+ definition: WorkflowDefinition,
+ cancel: WorkflowCancelSignal,
+) {
let model_override = get_workflow_run(&config.workspace_dir, run_id)
.ok()
.flatten()
@@ -272,7 +274,7 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W
run.revision,
);
}
- clear_cancel_flag(run_id);
+ clear_cancel_signal(run_id, &cancel);
return;
}
};
@@ -301,6 +303,13 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W
.unwrap_or_else(Err);
if let Err(err) = outcome {
+ if !is_current_cancel_signal(run_id, &cancel) {
+ log::debug!(
+ target: LOG_TARGET,
+ "[workflow_run_engine] loop.owner_lost run={run_id}; suppressing stale failure"
+ );
+ return;
+ }
log::error!(
target: LOG_TARGET,
"[workflow_run_engine] loop.failed run={run_id} err={err}"
@@ -334,7 +343,7 @@ pub(crate) async fn run_engine_loop(config: &Config, run_id: &str, definition: W
}
}
- clear_cancel_flag(run_id);
+ clear_cancel_signal(run_id, &cancel);
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/agent/schemas_tests.rs b/crates/openhuman-core/src/agent/schemas_tests.rs
index f15834b26d..2ad8855645 100644
--- a/crates/openhuman-core/src/agent/schemas_tests.rs
+++ b/crates/openhuman-core/src/agent/schemas_tests.rs
@@ -105,7 +105,10 @@ async fn graph_topologies_handler_exports_structural_reports() {
.filter_map(|g| g.get("name").and_then(Value::as_str))
.collect();
assert!(names.contains(&"delegation"), "saw {names:?}");
- assert!(names.contains(&"workflow_runs:scheduler"), "saw {names:?}");
+ assert!(
+ names.contains(&"workflow_runs:scheduler_preview"),
+ "saw {names:?}"
+ );
let agents = result
.get("agents")
.and_then(Value::as_array)
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
index 0a3204c3f7..e6cd7a5cf8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
@@ -22,7 +22,7 @@ fn all_topologies_includes_delegation_and_workflow_scheduler() {
let reports = all_graph_topologies();
for name in [
"delegation",
- "workflow_runs:scheduler",
+ "workflow_runs:scheduler_preview",
"spawn_parallel_graph",
] {
let report = reports
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 5cd6aac98e..1b1829950b 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 5cd6aac98efdfb124f305f9032443d104d74af0b
+Subproject commit 1b1829950b1626c3a1c740c6f54e7e36b2faaad2