The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(ops): handle missing resolution in ops module
Steven Enamakel9dd06719445a
diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 841ce39557..a29174b9e6 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -35,7 +35,8 @@ use std::path::{Path, PathBuf};use std::sync::OnceLock;use std::time::Duration;-use super::resolution::{self, Claim, Resolution, ResolutionState, ResolutionTable, Waited};+use tinybus::module::resolution::{self, Claim, Resolution, ResolutionState, ResolutionTable, Waited};+use tinybus::module::{artifact_dir, prune_stale_versions};use super::types::{ModuleRecord, ModuleState, ModuleStatus};use super::{host, platform, registry};use crate::config::Config;@@ -112,7 +113,7 @@ pub async fn ensure_loaded_within(let record =registry::find(id).ok_or_else(|| LoadError::Failed(format!("unknown module '{id}'")))?;- let receiver = match resolution::table().claim(id) {+ let receiver = match resolution::global().claim(id) {Claim::Done(Resolution::Ready) => return Ok(()),Claim::Done(Resolution::Failed(reason)) => return Err(LoadError::Failed(reason)),Claim::Wait(receiver) => receiver,@@ -131,7 +132,7 @@ pub async fn ensure_loaded_within(/// The state of `id` as the resolution table reports it, without touching it.#[must_use]pub fn state_of(id: &str) -> ModuleState {- match resolution::table().peek(id) {+ match resolution::global().peek(id) {ResolutionState::Unresolved => ModuleState::Available,ResolutionState::Loading => ModuleState::Loading,ResolutionState::Ready => ModuleState::Ready,@@ -163,7 +164,7 @@ async fn start_resolution(Resolution::Failed(reason)}};- resolution::table().complete(id, resolution, sender);+ resolution::global().complete(id, resolution, sender);};match host::runtime().await {Ok(runtime) => {@@ -405,98 +406,6 @@ fn load_cached())}-/// Whether `component` is safe to use as one directory name.-///-/// The three values that build a cache path — a module id, its version, and a-/// host key — are compiled-in `const` data today, so nothing reaches this with-/// a separator in it. It is checked anyway because of what sits at the end of-/// the path: [`prune_stale_versions`] calls `remove_dir_all` on what these-/// build. A registry edit or a future value that carried `..` or a separator-/// would turn a cache tidy-up into deleting somewhere else entirely, and a-/// rule that has to hold for a delete is worth stating rather than inferring-/// from where the data happens to come from today.-fn is_safe_path_component(component: &str) -> bool {- !component.is_empty()- && component != "."- && component != ".."- && !component.contains('/')- && !component.contains('\\')- && !component.contains('\0')- // A leading dot would collide with the `.staging-*` directories a- // concurrent download is filling.- && !component.starts_with('.')-}--/// Where one artifact of one module version is cached, when all three-/// components are usable as directory names.-///-/// `None` rather than a sanitised path: a registry entry that cannot name a-/// directory is a build-time mistake, and quietly rewriting it would hide the-/// mistake behind a cache that silently never hits.-fn artifact_dir(install_root: &Path, record: &ModuleRecord, host_key: &str) -> Option<PathBuf> {- for component in [record.id, record.version, host_key] {- if !is_safe_path_component(component) {- log::error!(- "[modules] '{}' has a component that cannot name a directory; refusing to build a \- cache path from it",- record.id- );- return None;- }- }- Some(- install_root- .join(record.id)- .join(record.version)- .join(host_key),- )-}--/// Remove cached versions of `record` other than the pinned one.-///-/// Best-effort and after the fact: a version that is no longer pinned will-/// never be loaded again, so keeping it only costs disk. Staging directories-/// are left alone — a concurrent process may be filling one — and every-/// removal is logged, because a cache that empties itself is worth noticing.-fn prune_stale_versions(install_root: &Path, record: &ModuleRecord) {- // Both sides of the comparison below have to be real directory names, or- // "everything that is not the pinned version" is not a set this function- // should be handing to `remove_dir_all`.- if !is_safe_path_component(record.id) || !is_safe_path_component(record.version) {- log::error!(- "[modules] refusing to prune '{}': its id or version cannot name a directory",- record.id- );- return;- }- let module_root = install_root.join(record.id);- let Ok(entries) = std::fs::read_dir(&module_root) else {- return;- };- for entry in entries.flatten() {- let path = entry.path();- let name = entry.file_name();- let name = name.to_string_lossy();- // `read_dir` never yields `.` or `..`, and the leading-dot skip covers- // the staging directories; the guard is here so the delete depends on- // this function's own check rather than on that being remembered.- if !path.is_dir() || name == record.version || !is_safe_path_component(&name) {- continue;- }- match std::fs::remove_dir_all(&path) {- Ok(()) => log::info!(- "[modules] removed cached '{}' {name}; {} is pinned",- record.id,- record.version- ),- Err(error) => log::warn!(- "[modules] could not remove cached '{}' {name}: {error}",- record.id- ),- }- }-}-/// Load a platform library from `path`.pub(super) fn load_local(runtime: &host::ModuleRuntime,@@ -673,7 +582,7 @@ fn status_of(config: &Config, record: &ModuleRecord) -> ModuleStatus {ModuleState::Unsupported,Some("modules are disabled in configuration".to_string()),),- _ => match resolution::table().peek(record.id) {+ _ => match resolution::global().peek(record.id) {ResolutionState::Ready => (ModuleState::Ready, None),ResolutionState::Loading => (ModuleState::Loading, None),ResolutionState::Failed(reason) => (ModuleState::Failed, Some(reason)),diff --git a/crates/openhuman-core/src/modules/resolution.rs b/crates/openhuman-core/src/modules/resolution.rsdeleted file mode 100644index 4725d02515..0000000000--- a/crates/openhuman-core/src/modules/resolution.rs+++ /dev/null@@ -1,224 +0,0 @@-//! Per-module resolution state, and the wait on it.-//!-//! [`super::ops::ensure_loaded`] used to hold one process-wide lock while it-//! resolved a module, and every caller for every module queued behind it. Three-//! things followed, and all three were visible in the field on a slow link:-//! the memory module waited its turn behind runtime downloads it had nothing to-//! do with; a caller that stopped waiting dropped the resolver's own future,-//! which released the lock with the module half-resolved and let the next-//! caller start a second download; and there was no way to say "still loading",-//! so every memory call ran into its caller's own timeout instead.-//!-//! This table replaces the lock with a slot per module. The first caller to-//! ask claims the slot and runs the resolution as a task with process lifetime,-//! so a caller that gives up cannot cancel it; every other caller waits on a-//! watch channel until the outcome lands. Waiting is cancel-safe, so a caller-//! may give up after a bound and report the module as loading rather than hang.--use std::collections::HashMap;-use std::sync::{Mutex, OnceLock};-use std::time::Duration;--use tokio::sync::watch;--/// Outcome of resolving one module, remembered for the process lifetime.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(super) enum Resolution {- /// Serving.- Ready,- /// Terminal. Carries the sanitised reason, never a path or URL.- Failed(String),-}--/// What one module's slot holds.-#[derive(Debug, Clone)]-enum Slot {- InFlight(watch::Receiver<Option<Resolution>>),- Done(Resolution),-}--/// What [`ResolutionTable::claim`] hands the caller.-pub(super) enum Claim {- /// Nobody has asked for this module yet. The caller runs the resolution and- /// reports through the sender; the receiver is its own seat in the queue.- Run {- sender: watch::Sender<Option<Resolution>>,- receiver: watch::Receiver<Option<Resolution>>,- },- /// Someone else is resolving it: wait for their outcome.- Wait(watch::Receiver<Option<Resolution>>),- /// Already resolved, one way or the other.- Done(Resolution),-}--/// A module's state as [`ResolutionTable::peek`] reports it.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(super) enum ResolutionState {- /// Nothing has asked for it.- Unresolved,- /// Being downloaded, verified, or initialised.- Loading,- Ready,- Failed(String),-}--/// How a wait on a slot ended.-#[derive(Debug, Clone, PartialEq, Eq)]-pub(super) enum Waited {- Ready,- Failed(String),- /// The bound passed before the outcome landed.- StillLoading,-}--impl From<Resolution> for Waited {- fn from(resolution: Resolution) -> Self {- match resolution {- Resolution::Ready => Self::Ready,- Resolution::Failed(reason) => Self::Failed(reason),- }- }-}--/// One slot per module, keyed by registry id.-#[derive(Default)]-pub(super) struct ResolutionTable {- slots: Mutex<HashMap<String, Slot>>,-}--impl ResolutionTable {- /// Claim `id` for resolution, or learn who already has.- ///- /// Atomic with respect to other claims: two concurrent first callers get one- /// `Run` and one `Wait`, never two `Run`s — that is the property the old- /// lock existed for, kept without serialising unrelated modules.- pub(super) fn claim(&self, id: &str) -> Claim {- let mut slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- match slots.get(id) {- Some(Slot::Done(resolution)) => Claim::Done(resolution.clone()),- Some(Slot::InFlight(receiver)) => Claim::Wait(receiver.clone()),- None => {- let (sender, receiver) = watch::channel(None);- slots.insert(id.to_string(), Slot::InFlight(receiver.clone()));- Claim::Run { sender, receiver }- }- }- }-- /// Record the outcome for `id` and wake everyone waiting on it.- ///- /// The table is updated before the channel fires, so a waiter that wakes and- /// looks again sees the settled slot rather than a stale in-flight one.- pub(super) fn complete(- &self,- id: &str,- resolution: Resolution,- sender: watch::Sender<Option<Resolution>>,- ) {- {- let mut slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- slots.insert(id.to_string(), Slot::Done(resolution.clone()));- }- let _ = sender.send(Some(resolution));- }-- /// Record that a module which resolved `Ready` has since faulted, such as- /// when a lifecycle reinitialization is refused. tinybus never recovers a- /// faulted module in-process, so the slot settles as failed and later- /// callers get the reason instead of a retry.- pub(crate) fn mark_faulted(&self, id: &str, reason: String) {- let mut slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- if matches!(slots.get(id), Some(Slot::Done(Resolution::Ready))) {- slots.insert(id.to_string(), Slot::Done(Resolution::Failed(reason)));- }- }-- /// The state of `id` without touching it.- pub(super) fn peek(&self, id: &str) -> ResolutionState {- let slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- match slots.get(id) {- None => ResolutionState::Unresolved,- Some(Slot::InFlight(_)) => ResolutionState::Loading,- Some(Slot::Done(Resolution::Ready)) => ResolutionState::Ready,- Some(Slot::Done(Resolution::Failed(reason))) => ResolutionState::Failed(reason.clone()),- }- }-- /// Wait for an outcome on `receiver`, for at most `within` when given.- ///- /// Cancel-safe: dropping this future leaves the resolution running and the- /// slot intact. A sender dropped without an outcome means the resolver task- /// itself died before reporting; that is reported as a failure rather than- /// waited on, because nothing will ever complete the slot.- pub(super) async fn wait(- mut receiver: watch::Receiver<Option<Resolution>>,- within: Option<Duration>,- ) -> Waited {- let settled = async move {- loop {- if let Some(resolution) = receiver.borrow_and_update().clone() {- return resolution;- }- if receiver.changed().await.is_err() {- return Resolution::Failed(- "module resolution was abandoned; restart the app to try again".to_string(),- );- }- }- };- match within {- None => settled.await.into(),- Some(limit) => match tokio::time::timeout(limit, settled).await {- Ok(resolution) => resolution.into(),- Err(_elapsed) => Waited::StillLoading,- },- }- }-- /// Put `id` in flight without a resolver, handing back the sender that- /// completes it. For tests that need to observe the loading state.- #[cfg(test)]- pub(super) fn mark_in_flight_for_test(&self, id: &str) -> watch::Sender<Option<Resolution>> {- let (sender, receiver) = watch::channel(None);- let mut slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- slots.insert(id.to_string(), Slot::InFlight(receiver));- sender- }-- /// Forget `id` entirely. For tests, so a slot they planted does not outlive- /// them in the process-wide table.- #[cfg(test)]- pub(super) fn reset_for_test(&self, id: &str) {- let mut slots = self- .slots- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- slots.remove(id);- }-}--/// The process-wide table. One per process because tinybus loads a library at-/// most once per process, so the outcome is a fact about the process.-pub(super) fn table() -> &'static ResolutionTable {- static TABLE: OnceLock<ResolutionTable> = OnceLock::new();- TABLE.get_or_init(ResolutionTable::default)-}--#[cfg(test)]-#[path = "resolution_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/modules/resolution_tests.rs b/crates/openhuman-core/src/modules/resolution_tests.rsdeleted file mode 100644index 4f8c691d1f..0000000000--- a/crates/openhuman-core/src/modules/resolution_tests.rs+++ /dev/null@@ -1,138 +0,0 @@-//! Tests for the per-module resolution table.-//!-//! Every test builds its own table: the process-wide one is shared with the-//! rest of the suite, and a slot planted there would be visible to any test-//! that happens to ask for the same module id.--use std::time::Duration;--use super::{Claim, Resolution, ResolutionState, ResolutionTable, Waited};--fn run_claim(- table: &ResolutionTable,- id: &str,-) -> (- tokio::sync::watch::Sender<Option<Resolution>>,- tokio::sync::watch::Receiver<Option<Resolution>>,-) {- match table.claim(id) {- Claim::Run { sender, receiver } => (sender, receiver),- Claim::Wait(_) | Claim::Done(_) => panic!("first claim must run the resolution"),- }-}--#[test]-fn the_first_claim_runs_and_every_later_claim_waits() {- let table = ResolutionTable::default();- assert_eq!(table.peek("m"), ResolutionState::Unresolved);-- let (_sender, _receiver) = run_claim(&table, "m");- assert_eq!(table.peek("m"), ResolutionState::Loading);- assert!(matches!(table.claim("m"), Claim::Wait(_)));- assert!(matches!(table.claim("m"), Claim::Wait(_)));-}--#[test]-fn modules_do_not_share_a_slot() {- let table = ResolutionTable::default();- let (_a, _ra) = run_claim(&table, "a");- // A second module is not queued behind the first.- assert!(matches!(table.claim("b"), Claim::Run { .. }));-}--#[tokio::test]-async fn an_outcome_reaches_every_waiter_and_is_remembered() {- let table = ResolutionTable::default();- let (sender, own) = run_claim(&table, "m");- let Claim::Wait(other) = table.claim("m") else {- panic!("second claim waits");- };-- let waiter = tokio::spawn(ResolutionTable::wait(other, None));- table.complete("m", Resolution::Ready, sender);-- assert_eq!(ResolutionTable::wait(own, None).await, Waited::Ready);- assert_eq!(waiter.await.unwrap(), Waited::Ready);- assert_eq!(table.peek("m"), ResolutionState::Ready);- assert!(matches!(table.claim("m"), Claim::Done(Resolution::Ready)));-}--#[tokio::test]-async fn a_failure_is_terminal_and_carries_its_reason() {- let table = ResolutionTable::default();- let (sender, receiver) = run_claim(&table, "m");- table.complete("m", Resolution::Failed("refused".to_string()), sender);-- assert_eq!(- ResolutionTable::wait(receiver, None).await,- Waited::Failed("refused".to_string())- );- assert_eq!(- table.peek("m"),- ResolutionState::Failed("refused".to_string())- );- assert!(matches!(- table.claim("m"),- Claim::Done(Resolution::Failed(reason)) if reason == "refused"- ));-}--#[tokio::test]-async fn a_bounded_wait_reports_still_loading_instead_of_hanging() {- let table = ResolutionTable::default();- let (sender, receiver) = run_claim(&table, "m");-- let started = std::time::Instant::now();- let outcome = ResolutionTable::wait(receiver.clone(), Some(Duration::from_millis(20))).await;- assert_eq!(outcome, Waited::StillLoading);- assert!(started.elapsed() < Duration::from_secs(5));-- // Giving up did not disturb the resolution: the slot is still in flight and- // the outcome still arrives for a later, unbounded wait.- assert_eq!(table.peek("m"), ResolutionState::Loading);- table.complete("m", Resolution::Ready, sender);- assert_eq!(ResolutionTable::wait(receiver, None).await, Waited::Ready);-}--#[tokio::test]-async fn a_resolver_that_dies_without_reporting_fails_its_waiters() {- let table = ResolutionTable::default();- let (sender, receiver) = run_claim(&table, "m");- drop(sender);- assert!(matches!(- ResolutionTable::wait(receiver, None).await,- Waited::Failed(reason) if reason.contains("abandoned")- ));-}--#[test]-fn test_hooks_plant_and_remove_a_slot() {- let table = ResolutionTable::default();- let _sender = table.mark_in_flight_for_test("m");- assert_eq!(table.peek("m"), ResolutionState::Loading);- table.reset_for_test("m");- assert_eq!(table.peek("m"), ResolutionState::Unresolved);-}--#[test]-fn a_ready_module_that_faults_settles_as_failed() {- let table = ResolutionTable::default();- // Nothing resolved yet: a fault report has nothing to downgrade.- table.mark_faulted("m", "refused".into());- assert_eq!(table.peek("m"), ResolutionState::Unresolved);-- let (sender, _receiver) = run_claim(&table, "m");- table.mark_faulted("m", "refused".into());- assert_eq!(table.peek("m"), ResolutionState::Loading);-- table.complete("m", Resolution::Ready, sender);- table.mark_faulted("m", "configuration refused".into());- assert_eq!(- table.peek("m"),- ResolutionState::Failed("configuration refused".into())- );- assert!(matches!(- table.claim("m"),- Claim::Done(Resolution::Failed(_))- ));-}