Skip to content

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

chore: files changed crates/openhuman-core/src/agent/host_agents.rs,crates/openhuman-core/src/core/r

Steven Enamakel4a559cf4c1f4
diff --git a/crates/openhuman-core/src/agent/host_agents.rs b/crates/openhuman-core/src/agent/host_agents.rs
index 40cd8cddb6..19f5a9f92b 100644
--- a/crates/openhuman-core/src/agent/host_agents.rs
+++ b/crates/openhuman-core/src/agent/host_agents.rs
@@ -80,7 +80,7 @@ impl HostAgent {
/// Run `fut` with this agent's context as the ambient [`CoreContext`].
pub async fn scope<F: std::future::Future>(&self, fut: F) -> F::Output {
- fut.await
+ CoreContext::scope(Arc::clone(&self.context), fut).await
}
}
@@ -88,7 +88,10 @@ impl std::fmt::Debug for HostAgent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// The config carries credentials and resolved paths; the belt is a
// closure. Name the agent and say whether it has a belt.
- f.debug_struct("HostAgent").finish_non_exhaustive()
+ f.debug_struct("HostAgent")
+ .field("id", &self.definition.id)
+ .field("host_tools", &self.host_tools.is_some())
+ .finish_non_exhaustive()
}
}
@@ -103,22 +106,43 @@ static RESOLVER: LazyLock<RwLock<Option<Arc<dyn HostAgentResolver>>>> =
/// Install `resolver`, replacing any earlier one, which is returned.
pub fn install(resolver: Arc<dyn HostAgentResolver>) -> Option<Arc<dyn HostAgentResolver>> {
- let _ = resolver;
- None
+ tracing::info!("[host_agents] host agent resolver installed");
+ RESOLVER
+ .write()
+ .unwrap_or_else(PoisonError::into_inner)
+ .replace(resolver)
}
/// Remove the installed resolver only while it is still `expected`. Returns
/// whether it was removed.
pub fn clear_if(expected: &Arc<dyn HostAgentResolver>) -> bool {
- let _ = expected;
- false
+ let mut installed = RESOLVER.write().unwrap_or_else(PoisonError::into_inner);
+ if installed
+ .as_ref()
+ .is_some_and(|current| Arc::ptr_eq(current, expected))
+ {
+ installed.take();
+ tracing::info!("[host_agents] host agent resolver removed");
+ true
+ } else {
+ false
+ }
}
/// Ask the installed resolver for `agent_id`. `None` when nothing is
/// installed or the host has no such agent.
pub fn resolve(agent_id: &str) -> Option<HostAgent> {
- let _ = agent_id;
- None
+ let resolver = RESOLVER
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clone()?;
+ let hit = resolver.resolve(agent_id);
+ tracing::debug!(
+ agent_id,
+ hit = hit.is_some(),
+ "[host_agents] resolve host agent"
+ );
+ hit
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 7f9d54a99c..d68fda387f 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -554,7 +554,7 @@ impl CoreContext {
/// as [`CoreContext::current`]. For blocking work that reads the ambient
/// context, such as building a session for a host-registered agent.
pub fn sync_scope<R>(ctx: Arc<CoreContext>, f: impl FnOnce() -> R) -> R {
- unimplemented!("sync_scope")
+ CURRENT_CONTEXT.sync_scope(ctx, f)
}
/// Capture the current context now and carry it across a subsequently
diff --git a/crates/openhuman-core/src/cron/policy.rs b/crates/openhuman-core/src/cron/policy.rs
index 5fe2a5f48c..b6f7cb7cfb 100644
--- a/crates/openhuman-core/src/cron/policy.rs
+++ b/crates/openhuman-core/src/cron/policy.rs
@@ -1,20 +1,35 @@
//! Per-job run policy: retry budget and single-flight.
//!
-//! Stub (RED).
+//! The job row itself (`CronJob`) belongs to `tinyflows-schedule` and its
+//! SQLite store to `tinyflows-sqlite`; neither has room for these two knobs,
+//! and both are host policy rather than scheduling logic. They live here, in a
+//! host-owned `cron_job_policies` table beside the store in the same
+//! `<workspace>/cron/jobs.db`, keyed by job id. A job with no row has the
+//! default policy, so every existing job keeps its behaviour:
+//!
+//! - `retries: None` uses `reliability.scheduler_retries`; `Some(0)` means
+//! exactly one attempt.
+//! - `single_flight: false` is the scheduler's historical behaviour: a job is
+//! never dispatched twice by the scheduler, and a slot it misses while still
+//! running is skipped silently. `true` additionally records each missed slot
+//! as a `skipped` run and refuses a manual "Run now" while a run is in flight.
use std::path::PathBuf;
-use anyhow::Result;
+use anyhow::{Context, Result};
+use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use crate::config::Config;
-/// How the scheduler runs one job.
+/// How the scheduler runs one job. The default is the historical behaviour.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct JobPolicy {
- /// Retries after a failed attempt. `None` keeps the default.
+ /// Retries after a failed attempt. `None` keeps
+ /// `reliability.scheduler_retries`; `Some(0)` runs exactly once.
pub retries: Option<u32>,
- /// Skip a run that comes due while the previous one is still running.
+ /// Skip, and record as `skipped`, a run that comes due while the previous
+ /// run of the same job is still in flight.
pub single_flight: bool,
}
@@ -22,19 +37,93 @@ pub(crate) fn db_path(config: &Config) -> PathBuf {
config.workspace_dir.join("cron").join("jobs.db")
}
-/// The policy stored for `job_id`.
-pub fn get_policy(_config: &Config, _job_id: &str) -> Result<JobPolicy> {
- Ok(JobPolicy::default())
+fn open(config: &Config) -> Result<Connection> {
+ let path = db_path(config);
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .with_context(|| format!("Failed to create cron directory {}", parent.display()))?;
+ }
+ let conn = Connection::open(&path)
+ .with_context(|| format!("Failed to open cron store {}", path.display()))?;
+ conn.busy_timeout(std::time::Duration::from_secs(5))?;
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS cron_job_policies (
+ job_id TEXT PRIMARY KEY,
+ retries INTEGER,
+ single_flight INTEGER NOT NULL DEFAULT 0
+ )",
+ [],
+ )
+ .context("Failed to create cron_job_policies")?;
+ Ok(conn)
+}
+
+/// The policy stored for `job_id`; the default when none is.
+pub fn get_policy(config: &Config, job_id: &str) -> Result<JobPolicy> {
+ let conn = open(config)?;
+ let row = conn
+ .query_row(
+ "SELECT retries, single_flight FROM cron_job_policies WHERE job_id = ?1",
+ params![job_id],
+ |row| {
+ Ok(JobPolicy {
+ retries: row
+ .get::<_, Option<i64>>(0)?
+ .map(|n| u32::try_from(n.max(0)).unwrap_or(u32::MAX)),
+ single_flight: row.get::<_, i64>(1)? != 0,
+ })
+ },
+ )
+ .optional()?;
+ Ok(row.unwrap_or_default())
+}
+
+/// Store `policy` for `job_id`. The default policy is stored as no row.
+pub fn set_policy(config: &Config, job_id: &str, policy: JobPolicy) -> Result<()> {
+ if policy == JobPolicy::default() {
+ return clear_policy(config, job_id);
+ }
+ tracing::debug!(job_id, ?policy, "[cron:policy] storing job policy");
+ open(config)?.execute(
+ "INSERT INTO cron_job_policies (job_id, retries, single_flight) VALUES (?1, ?2, ?3)
+ ON CONFLICT(job_id) DO UPDATE SET retries = ?2, single_flight = ?3",
+ params![
+ job_id,
+ policy.retries.map(i64::from),
+ i64::from(policy.single_flight)
+ ],
+ )?;
+ Ok(())
}
-/// Store `policy` for `job_id`.
-pub fn set_policy(_config: &Config, _job_id: &str, _policy: JobPolicy) -> Result<()> {
+/// Remove `job_id`'s policy; it reverts to the default.
+pub fn clear_policy(config: &Config, job_id: &str) -> Result<()> {
+ open(config)?.execute(
+ "DELETE FROM cron_job_policies WHERE job_id = ?1",
+ params![job_id],
+ )?;
Ok(())
}
-/// Retry budget for a job with `policy`.
-pub fn effective_retries(_config: &Config, _policy: &JobPolicy) -> u32 {
- 0
+/// Remove every stored policy.
+pub(crate) fn clear_all_policies(config: &Config) -> Result<usize> {
+ Ok(open(config)?.execute("DELETE FROM cron_job_policies", [])?)
+}
+
+/// The retry budget for a job with `policy`.
+pub fn effective_retries(config: &Config, policy: &JobPolicy) -> u32 {
+ policy
+ .retries
+ .unwrap_or(config.reliability.scheduler_retries)
+}
+
+/// The stored policy for `job_id`, or the default when it cannot be read: a
+/// policy-store hiccup must not stop a job from running.
+pub(crate) fn policy_or_default(config: &Config, job_id: &str) -> JobPolicy {
+ get_policy(config, job_id).unwrap_or_else(|error| {
+ tracing::warn!(job_id, %error, "[cron:policy] policy unreadable; using the default");
+ JobPolicy::default()
+ })
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/cron/scheduler/in_flight.rs b/crates/openhuman-core/src/cron/scheduler/in_flight.rs
index ae8f0fb2ea..32938d1280 100644
--- a/crates/openhuman-core/src/cron/scheduler/in_flight.rs
+++ b/crates/openhuman-core/src/cron/scheduler/in_flight.rs
@@ -1,16 +1,58 @@
-//! Which cron jobs are running right now. Stub (RED).
+//! Which cron jobs are running right now.
+//!
+//! The scheduler dispatches each due job onto its own task and returns to its
+//! poll loop, so the old "the loop is busy until the batch finishes" guarantee
+//! no longer keeps a job from being picked up twice. This registry does: a job
+//! is in flight from dispatch until its run is persisted. It counts rather than
+//! flags because a manual "Run now" may legitimately overlap a scheduled run of
+//! a job that is not single-flight, and the first to finish must not mark the
+//! other one done.
-/// Held for the duration of one run.
-pub(crate) struct InFlightGuard;
+use std::collections::HashMap;
+use std::sync::{LazyLock, Mutex, PoisonError};
+
+static RUNNING: LazyLock<Mutex<HashMap<String, usize>>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+/// Held for the duration of one run; releases it on drop, including on panic
+/// or cancellation.
+#[must_use = "the job counts as running only while the guard is held"]
+pub(crate) struct InFlightGuard {
+ job_id: String,
+}
+
+impl Drop for InFlightGuard {
+ fn drop(&mut self) {
+ let mut running = RUNNING.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(count) = running.get_mut(&self.job_id) {
+ *count = count.saturating_sub(1);
+ if *count == 0 {
+ running.remove(&self.job_id);
+ }
+ }
+ tracing::trace!(job_id = %self.job_id, "[cron:in_flight] run released");
+ }
+}
/// Mark `job_id` as running until the returned guard drops.
-pub(crate) fn enter(_job_id: &str) -> InFlightGuard {
- InFlightGuard
+pub(crate) fn enter(job_id: &str) -> InFlightGuard {
+ *RUNNING
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .entry(job_id.to_string())
+ .or_insert(0) += 1;
+ tracing::trace!(job_id, "[cron:in_flight] run entered");
+ InFlightGuard {
+ job_id: job_id.to_string(),
+ }
}
/// Whether any run of `job_id` is in progress.
-pub(crate) fn is_running(_job_id: &str) -> bool {
- false
+pub(crate) fn is_running(job_id: &str) -> bool {
+ RUNNING
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .contains_key(job_id)
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/cron/store.rs b/crates/openhuman-core/src/cron/store.rs
index 90526a0c84..cba4c64626 100644
--- a/crates/openhuman-core/src/cron/store.rs
+++ b/crates/openhuman-core/src/cron/store.rs
@@ -110,13 +110,20 @@ pub fn get_job(config: &Config, job_id: &str) -> Result<CronJob> {
pub fn remove_job(config: &Config, id: &str) -> Result<()> {
upstream::remove_job(&opts(config), id)?;
+ if let Err(error) = super::policy::clear_policy(config, id) {
+ tracing::warn!(job_id = id, %error, "[cron:store] removing job policy failed");
+ }
println!("✅ Removed cron job {id}");
Ok(())
}
/// Deletes every cron job in the workspace (E2E `openhuman.test_reset`).
pub fn clear_all_jobs(config: &Config) -> Result<usize> {
- upstream::clear_all_jobs(&opts(config))
+ let removed = upstream::clear_all_jobs(&opts(config))?;
+ if let Err(error) = super::policy::clear_all_policies(config) {
+ tracing::warn!(%error, "[cron:store] clearing job policies failed");
+ }
+ Ok(removed)
}
/// Removes duplicate jobs sharing a `name`, keeping the one with most history.
diff --git a/crates/openhuman-core/src/cron/system_job_handlers.rs b/crates/openhuman-core/src/cron/system_job_handlers.rs
index b864485e0b..351032d7de 100644
--- a/crates/openhuman-core/src/cron/system_job_handlers.rs
+++ b/crates/openhuman-core/src/cron/system_job_handlers.rs
@@ -1,6 +1,20 @@
-//! In-process handlers for system cron jobs. Stub (RED).
+//! In-process handlers for system cron jobs.
+//!
+//! A system job (see [`crate::cron::system_jobs`]) normally *announces* itself:
+//! the scheduler publishes `DomainEvent::CronSystemJobDue` and records the run
+//! as `ok` the moment it is published, because the bus is fire-and-forget and
+//! nothing comes back. A host that wants the run's real outcome in the job's
+//! history registers a handler here instead. When the job comes due the
+//! scheduler still publishes the event (observers keep working), then awaits
+//! the handler and records **its** result: `ok`, or `error` with the handler's
+//! message, subject to the job's retry budget like any other run.
+//!
+//! One handler per name; a later registration replaces an earlier one, and
+//! dropping a [`SystemJobRegistration`] removes its handler only while it is
+//! still the registered one.
-use std::sync::Arc;
+use std::collections::HashMap;
+use std::sync::{Arc, LazyLock, PoisonError, RwLock};
use futures::future::BoxFuture;
@@ -9,30 +23,81 @@ use futures::future::BoxFuture;
pub struct SystemJobContext {
/// The cron row's id.
pub job_id: String,
- /// The system job's name (`system:<name>`).
+ /// The system job's name: the `<name>` in its `system:<name>` command.
pub name: String,
}
-/// A handler for one system job.
+/// A handler for one system job. `Err` is recorded as the run's failure.
pub type SystemJobHandler =
Arc<dyn Fn(SystemJobContext) -> BoxFuture<'static, Result<(), String>> + Send + Sync>;
+static HANDLERS: LazyLock<RwLock<HashMap<String, SystemJobHandler>>> =
+ LazyLock::new(|| RwLock::new(HashMap::new()));
+
/// Keeps a handler registered while held.
-pub struct SystemJobRegistration;
+#[must_use = "the handler is unregistered when the registration drops"]
+pub struct SystemJobRegistration {
+ name: String,
+ handler: SystemJobHandler,
+}
+
+impl Drop for SystemJobRegistration {
+ fn drop(&mut self) {
+ let mut handlers = HANDLERS.write().unwrap_or_else(PoisonError::into_inner);
+ if handlers
+ .get(&self.name)
+ .is_some_and(|current| Arc::ptr_eq(current, &self.handler))
+ {
+ handlers.remove(&self.name);
+ tracing::debug!(job = %self.name, "[cron:system_handlers] handler unregistered");
+ }
+ }
+}
+
+impl std::fmt::Debug for SystemJobRegistration {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SystemJobRegistration")
+ .field("name", &self.name)
+ .finish_non_exhaustive()
+ }
+}
-/// Register `handler` for system job `name`.
-pub fn register(_name: &str, _handler: SystemJobHandler) -> SystemJobRegistration {
- SystemJobRegistration
+/// Register `handler` for system job `name`, replacing any earlier handler.
+pub fn register(name: &str, handler: SystemJobHandler) -> SystemJobRegistration {
+ HANDLERS
+ .write()
+ .unwrap_or_else(PoisonError::into_inner)
+ .insert(name.to_string(), Arc::clone(&handler));
+ tracing::debug!(job = %name, "[cron:system_handlers] handler registered");
+ SystemJobRegistration {
+ name: name.to_string(),
+ handler,
+ }
}
/// Whether `name` has a handler.
-pub fn has_handler(_name: &str) -> bool {
- false
+pub fn has_handler(name: &str) -> bool {
+ HANDLERS
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .contains_key(name)
}
-/// Run the handler for `ctx.name`.
-pub async fn dispatch(_ctx: SystemJobContext) -> Option<Result<(), String>> {
- None
+/// Run the handler registered for `ctx.name`. `None` when there is none.
+pub async fn dispatch(ctx: SystemJobContext) -> Option<Result<(), String>> {
+ let handler = HANDLERS
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .get(&ctx.name)
+ .cloned()?;
+ tracing::debug!(job = %ctx.name, job_id = %ctx.job_id, "[cron:system_handlers] dispatching");
+ let result = handler(ctx.clone()).await;
+ tracing::debug!(
+ job = %ctx.name,
+ ok = result.is_ok(),
+ "[cron:system_handlers] handler finished"
+ );
+ Some(result)
}
#[cfg(test)]