Skip to content

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

fix(cron): fail closed when a schedule callback's bound context has expired

Steven Enamakeld323df8f9b44
diff --git a/crates/openhuman-core/src/cron/bus_host.rs b/crates/openhuman-core/src/cron/bus_host.rs
index b432be6d49..7c1b2e1b5c 100644
--- a/crates/openhuman-core/src/cron/bus_host.rs
+++ b/crates/openhuman-core/src/cron/bus_host.rs
@@ -136,6 +136,19 @@ impl Binding {
self.context.as_ref().and_then(Weak::upgrade)
}
+ /// Acquire the bound context for one callback. A missing weak reference is
+ /// an intentional unbound test/pre-boot context; an expired bound context
+ /// fails closed instead of borrowing the callback runtime's ambient one.
+ fn callback_context(&self) -> Result<Option<Arc<CoreContext>>, String> {
+ match &self.context {
+ Some(context) => context
+ .upgrade()
+ .map(Some)
+ .ok_or_else(|| "the schedule callback's bound context has expired".to_string()),
+ None => Ok(None),
+ }
+ }
+
/// Runs `fut` under the bound context. A context that has since been
/// dropped (its agent is no longer live) runs `fut` as the caller is.
pub(crate) async fn within<F: Future>(&self, fut: F) -> F::Output {
@@ -191,9 +204,16 @@ impl ScheduleHost {
/// One attempt of a shell or agent job, classified `retryable` or permanent.
async fn execute(&self, job: CronJob, run_id: String) -> BusResult<Attempt> {
tracing::debug!(job_id = %job.id, %run_id, "[cron:bus] Execute");
+ let context_pin = self
+ .binding
+ .callback_context()
+ .map_err(|error| bus_error("Execute", error))?;
let executor = Arc::clone(&self.executor);
self.binding
- .offload(async move { executor.execute(&job, &run_id).await })
+ .offload(async move {
+ let _context_pin = context_pin;
+ executor.execute(&job, &run_id).await
+ })
.await
.map_err(|e| bus_error("Execute", e))
}
@@ -201,9 +221,16 @@ impl ScheduleHost {
/// The final failure of a run: reported once.
async fn failed(&self, job: CronJob, run_id: String, attempt: Attempt) -> BusResult<()> {
tracing::debug!(job_id = %job.id, %run_id, "[cron:bus] Failed");
+ let context_pin = self
+ .binding
+ .callback_context()
+ .map_err(|error| bus_error("Failed", error))?;
let executor = Arc::clone(&self.executor);
self.binding
- .offload(async move { executor.failed(&job, &run_id, &attempt).await })
+ .offload(async move {
+ let _context_pin = context_pin;
+ executor.failed(&job, &run_id, &attempt).await
+ })
.await
.map_err(|e| bus_error("Failed", e))
}
@@ -211,10 +238,15 @@ impl ScheduleHost {
/// Send a finished run's output exactly once; the reply is its status.
async fn send(&self, job: CronJob, run_id: String, attempt: Attempt) -> BusResult<String> {
tracing::debug!(job_id = %job.id, %run_id, "[cron:bus] Send");
+ let context_pin = self
+ .binding
+ .callback_context()
+ .map_err(|error| bus_error("Send", error))?;
let binding = self.binding.clone();
let status: Result<DeliveryStatus, String> = self
.binding
.offload(async move {
+ let _context_pin = context_pin;
run_delivery::send(&binding, &job, &run_id, &attempt)
.await
.map_err(|error| error.to_string())
@@ -229,9 +261,16 @@ impl ScheduleHost {
/// Project the module's terminal decision without sending a second time.
async fn deliver(&self, projection: DeliveryProjection) -> BusResult<()> {
tracing::debug!(job_id = %projection.job.id, run_id = %projection.run_id, "[cron:bus] Deliver");
+ let context_pin = self
+ .binding
+ .callback_context()
+ .map_err(|error| bus_error("Deliver", error))?;
let binding = self.binding.clone();
self.binding
- .offload(async move { run_delivery::deliver(&binding, &projection).await })
+ .offload(async move {
+ let _context_pin = context_pin;
+ run_delivery::deliver(&binding, &projection).await
+ })
.await
.map_err(|e| bus_error("Deliver", e))?;
Ok(())
@@ -240,9 +279,16 @@ impl ScheduleHost {
/// A flow row's schedule tick (or a `system:<name>` job).
async fn schedule_trigger(&self, job: CronJob, run_id: String) -> BusResult<Attempt> {
tracing::debug!(job_id = %job.id, %run_id, "[cron:bus] ScheduleTrigger");
+ let context_pin = self
+ .binding
+ .callback_context()
+ .map_err(|error| bus_error("ScheduleTrigger", error))?;
let binding = self.binding.clone();
self.binding
- .offload(async move { run_delivery::trigger(&binding, &job, &run_id).await })
+ .offload(async move {
+ let _context_pin = context_pin;
+ run_delivery::trigger(&binding, &job, &run_id).await
+ })
.await
.map_err(|e| bus_error("ScheduleTrigger", e))
}
diff --git a/crates/openhuman-core/src/cron/bus_host_tests.rs b/crates/openhuman-core/src/cron/bus_host_tests.rs
index d5d8521a90..2d787356a5 100644
--- a/crates/openhuman-core/src/cron/bus_host_tests.rs
+++ b/crates/openhuman-core/src/cron/bus_host_tests.rs
@@ -123,6 +123,58 @@ async fn execute_runs_the_registered_handler_and_reports_a_retryable_failure() {
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
+#[tokio::test]
+async fn an_expired_bound_callback_fails_closed_under_another_ambient_context() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+
+ let tmp = TempDir::new().unwrap();
+ let config = config(&tmp);
+ let expired = CoreContext::for_test_with_config(DomainSet::full(), config.clone());
+ let dispatch = DispatchCtx::new(Arc::clone(&expired));
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let binding = Binding::new(&dispatch, &config, security);
+ let host = ScheduleHost {
+ executor: Arc::new(HostExecutor::new(binding.clone())),
+ binding,
+ };
+ drop(dispatch);
+ drop(expired);
+
+ let other = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
+ ContextOverlay::new(
+ config.clone(),
+ DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .session_agent("other-callback-scope"),
+ );
+ let name = format!("expired-callback-{}", uuid::Uuid::new_v4().simple());
+ let calls = Arc::new(AtomicUsize::new(0));
+ let handler_calls = Arc::clone(&calls);
+ let _handler = crate::cron::system_job_handlers::register(
+ &name,
+ Arc::new(move |_| {
+ handler_calls.fetch_add(1, Ordering::SeqCst);
+ Box::pin(async { Ok(()) })
+ }),
+ );
+ let job = flow_job(&config, &format!("system:{name}"));
+ let result = CoreContext::scope(other, async {
+ host.execute(job, "expired-context-run".to_string()).await
+ })
+ .await;
+ assert!(result.is_err(), "an expired bound callback must be refused");
+ assert_eq!(
+ calls.load(Ordering::SeqCst),
+ 0,
+ "the callback must not execute under the unrelated ambient context"
+ );
+}
+
#[tokio::test]
async fn a_permanent_handler_outcome_stops_the_retry_loop() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
index dcef2dcea8..1ed0929e34 100644
--- a/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_dispatch_tests.rs
@@ -231,6 +231,40 @@ async fn module_scheduler_slot_is_per_store_scope_and_refuses_a_duplicate() {
second.drain().await;
}
+#[tokio::test]
+async fn started_agent_scheduler_pins_its_context_only_until_stop_is_confirmed() {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DispatchCtx, DomainSet};
+
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp).await;
+ let agent = format!("retire-{}", uuid::Uuid::new_v4().simple());
+ let context = CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
+ ContextOverlay::new(
+ config.clone(),
+ DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .session_agent(agent),
+ );
+ let weak = Arc::downgrade(&context);
+ let mut dispatcher = JobDispatcher::new(
+ &DispatchCtx::new(Arc::clone(&context)),
+ &config,
+ &security(&config),
+ );
+ assert_eq!(dispatcher.tick(&config).await.unwrap(), 0);
+
+ drop(dispatcher);
+ drop(context);
+ tokio::time::timeout(std::time::Duration::from_secs(3), async {
+ while weak.upgrade().is_some() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("the finite StopScheduler owner releases its context after confirmation");
+}
+
/// Upgrade regression: a job whose retry budget and single-flight setting lived
/// in the old `cron_job_policies` side table keeps firing after the upgrade,
/// with that policy now on the job itself.