Skip to content

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

Cache native modules and keep memory calls off the download path

Shanu80ade13d8c94
diff --git a/AGENTS.md b/AGENTS.md
index b0145a8dee..6c658f02cf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -970,6 +970,43 @@ always-on kernel surface, so `features = ["modules"]` there puts a loader plus
one — 305 → 308 packages, which the kernel-floor ratchet caught. It is forwarded
from this crate's own `modules` feature instead.
+#### Release cache, boot preload, and the loading state
+
+**Every module load goes through a persistent, verified cache.** `ops::resolve`
+loads the pinned release with tinybus's `load_github_release_cached`, which
+keeps the archive, its extraction and the manifest digest under
+`install_dir(config)/<id>/<version>/<host_key>/` (`~/Library/Caches/openhuman/modules`
+on macOS, `~/.cache/openhuman/modules` on Linux). A warm launch re-hashes the
+archive against the registry pin and maps the library without the network; a
+cold launch downloads into a staging sibling and commits with one rename, and
+the versions no longer pinned are pruned afterwards. Before this existed every
+launch downloaded every module — five on the desktop — serialised behind one
+lock, and tinybus's default HTTP client had no connect timeout, so a single
+black-holed CDN address cost the OS SYN timeout (75 s on macOS, ~2 min on
+Linux) per module while every memory call and the chat turn waited behind it.
+
+Three host-side rules ride on it:
+
+- **`LoadPolicy::Eager` runs at boot now.** `start_bootstrap_jobs` spawns
+ `modules::boot::load_declared_modules` behind `ServiceSet::memory_queue`; it
+ installs the memory host callbacks first (a module admitted without them
+ resolves no embedder) and then resolves TinyMemory off the request path. The
+ function had no product caller from the day it landed.
+- **Resolution is per module, and the wait is bounded.** `modules::resolution`
+ gives each module a slot: the first caller runs the load as a
+ process-lifetime task on the module runtime and everyone else waits on a
+ watch channel, so a caller that gives up cancels nothing and two modules
+ never queue behind each other. `ensure_loaded_within` bounds the wait.
+ `ModuleMemoryProvider::proxy` uses an 8 s grace for reads and answers
+ `MemoryError::Unavailable` ("memory is still starting") instead of hanging
+ into the UI's 30 s RPC deadline; writes (`store`, the syncs, `shutdown`, …)
+ wait it out because a dropped write is lost work. `modules.list` reports
+ `Loading`, and `health()` answers `Degraded` — never `Down`, which is the
+ signal that rebinds the fallback driver — while a load is in flight.
+- **The chat turn's one inline memory await is bounded** — 3 s around
+ `recall_situational_preferences_on` in `core_turn.rs`; citations and autosave
+ were already spawned off the path.
+
#### The memory seam — one contract, two live paths (#5560)
Memory is the second module consumer, and it is **half migrated**. Read this
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rs
index 6760afc45b..3c5b9083cf 100644
--- a/src/core/runtime/services.rs
+++ b/src/core/runtime/services.rs
@@ -216,6 +216,9 @@ pub(crate) struct BootstrapJobPlan {
/// Proactive task pollers (`task_sources::start_periodic_poll` +
/// `agent::task_dispatcher::start_board_poller`).
pub proactive_task_pollers: bool,
+ /// Eager native-module preload (`modules::boot::load_declared_modules`):
+ /// the memory module resolving at boot, off the request path.
+ pub module_preload: bool,
}
/// Pure flag→job mapping for [`start_bootstrap_jobs`]. No side effects.
@@ -230,6 +233,9 @@ pub(crate) fn bootstrap_job_plan(services: &ServiceSet) -> BootstrapJobPlan {
composio_integration_sync: services.integrations,
workspace_memory_sync: services.memory_sync,
proactive_task_pollers: services.cron,
+ // The memory module is the only eager module, so its preload is memory
+ // background work and rides the same flag as the queue.
+ module_preload: services.memory_queue,
}
}
@@ -245,17 +251,25 @@ pub(crate) fn bootstrap_job_plan(services: &ServiceSet) -> BootstrapJobPlan {
/// silently lost all of them (#5028) — so they now sit behind `integrations` /
/// `memory_sync` instead.
///
-/// `config` is unread as of openhuman#5560 — the engine's `queue::start` was
-/// this function's only consumer of it, and the loaded TinyMemory module starts
-/// that pool itself now. The parameter is **kept** rather than dropped: every
-/// other job here is one config read away from needing it again (the periodic
-/// sync loops below already re-load config internally), and removing it would
-/// churn every embedder that calls `start_bootstrap_jobs` for no gain. Named
-/// `_config` so the compiler does not have to be told to ignore it.
-pub fn start_bootstrap_jobs(services: ServiceSet, _config: &Config) {
+/// `config` feeds the native-module preload and nothing else here: the
+/// engine's `queue::start` was this function's other consumer of it, and the
+/// loaded TinyMemory module starts that pool itself now (openhuman#5560).
+pub fn start_bootstrap_jobs(services: ServiceSet, config: &Config) {
let plan = bootstrap_job_plan(&services);
log::debug!("[runtime.bootstrap] starting bootstrap jobs with plan {plan:?}");
+ // Native modules the registry marks eager — today TinyMemory, when the
+ // memory driver is module-backed. Off the boot path: the first launch on a
+ // machine downloads the release, and becoming RPC-ready must not wait on
+ // the network. A warm launch maps the cached library in milliseconds, so
+ // the first memory call finds it serving instead of starting the load
+ // itself and waiting behind it.
+ if plan.module_preload {
+ spawn_module_preload(config);
+ } else {
+ log::debug!("[runtime.bootstrap] native module preload disabled by ServiceSet");
+ }
+
// ── The queue pool moved into the module, and must NOT be started here ──
//
// This block used to call `tinymemory_core::queue::start(config.to_arc())`,
@@ -345,6 +359,23 @@ pub fn start_bootstrap_jobs(services: ServiceSet, _config: &Config) {
log::debug!("[runtime.bootstrap] bootstrap job dispatch complete");
}
+/// Resolve every eager native module in the background.
+#[cfg(feature = "modules")]
+fn spawn_module_preload(config: &Config) {
+ let config = config.clone();
+ tokio::spawn(async move {
+ log::debug!("[runtime.bootstrap] native module preload started");
+ crate::openhuman::modules::boot::load_declared_modules(&config).await;
+ log::debug!("[runtime.bootstrap] native module preload finished");
+ });
+}
+
+/// Without the module host compiled in there is nothing to preload.
+#[cfg(not(feature = "modules"))]
+fn spawn_module_preload(_config: &Config) {
+ log::debug!("[runtime.bootstrap] native module preload skipped: modules are compiled out");
+}
+
/// Runs startup migrations, then starts one-shot boot background work selected
/// by [`ServiceSet`].
///
@@ -548,6 +579,7 @@ mod tests {
composio_integration_sync: true,
workspace_memory_sync: true,
proactive_task_pollers: true,
+ module_preload: true,
}
);
}
@@ -560,6 +592,7 @@ mod tests {
composio_integration_sync: false,
workspace_memory_sync: false,
proactive_task_pollers: false,
+ module_preload: false,
};
assert_eq!(bootstrap_job_plan(&ServiceSet::none()), empty);
assert_eq!(bootstrap_job_plan(&ServiceSet::headless_api()), empty);
@@ -582,6 +615,18 @@ mod tests {
let plan = bootstrap_job_plan(&memory_sync);
assert!(plan.workspace_memory_sync);
assert!(!plan.composio_integration_sync);
+ assert!(!plan.module_preload);
+
+ // The module preload is memory background work: it follows the queue
+ // flag and no other.
+ let mut memory_queue = ServiceSet::none();
+ memory_queue.memory_queue = true;
+ let plan = bootstrap_job_plan(&memory_queue);
+ assert!(plan.module_preload);
+ assert!(plan.memory_queue);
+ assert!(!plan.workspace_memory_sync);
+ assert!(!plan.composio_integration_sync);
+ assert!(!plan.proactive_task_pollers);
}
/// From desktop(), disabling exactly one concern flag disables only its job.
diff --git a/src/openhuman/agent/harness/session/turn/core_turn.rs b/src/openhuman/agent/harness/session/turn/core_turn.rs
index b5747b5c01..4a862472eb 100644
--- a/src/openhuman/agent/harness/session/turn/core_turn.rs
+++ b/src/openhuman/agent/harness/session/turn/core_turn.rs
@@ -343,12 +343,32 @@ impl Agent {
// cost). An unrelated message clears the similarity gate to nothing, so
// no block is injected.
{
- let situational =
+ // Bounded: this is the one memory await left on the turn's
+ // critical path, and on a cold launch the memory module may still
+ // be downloading behind it. A turn without a preference block is
+ // an ordinary turn; a turn that waits minutes for one is the
+ // outage this bound exists to prevent. The citation and autosave
+ // work above is already spawned off the path.
+ const SITUATIONAL_RECALL_BUDGET: std::time::Duration =
+ std::time::Duration::from_secs(3);
+ let situational = match tokio::time::timeout(
+ SITUATIONAL_RECALL_BUDGET,
crate::openhuman::memory::preferences::recall_situational_preferences_on(
&self.memory,
user_message,
- )
- .await;
+ ),
+ )
+ .await
+ {
+ Ok(situational) => situational,
+ Err(_elapsed) => {
+ log::warn!(
+ "[pref_recall] situational recall exceeded {SITUATIONAL_RECALL_BUDGET:?}; \
+ continuing without a preference block"
+ );
+ Vec::new()
+ }
+ };
if !situational.is_empty() {
log::info!(
"[pref_recall] situational block injected: {} item(s)",
diff --git a/src/openhuman/modules/boot.rs b/src/openhuman/modules/boot.rs
index ef28754dcf..b8016a7ce3 100644
--- a/src/openhuman/modules/boot.rs
+++ b/src/openhuman/modules/boot.rs
@@ -65,6 +65,23 @@ pub async fn load_declared_modules(config: &Config) {
);
continue;
}
+ // TinyMemory resolves its embedding provider while the library is
+ // admitted, through callbacks this host serves on the module bus. The
+ // lazy path installs them before loading; the eager path must too, or
+ // the module comes up without an embedder and every memory write fails
+ // from then on.
+ if record.id == super::memory::MODULE_ID {
+ if let Err(reason) =
+ super::memory::install_host_callbacks(std::sync::Arc::new(config.clone())).await
+ {
+ log::warn!(
+ "[modules] eager module '{}' skipped: host callbacks are unavailable: {reason}",
+ record.id
+ );
+ continue;
+ }
+ }
+ log::info!("[modules] eager module '{}' resolving at boot", record.id);
if let Err(reason) = ops::ensure_loaded(config, record.id).await {
log::warn!(
"[modules] eager module '{}' did not load: {reason}",
diff --git a/src/openhuman/modules/host.rs b/src/openhuman/modules/host.rs
index d839dc8cd5..9007aa3d3f 100644
--- a/src/openhuman/modules/host.rs
+++ b/src/openhuman/modules/host.rs
@@ -67,6 +67,18 @@ impl ModuleRuntime {
&self.connection
}
+ /// Spawn `future` with process lifetime.
+ ///
+ /// For work that other callers wait on — a module resolution — and that
+ /// must therefore outlive whichever caller runtime started it.
+ pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
+ where
+ F: std::future::Future + Send + 'static,
+ F::Output: Send + 'static,
+ {
+ self.handle.spawn(future)
+ }
+
/// Run module admission work on this runtime's blocking pool.
pub async fn blocking<F>(&self, work: F) -> Result<(), String>
where
diff --git a/src/openhuman/modules/memory_part_01.rs b/src/openhuman/modules/memory_part_01.rs
index 9cab25a367..9f48293fa9 100644
--- a/src/openhuman/modules/memory_part_01.rs
+++ b/src/openhuman/modules/memory_part_01.rs
@@ -1,4 +1,5 @@
use std::sync::Arc;
+use std::time::Duration;
use tinymemory_api::capabilities::{Capabilities, Capability};
@@ -131,11 +132,11 @@ use tinymemory_api::chunks::Chunk;
use tinymemory_api::error::MemoryError;
use tinymemory_api::goals::GoalsDoc;
use tinymemory_api::health::MemoryHealth;
+use tinymemory_api::learning::LearningCandidate;
use tinymemory_api::provider::operations::{
- AnswerRequest, AnswerResponse, MemoryAnswer, MemoryConversationIngest,
- MemoryDocumentIngest, MemoryEventIngest, MemoryLearningIngest, RawMemoryEvent,
+ AnswerRequest, AnswerResponse, MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest,
+ MemoryEventIngest, MemoryLearningIngest, RawMemoryEvent,
};
-use tinymemory_api::learning::LearningCandidate;
use tinymemory_api::provider::sessions::{
CodingSessionIngestReport, CodingSessionIngestRequest, CodingSessionSource,
};
@@ -218,6 +219,56 @@ pub(crate) fn policy() -> Option<&'static Arc<Config>> {
MODULES_POLICY.get()
}
+/// How long a bounded memory call waits for the module before reporting it as
+/// still loading.
+///
+/// A warm launch maps the cached library in well under a second and the
+/// module's own initialisation is capped at five by tinybus, so this is
+/// comfortably past the whole happy path while staying well inside the
+/// desktop's thirty-second RPC deadline — the caller learns "loading", not
+/// "timed out".
+const MODULE_LOADING_GRACE: Duration = Duration::from_secs(8);
+
+/// Operations that keep waiting while the module loads.
+///
+/// A write that gives up is lost work: the message a chat turn autosaves, a
+/// sync an operator kicked off, the shutdown that releases queue locks. Those
+/// wait for the outcome however long a cold download takes, exactly as every
+/// call did before the wait was bounded. Reads are the other case — a page or
+/// a turn that is better served by "memory is loading" now than by the result
+/// in three minutes — and every operation not named here is treated as one.
+const UNBOUNDED_OPERATIONS: &[&str] = &[
+ "store",
+ "import_records",
+ "ingest_coding_sessions",
+ "run_source_sync",
+ "run_connection_sync",
+ "bootstrap_connection",
+ "forget",
+ "override_scheduler_gate",
+ "shutdown",
+];
+
+/// Install the host-side callbacks the module reaches for while it loads.
+///
+/// Idempotent and process-wide. Both the lazy path ([`ModuleMemoryProvider`]'s
+/// first call) and the eager path (boot) go through here, because a module
+/// admitted before these exist resolves no embedding provider and cannot be
+/// repaired without a restart.
+///
+/// # Errors
+///
+/// Returns a message when the module bus cannot start or the callbacks cannot
+/// be served on it.
+pub async fn install_host_callbacks(config: Arc<Config>) -> Result<(), String> {
+ let runtime = host::runtime()
+ .await
+ .map_err(|error| format!("the module bus is not running: {error}"))?;
+ super::memory_host::install(runtime.connection(), config)
+ .await
+ .map_err(|error| format!("the memory module host callbacks are unavailable: {error}"))
+}
+
/// A memory driver served by the loaded `tinymemory` module.
pub struct ModuleMemoryProvider {
/// The id reported by [`MemoryProvider::driver_id`].
@@ -239,6 +290,10 @@ pub struct ModuleMemoryProvider {
memory_subdir: Option<String>,
/// Object path resolved for [`Self::memory_subdir`], once asked for.
resolved_path: tokio::sync::OnceCell<String>,
+ /// How long a bounded call waits for the module to load — see
+ /// [`MODULE_LOADING_GRACE`]. Overridable so a test can observe the loading
+ /// state without waiting eight seconds for it.
+ loading_grace: Duration,
}
impl std::fmt::Debug for ModuleMemoryProvider {
@@ -278,6 +333,23 @@ impl ModuleMemoryProvider {
verified: std::sync::OnceLock::new(),
memory_subdir: None,
resolved_path: tokio::sync::OnceCell::new(),
+ loading_grace: MODULE_LOADING_GRACE,
+ }
+ }
+
+ /// Bound how long a read waits for the module to load.
+ #[must_use]
+ pub fn with_loading_grace(mut self, grace: Duration) -> Self {
+ self.loading_grace = grace;
+ self
+ }
+
+ /// How long `operation` may wait for the module: `None` waits it out.
+ fn loading_grace(&self, operation: &str) -> Option<Duration> {
+ if UNBOUNDED_OPERATIONS.contains(&operation) {
+ None
+ } else {
+ Some(self.loading_grace)
}
}
@@ -334,20 +406,16 @@ impl ModuleMemoryProvider {
cannot be loaded; call modules::memory::set_modules_policy during boot"
))
})?;
- let runtime = host::runtime().await.map_err(|error| {
- MemoryError::Other(anyhow::anyhow!("the module bus is not running: {error}"))
- })?;
- super::memory_host::install(runtime.connection(), Arc::clone(config))
- .await
- .map_err(|error| {
- MemoryError::Other(anyhow::anyhow!(
- "the memory module host callbacks are unavailable: {error}"
- ))
- })?;
// TinyMemory resolves its embedding provider while the native library
// is admitted. Host callbacks must therefore exist before loading,
// including in tests and explicit-path overrides where no boot policy
// was available when the shared module runtime first started.
+ install_host_callbacks(Arc::clone(config))
+ .await
+ .map_err(|message| MemoryError::Other(anyhow::anyhow!(message)))?;
+ let runtime = host::runtime().await.map_err(|error| {
+ MemoryError::Other(anyhow::anyhow!("the module bus is not running: {error}"))
+ })?;
// A load failure is terminal for the process (the loader caches it),
// so every memory member would otherwise return the loader's raw
// message — release URLs, digest text, "restart the app" repeated per
@@ -355,15 +423,36 @@ impl ModuleMemoryProvider {
// user_error broadcast (once per process, metadata only) plus a
// stable, actionable error for the caller. The raw reason goes to the
// log, where an operator can act on it.
- ops::ensure_loaded(config, MODULE_ID).await.map_err(|message| {
- crate::openhuman::memory::tree::health::user_error::notice_memory_module_unavailable_once(
- &message,
- );
- MemoryError::Backend(
- "memory is unavailable: the memory module failed to load. Restart the app to retry; the reason is in the log."
- .to_string(),
- )
- })?;
+ //
+ // A load still in progress is different: nothing failed, the caller
+ // simply asked before the download or the initialisation finished. A
+ // read reports that as `Unavailable` — the retryable class — after its
+ // grace instead of hanging into the caller's own deadline; a write
+ // waits it out (see `UNBOUNDED_OPERATIONS`).
+ let grace = self.loading_grace(operation);
+ match ops::ensure_loaded_within(config, MODULE_ID, grace).await {
+ Ok(()) => {}
+ Err(ops::LoadError::StillLoading) => {
+ log::info!(
+ "[modules:memory] operation={operation} module still loading after {grace:?}; \
+ answering unavailable"
+ );
+ return Err(MemoryError::Unavailable(
+ "memory is still starting: the memory module is loading; try again in a moment"
+ .to_string(),
+ ));
+ }
+ Err(ops::LoadError::Failed(message)) => {
+ crate::openhuman::memory::tree::health::user_error::notice_memory_module_unavailable_once(
+ &message,
+ );
+ return Err(MemoryError::Backend(
+ "memory is unavailable: the memory module failed to load. Restart the app to \
+ retry; the reason is in the log."
+ .to_string(),
+ ));
+ }
+ }
let record = registry::find(MODULE_ID)
.ok_or_else(|| MemoryError::Other(anyhow::anyhow!("unknown module '{MODULE_ID}'")))?;
@@ -466,11 +555,28 @@ impl MemoryProvider for ModuleMemoryProvider {
// An unreachable module is a *health* answer, not an error: that is the
// question this method exists to answer, and returning `Down` is how
// status output shows an unsupported platform or a refused artifact.
+ //
+ // A module that is still loading is *not* down. `Down` is the signal
+ // that tells the kernel to give up on this driver and rebind the
+ // fallback, and a cold launch on a slow link must not trip it; the
+ // driver is serving, just not yet. Configuration stays authoritative:
+ // a host whose modules are switched off is down whatever the
+ // process-wide table says about a load someone else started.
+ let modules_enabled = self
+ .config
+ .as_ref()
+ .or_else(|| policy())
+ .is_some_and(|config| config.modules.enabled);
+ if modules_enabled && matches!(ops::state_of(MODULE_ID), super::types::ModuleState::Loading)
+ {
+ return MemoryHealth::degraded("the memory module is loading");
+ }
match self.proxy("health").await {
Ok(proxy) => proxy
.call::<MemoryHealth>("Health", ())
.await
.unwrap_or_else(|error| MemoryHealth::down(error.to_string())),
+ Err(MemoryError::Unavailable(reason)) => MemoryHealth::degraded(reason),
Err(error) => MemoryHealth::down(error.to_string()),
}
}
diff --git a/src/openhuman/modules/memory_tests.rs b/src/openhuman/modules/memory_tests.rs
index 420aea6cc0..5fbf4363a1 100644
--- a/src/openhuman/modules/memory_tests.rs
+++ b/src/openhuman/modules/memory_tests.rs
@@ -233,6 +233,67 @@ async fn shutdown_on_an_unused_driver_is_a_no_op() {
assert!(provider.shutdown().await.is_ok());
}
+#[tokio::test]
+async fn a_read_against_a_loading_module_reports_unavailable_within_its_grace() {
+ use crate::openhuman::modules::resolution::{self, Resolution};
+ use tinymemory_api::provider::mandatory::MemoryCore;
+
+ // Plant an in-flight slot for the memory module. The table is process-wide
+ // and shared with the rest of the suite, so the slot is settled and
+ // removed before this test returns; a parallel caller sees, at worst, a
+ // brief "loading" followed by the terminal failure it would have reached
+ // anyway with downloads off.
+ let table = resolution::table();
+ let sender = table.mark_in_flight_for_test(MODULE_ID);
+ let provider = ModuleMemoryProvider::new(Arc::new(Config::default()))
+ .with_loading_grace(std::time::Duration::from_millis(30));
+
+ // Loading is degraded, never down: `Down` is what rebinds the fallback.
+ let health = provider.health().await;
+ assert!(
+ matches!(
+ health,
+ tinymemory_api::health::MemoryHealth::Degraded { .. }
+ ),
+ "a loading module must report Degraded, got {health:?}"
+ );
+
+ // A read gives up after its grace with the retryable class, and does so
+ // promptly rather than at some caller's deadline.
+ let started = std::time::Instant::now();
+ let outcome = MemoryCore::get(&provider, "ns", "key").await;
+ assert!(
+ matches!(outcome, Err(MemoryError::Unavailable(_))),
+ "expected Unavailable while loading, got {outcome:?}"
+ );
+ assert!(started.elapsed() < std::time::Duration::from_secs(5));
+
+ table.complete(
+ MODULE_ID,
+ Resolution::Failed("planted by a test".to_string()),
+ sender,
+ );
+ table.reset_for_test(MODULE_ID);
+}
+
+#[test]
+fn writes_wait_for_the_module_and_reads_do_not() {
+ let provider = provider();
+ for write in ["store", "import_records", "run_source_sync", "shutdown"] {
+ assert_eq!(
+ provider.loading_grace(write),
+ None,
+ "{write} must wait it out"
+ );
+ }
+ for read in ["get", "recall", "list", "health", "namespaces"] {
+ assert!(
+ provider.loading_grace(read).is_some(),
+ "{read} must be bounded"
+ );
+ }
+}
+
#[test]
fn the_capability_list_matches_the_pinned_release() {
// ARTIFACT_CAPABILITIES describes what ONE specific release of the module
diff --git a/src/openhuman/modules/mod.rs b/src/openhuman/modules/mod.rs
index f8620bee76..daf10b932b 100644
--- a/src/openhuman/modules/mod.rs
+++ b/src/openhuman/modules/mod.rs
@@ -48,6 +48,7 @@ mod memory_host;
pub mod ops;
pub mod platform;
pub mod registry;
+mod resolution;
pub mod runtime;
pub mod schemas;
mod tokenjuice_host;
@@ -57,6 +58,6 @@ pub mod voice;
#[cfg(feature = "web3")]
pub mod wallet;
-pub use ops::ensure_loaded;
+pub use ops::{ensure_loaded, ensure_loaded_within, state_of, LoadError};
pub use schemas::{all_controller_schemas, all_registered_controllers};
pub use types::{LoadPolicy, ModuleRecord, ModuleState, ModuleStatus, PlatformAsset};
diff --git a/src/openhuman/modules/ops.rs b/src/openhuman/modules/ops.rs
index cb527f427a..cada62adff 100644
--- a/src/openhuman/modules/ops.rs
+++ b/src/openhuman/modules/ops.rs
@@ -10,44 +10,62 @@
//! download and a `dlopen` on every tool call to arrive at the same error, so a
//! failure is cached and returned directly. The user-visible consequence is that
//! fixing a module means restarting the core, which is stated in the error.
+//!
+//! # Where an artifact comes from, and where it stays
+//!
+//! Resolution order is cheapest-first: already loaded, a developer's override,
+//! the module search path, then the release cache. The cache is a directory per
+//! module version under [`install_dir`], filled by the first load — downloaded,
+//! verified against the digest in [`registry`], extracted — and re-verified from
+//! disk on every later launch. That is the difference between a launch that
+//! maps a library in milliseconds and one that downloads five archives over
+//! whatever network it happens to be on: the second is what every launch did
+//! before the cache existed, and on a link with one unreachable CDN address it
+//! cost minutes during which every memory call and every chat turn waited.
+//!
+//! # How callers wait
+//!
+//! Each module has one slot in [`super::resolution`]. The first caller runs the
+//! resolution as a process-lifetime task and every other caller waits on its
+//! outcome; two modules never queue behind each other. [`ensure_loaded_within`]
+//! bounds the wait, so a caller with a deadline of its own can report the module
+//! as still loading instead of hanging into that deadline.
-use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+use super::resolution::{self, Claim, Resolution, ResolutionState, ResolutionTable, Waited};
use super::types::{ModuleRecord, ModuleState, ModuleStatus};
use super::{host, platform, registry};
use crate::openhuman::config::Config;
-/// Outcome of resolving one module, remembered for the process lifetime.
-#[derive(Debug, Clone)]
-enum Resolution {
- Ready,
- /// Terminal. Carries the sanitised reason, never a path or URL.
+/// Why a bounded [`ensure_loaded_within`] did not end with the module serving.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum LoadError {
+ /// Terminal for the process. Carries a message suitable for a user or a
+ /// model: no artifact for this host, downloads disabled, a refused
+ /// artifact, or a previous failure in this process.
Failed(String),
+ /// The module is still being downloaded, verified, or initialised, and the
+ /// caller's bound passed first. Asking again later can succeed.
+ StillLoading,
}
-/// Per-module resolution results.
-fn resolutions() -> &'static Mutex<HashMap<String, Resolution>> {
- static RESOLUTIONS: OnceLock<Mutex<HashMap<String, Resolution>>> = OnceLock::new();
- RESOLUTIONS.get_or_init(|| Mutex::new(HashMap::new()))
-}
-
-/// Serialises resolution so two concurrent tool calls do not both download.
-///
-/// Coarse on purpose — one lock for all modules rather than one per module.
-/// Resolution happens at most once per module per process, so contention is
-/// bounded by the number of modules, and a per-module lock table would be more
-/// machinery than the problem justifies.
-fn resolve_gate() -> &'static tokio::sync::Mutex<()> {
- static GATE: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
- GATE.get_or_init(|| tokio::sync::Mutex::new(()))
+impl LoadError {
+ /// The message for a caller that cannot distinguish the two cases.
+ #[must_use]
+ pub fn into_message(self) -> String {
+ match self {
+ Self::Failed(message) => message,
+ Self::StillLoading => "the module is still loading; try again shortly".to_string(),
+ }
+ }
}
/// Ensure `id` is loaded and serving, loading it if this is the first ask.
///
-/// Resolution order is cheapest-first: already loaded, then an artifact already
-/// on disk, then the module search path, then a verified download.
+/// Waits without bound. Prefer [`ensure_loaded_within`] from any path that has
+/// a deadline of its own.
///
/// # Errors
///
@@ -55,45 +73,96 @@ fn resolve_gate() -> &'static tokio::sync::Mutex<()> {
/// cannot be loaded: no artifact for this host, downloads disabled, a refused
/// artifact, or a previous failure in this process.
pub async fn ensure_loaded(config: &Config, id: &str) -> Result<(), String> {
+ ensure_loaded_within(config, id, None)
+ .await
+ .map_err(LoadError::into_message)
+}
+
+/// [`ensure_loaded`] with a bound on how long this caller waits.
+///
+/// The bound is on the *wait*, never on the resolution: a caller that gives up
+/// leaves the download running and the slot intact, and a later call finds the
+/// outcome. `None` waits without bound.
+///
+/// # Errors
+///
+/// [`LoadError::Failed`] when the module cannot be loaded in this process;
+/// [`LoadError::StillLoading`] when `within` passed first.
+pub async fn ensure_loaded_within(
+ config: &Config,
+ id: &str,
+ within: Option<Duration>,
+) -> Result<(), LoadError> {
if !config.modules.enabled {
- return Err(format!(
+ return Err(LoadError::Failed(format!(
"module '{id}' is unavailable: modules are disabled in configuration"
- ));
+ )));
}
- let record = registry::find(id).ok_or_else(|| format!("unknown module '{id}'"))?;
+ let record =
+ registry::find(id).ok_or_else(|| LoadError::Failed(format!("unknown module '{id}'")))?;
- if let Some(cached) = cached_resolution(id) {
- return match cached {
- Resolution::Ready => Ok(()),
- Resolution::Failed(reason) => Err(reason),
- };
+ let receiver = match resolution::table().claim(id) {
+ Claim::Done(Resolution::Ready) => return Ok(()),
+ Claim::Done(Resolution::Failed(reason)) => return Err(LoadError::Failed(reason)),
+ Claim::Wait(receiver) => receiver,
+ Claim::Run { sender, receiver } => {
+ start_resolution(config.clone(), record, sender).await;
+ receiver
+ }
+ };
+ match ResolutionTable::wait(receiver, within).await {
+ Waited::Ready => Ok(()),
+ Waited::Failed(reason) => Err(LoadError::Failed(reason)),
+ Waited::StillLoading => Err(LoadError::StillLoading),
}
+}
- // One resolver at a time. Two chat turns asking for a document at once must
- // not both download the same archive.
- let _guard = resolve_gate().lock().await;
- // Re-check: the winner of the race may have resolved it while we waited.
- if let Some(cached) = cached_resolution(id) {
- return match cached {
- Resolution::Ready => Ok(()),
- Resolution::Failed(reason) => Err(reason),
- };
+/// 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) {
+ ResolutionState::Unresolved => ModuleState::Available,
+ ResolutionState::Loading => ModuleState::Loading,
+ ResolutionState::Ready => ModuleState::Ready,
+ ResolutionState::Failed(_) => ModuleState::Failed,
}
+}
- let outcome = resolve(config, record).await;
- let resolution = match &outcome {
- Ok(()) => Resolution::Ready,
- Err(reason) => Resolution::Failed(reason.clone()),
+/// Run the resolution for `record` and record its outcome.
+///
+/// Spawned on the module runtime, which lives for the process: a caller
+/// runtime that shuts down mid-load — a test's, an embedder's — must not
+/// cancel a resolution other callers are waiting on. Without a module runtime
+/// there is nothing to load into, so the outcome is recorded inline instead.
+async fn start_resolution(
+ config: Config,
+ record: &'static ModuleRecord,
+ sender: tokio::sync::watch::Sender<Option<Resolution>>,
+) {
+ let id = record.id;
+ let work = async move {
+ log::info!("[modules] resolving '{id}' {}", record.version);
+ let resolution = match resolve(&config, record).await {
+ Ok(()) => {
+ log::info!("[modules] '{id}' is serving");
+ Resolution::Ready
+ }
+ Err(reason) => {
+ log::warn!("[modules] '{id}' did not load: {reason}");
+ Resolution::Failed(reason)
+ }
+ };
+ resolution::table().complete(id, resolution, sender);
};
- if let Ok(mut cache) = resolutions().lock() {
- cache.insert(id.to_string(), resolution);
+ match host::runtime().await {
+ Ok(runtime) => {
+ runtime.spawn(work);
+ }
+ Err(error) => {
+ log::warn!("[modules] the module bus could not start: {error}");
+ work.await;
+ }
}
- outcome
-}
-
-/// The remembered outcome for `id`, if it has been resolved.
-fn cached_resolution(id: &str) -> Option<Resolution> {
- resolutions().lock().ok()?.get(id).cloned()
}
/// Do the actual work of getting `record` serving.
@@ -123,12 +192,6 @@ async fn resolve(config: &Config, record: &'static ModuleRecord) -> Result<(), S
return blocking(move || load_local(runtime, &path, record.id, module_config)).await;
}
- // An artifact already extracted into the install directory by an earlier run.
- if let Some(path) = installed_artifact(config, record) {
- let module_config = module_config(config, record.id);
- return blocking(move || load_local(runtime, &path, record.id, module_config)).await;
- }
-
// The search path tinybus itself honours, including OPENHUMAN_MODULE_PATH.
// A refused search-path artifact is ordinary — most directories hold
// nothing, and tinybus reports each refusal with a sanitised reason — so the
@@ -148,20 +211,42 @@ async fn resolve(config: &Config, record: &'static ModuleRecord) -> Result<(), S
return Ok(());
}
- if !config.modules.allow_download {
+ // The release cache: a verified artifact from an earlier launch, or a
+ // download into the same place. Off the runtime worker — the cold path
+ // fetches over the network, hashes the archive, extracts it and `dlopen`s
+ // the result, all synchronously, and left inline it would stall every
+ // other task sharing this worker for the length of a download on
+ // whatever link the user has.
+ let Some(root) = install_dir(config) else {
return Err(format!(
- "module '{}' is unavailable: no local artifact is installed and downloads are \
- disabled in configuration",
+ "module '{}' is unavailable: no directory is available to install modules into",
record.id
));
- }
-
- // Off the runtime worker. `load_github_release` fetches over the network,
- // hashes the archive, extracts it and `dlopen`s the result — all
- // synchronously. Left inline it would stall every other task sharing this
- // worker for the length of a download on whatever link the user has.
+ };
+ let allow_download = config.modules.allow_download;
let module_config = module_config(config, record.id);
- blocking(move || download(runtime, record, module_config)).await
+ let cache_root = root.clone();
+ let outcome =
+ blocking(move || load_cached(runtime, record, &cache_root, module_config, allow_download))
+ .await;
+ match outcome {
+ Ok(()) => {
+ prune_stale_versions(&root, record);
+ Ok(())
+ }
+ Err(reason) if !allow_download => {
+ log::debug!(
+ "[modules] '{}' release cache miss with downloads disabled: {reason}",
+ record.id
+ );
+ Err(format!(
+ "module '{}' is unavailable: no local artifact is installed and downloads are \
+ disabled in configuration",
+ record.id
+ ))
+ }
+ Err(reason) => Err(reason),
+ }
}
/// Run a blocking module operation on the blocking pool.
@@ -184,11 +269,19 @@ where
})
}
-/// Download, verify, and load the pinned release artifact for this host.
-fn download(
+/// Load the pinned release for this host through the release cache.
+///
+/// Tries the preferred artifact first and falls through on admission failure —
+/// a host newer than the newest published build runs that build, and one whose
+/// toolchain the newest artifact does not match falls back. Each artifact has
+/// its own directory under the version, so two builds of one release never
+/// share an extraction.
+fn load_cached(
runtime: &'static host::ModuleRuntime,
record: &'static ModuleRecord,
+ install_root: &Path,
module_config: serde_json::Value,
+ allow_download: bool,
) -> Result<(), String> {
let candidates = platform::host_candidates();
let assets: Vec<_> = candidates
@@ -203,20 +296,23 @@ fn download(
));
}
- // Try the preferred artifact first and fall through on admission failure —
- // a host newer than the newest published build runs that build, and one
- // whose toolchain the newest artifact does not match falls back.
let mut last_error = String::new();
for asset in assets {
- match runtime.host().load_github_release(
- record.release_url,
- asset.archive,
- Some(asset.sha256),
- module_config.clone(),
- ) {
+ let cache_dir = artifact_dir(install_root, record, asset.host_key);
+ let release = tinybus::module::CachedRelease {
+ release_url: record.release_url,
+ asset_name: asset.archive,
+ expected_sha256: Some(asset.sha256),
+ cache_dir: &cache_dir,
+ allow_download,
+ };
+ match runtime
+ .host()
+ .load_github_release_cached(&release, module_config.clone())
+ {
Ok(_) => {
log::info!(
- "[modules] loaded '{}' {} from the pinned release ({})",
+ "[modules] loaded '{}' {} ({}) through the release cache",
record.id,
record.version,
asset.host_key
@@ -242,6 +338,46 @@ fn download(
))
}
+/// Where one artifact of one module version is cached.
+fn artifact_dir(install_root: &Path, record: &ModuleRecord, host_key: &str) -> PathBuf {
+ 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) {
+ 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();
+ if !path.is_dir() || name == record.version || name.starts_with('.') {
+ 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,
@@ -365,13 +501,6 @@ fn local_override(config: &Config, id: &str) -> Option<PathBuf> {
})
}
-/// The artifact an earlier run extracted, if it is still there.
-fn installed_artifact(config: &Config, record: &ModuleRecord) -> Option<PathBuf> {
- let dir = install_dir(config)?.join(record.id).join(record.version);
- let candidate = dir.join(platform_library_name(record.id));
- candidate.is_file().then_some(candidate)
-}
-
/// Where downloaded artifacts are kept.
///
/// The user cache directory, falling back to the workspace when there is none —
@@ -390,18 +519,6 @@ pub fn install_dir(config: &Config) -> Option<PathBuf> {
Some(config.workspace_dir.join("modules"))
}
-/// The platform library file name for a module id.
-fn platform_library_name(id: &str) -> String {
- let stem = id.replace('-', "_");
- if cfg!(target_os = "windows") {
- format!("{stem}_module.dll")
- } else if cfg!(target_os = "macos") {
- format!("lib{stem}_module.dylib")
- } else {
- format!("lib{stem}_module.so")
- }
-}
-
/// Status of every module this build knows about.
#[must_use]
pub fn list(config: &Config) -> Vec<ModuleStatus> {
@@ -421,10 +538,11 @@ fn status_of(config: &Config, record: &ModuleRecord) -> ModuleStatus {
ModuleState::Unsupported,
Some("modules are disabled in configuration".to_string()),
),
- _ => match cached_resolution(record.id) {
- Some(Resolution::Ready) => (ModuleState::Ready, None),
- Some(Resolution::Failed(reason)) => (ModuleState::Failed, Some(reason)),
- None => {
+ _ => match resolution::table().peek(record.id) {
+ ResolutionState::Ready => (ModuleState::Ready, None),
+ ResolutionState::Loading => (ModuleState::Loading, None),
+ ResolutionState::Failed(reason) => (ModuleState::Failed, Some(reason)),
+ ResolutionState::Unresolved => {
let supported = platform::host_candidates()
.iter()
.any(|key| record.asset_for(key).is_some());
diff --git a/src/openhuman/modules/ops_tests.rs b/src/openhuman/modules/ops_tests.rs
index 45083d0e28..a52b05c338 100644
--- a/src/openhuman/modules/ops_tests.rs
+++ b/src/openhuman/modules/ops_tests.rs
@@ -178,3 +178,96 @@ fn module_config_hands_the_module_the_hosts_cloud_embedding_defaults() {
// The user's own model still travels, just not as the cloud fallback.
assert_eq!(sent["memory"]["embedding_model"], "nomic-embed-text:latest");
}
+
+#[tokio::test]
+async fn a_bounded_wait_with_nothing_cached_and_downloads_off_fails_rather_than_loading() {
+ // An isolated install directory: this machine's real cache may hold the
+ // module, and a warm hit would turn the terminal refusal into a load.
+ let install = tempfile::tempdir().expect("temp install dir");
+ let mut config = offline_config();
+ config.modules.install_dir = Some(install.path().display().to_string());
+
+ // Nothing to download from, nothing cached: the resolution settles at once,
+ // so a bounded caller gets the terminal reason, never `StillLoading`.
+ let outcome = ops::ensure_loaded_within(
+ &config,
+ "tinydocs",
+ Some(std::time::Duration::from_secs(30)),
+ )
+ .await;
+ match outcome {
+ Err(ops::LoadError::Failed(reason)) => assert!(
+ reason.contains("downloads are disabled")
+ || reason.contains("not available for this platform"),
+ "unhelpful message: {reason}"
+ ),
+ other => panic!("expected a terminal failure, got {other:?}"),
+ }
+
+ // The outcome is remembered as a failure, and reported as one.
+ assert_eq!(ops::state_of("tinydocs"), ModuleState::Failed);
+ let status = list(&config)
+ .into_iter()
+ .find(|status| status.id == "tinydocs")
+ .expect("tinydocs is a registry entry");
+ assert_eq!(status.state, ModuleState::Failed);
+ assert!(status.detail.is_some());
+}
+
+#[test]
+fn each_artifact_of_a_version_has_its_own_cache_directory() {
+ let record = registry::find("tinydocs").expect("tinydocs is a registry entry");
+ let root = std::path::Path::new("/cache/modules");
+ let dir = ops::artifact_dir(root, record, "macos-26-arm64");
+ assert_eq!(
+ dir,
+ root.join("tinydocs")
+ .join(record.version)
+ .join("macos-26-arm64")
+ );
+ assert_ne!(dir, ops::artifact_dir(root, record, "macos-15-arm64"));
+}
+
+#[test]
+fn pruning_keeps_the_pinned_version_and_anything_still_being_staged() {
+ let record = registry::find("tinydocs").expect("tinydocs is a registry entry");
+ let install = tempfile::tempdir().expect("temp install dir");
+ let module_root = install.path().join(record.id);
+ let pinned = module_root.join(record.version);
+ let stale = module_root.join("0.0.1");
+ let staging = module_root.join(".staging-abc123");
+ for dir in [&pinned, &stale, &staging] {
+ std::fs::create_dir_all(dir).unwrap();
+ std::fs::write(dir.join("marker"), b"x").unwrap();
+ }
+ // A stray file beside the version directories is not a version.
+ std::fs::write(module_root.join("notes.txt"), b"x").unwrap();
+
+ ops::prune_stale_versions(install.path(), record);
+
+ assert!(pinned.join("marker").is_file(), "the pinned version stays");
+ assert!(
+ staging.join("marker").is_file(),
+ "an in-progress staging dir stays"
+ );
+ assert!(!stale.exists(), "an unpinned version is removed");
+ assert!(module_root.join("notes.txt").is_file());
+
+ // A module that was never cached has nothing to prune, and says nothing.
+ ops::prune_stale_versions(&install.path().join("never"), record);
+}
+
+#[test]
+fn a_module_nobody_asked_for_is_available_not_loading() {
+ assert_eq!(ops::state_of("never-asked"), ModuleState::Available);
+}
+
+#[test]
+fn load_errors_render_for_callers_that_cannot_wait_again() {
+ assert_eq!(
+ ops::LoadError::Failed("refused".to_string()).into_message(),
+ "refused"
+ );
+ let message = ops::LoadError::StillLoading.into_message();
+ assert!(message.contains("still loading"), "{message}");
+}
diff --git a/src/openhuman/modules/resolution.rs b/src/openhuman/modules/resolution.rs
new file mode 100644
index 0000000000..637ad8229d
--- /dev/null
+++ b/src/openhuman/modules/resolution.rs
@@ -0,0 +1,210 @@
+//! 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));
+ }
+
+ /// 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/src/openhuman/modules/resolution_tests.rs b/src/openhuman/modules/resolution_tests.rs
new file mode 100644
index 0000000000..66a2810129
--- /dev/null
+++ b/src/openhuman/modules/resolution_tests.rs
@@ -0,0 +1,115 @@
+//! 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);
+}
diff --git a/vendor/tinybus b/vendor/tinybus
index 92b817e42e..8b6793a147 160000
--- a/vendor/tinybus
+++ b/vendor/tinybus
@@ -1 +1 @@
-Subproject commit 92b817e42ecb980628166dd31b465524130de2f5
+Subproject commit 8b6793a14722609c9328a9a58b31454941be225d