Skip to content

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

Ask the driver to re-embed instead of the engine's queue

Shanuc264cb0369c2
diff --git a/src/openhuman/config/ops/model.rs b/src/openhuman/config/ops/model.rs
index 9eb59032c2..5ba45e79c5 100644
--- a/src/openhuman/config/ops/model.rs
+++ b/src/openhuman/config/ops/model.rs
@@ -253,7 +253,7 @@ pub async fn apply_model_settings(
// so a UI embedder switch recovers prior memory under the new
// signature. Coverage-gated + non-fatal: if the active signature did
// not actually change, this enqueues nothing.
- tinymemory_core::queue::ensure_reembed_backfill(config);
+ crate::openhuman::memory::ops::maintenance::reembed_best_effort(config, "model settings").await;
// #5324: the embedder may have just moved off the exhausted managed
// budget onto local Ollama / a BYO provider. Give the jobs that parked as
// `unrecoverable` under the old provider a fresh attempt budget — but ONLY
@@ -348,7 +348,8 @@ pub async fn apply_memory_settings(
// dark. Idempotent + non-fatal (covered space enqueues nothing; errors
// are logged, never fail the settings save). §7's migration is
// one-shot so it does not cover a later switch — this does.
- tinymemory_core::queue::ensure_reembed_backfill(config);
+ crate::openhuman::memory::ops::maintenance::reembed_best_effort(config, "memory settings")
+ .await;
// #5324: same rationale as the model-settings path — a switch away from
// the exhausted managed budget must un-park the jobs that failed under it,
// but a `memory_window` / `auto_save` / `backend` save must not. Gate on a
diff --git a/src/openhuman/inference/embeddings/rpc.rs b/src/openhuman/inference/embeddings/rpc.rs
index ad9d002ffb..01e203b935 100644
--- a/src/openhuman/inference/embeddings/rpc.rs
+++ b/src/openhuman/inference/embeddings/rpc.rs
@@ -376,7 +376,11 @@ pub async fn update_settings(
config.save().await.map_err(|e| e.to_string())?;
if sig_changed {
- tinymemory_core::queue::ensure_reembed_backfill(&config);
+ crate::openhuman::memory::ops::maintenance::reembed_best_effort(
+ &config,
+ "embedding settings",
+ )
+ .await;
}
// #5324: this is the exact screen the "embedding budget reached" alert
diff --git a/src/openhuman/memory/binding.rs b/src/openhuman/memory/binding.rs
index deaab19be0..bbaac311ae 100644
--- a/src/openhuman/memory/binding.rs
+++ b/src/openhuman/memory/binding.rs
@@ -476,6 +476,12 @@ pub fn for_workspace(
#[cfg(test)]
pub(crate) struct FixedDiagnostics {
inner: NullMemoryProvider,
+ /// How many times the host has asked this driver to re-embed.
+ ///
+ /// `reembed` enqueues work rather than doing it, so the host's side of that
+ /// contract is only that it *asked* — whether a row appears is the driver's
+ /// business, and pinning it here would test the driver through the host.
+ reembed_calls: std::sync::atomic::AtomicUsize,
store: crate::openhuman::memory::api::provider::types::StoreStats,
queue: crate::openhuman::memory::api::provider::types::QueueStats,
failure: Option<crate::openhuman::memory::api::provider::types::QueueFailure>,
@@ -506,8 +512,14 @@ mod fixed_diagnostics_impl {
store,
queue,
failure: None,
+ reembed_calls: std::sync::atomic::AtomicUsize::new(0),
}
}
+
+ /// How many times [`MemoryMaintenance::reembed`] has been called.
+ pub(crate) fn reembed_calls(&self) -> usize {
+ self.reembed_calls.load(std::sync::atomic::Ordering::SeqCst)
+ }
}
#[async_trait]
@@ -586,6 +598,8 @@ mod fixed_diagnostics_impl {
#[async_trait]
impl MemoryMaintenance for FixedDiagnostics {
async fn reembed(&self) -> Result<MaintenanceReport, MemoryError> {
+ self.reembed_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(MaintenanceReport::default())
}
@@ -647,12 +661,14 @@ pub(crate) fn install_diagnostics_for_test(
cfg: &MemorySubsystemConfig,
store: crate::openhuman::memory::api::provider::types::StoreStats,
queue: crate::openhuman::memory::api::provider::types::QueueStats,
-) {
+) -> Arc<FixedDiagnostics> {
+ let driver = Arc::new(FixedDiagnostics::new(store, queue));
install_for_test(
workspace_dir,
cfg,
- Arc::new(FixedDiagnostics::new(store, queue)),
+ Arc::clone(&driver) as Arc<dyn MemoryProvider>,
);
+ driver
}
/// Install `provider` as the binding a workspace resolves to.
diff --git a/src/openhuman/memory/direct_engine_refs_tests.rs b/src/openhuman/memory/direct_engine_refs_tests.rs
index ffbed0a3a7..2492bb11c2 100644
--- a/src/openhuman/memory/direct_engine_refs_tests.rs
+++ b/src/openhuman/memory/direct_engine_refs_tests.rs
@@ -112,8 +112,17 @@
//! `util::redact` (136 lines over `sha2`) is the clean case, and it costs
//! `sha2` in the contract crate.
//! - **The re-embed queue** (~8 files) — `queue::{start, store, types,
-//! ensure_reembed_backfill, requeue_failed_after_provider_change,
-//! drain_until_idle, wake_workers, backfill_in_progress}`. No family.
+//! requeue_failed_after_provider_change, drain_until_idle, wake_workers,
+//! backfill_in_progress}`. No family.
+//!
+//! `ensure_reembed_backfill` is off this list, and how it left is the part
+//! worth keeping: it needed no upstream work at all. `Maintenance::reembed`
+//! is documented as "recompute embeddings for content whose embedding is
+//! missing or stale", and the TinyCortex driver implements it by calling
+//! `ensure_reembed_backfill` and reporting how many jobs that enqueued — so
+//! the five host call sites were already expressible and this audit had
+//! simply not checked. Before sizing an upstream ask for anything else here,
+//! read what the driver already does with the nearest existing method.
//! - **Engine-shaped integration internals** (~11 files) —
//! `tinycortex::{memory_config_from, run_composio_connection,
//! load_composio_sync_state, HostSyncAdapter, CodingSession*}`. Named after
@@ -386,7 +395,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/config/ops/model.rs",
Verdict::NeedsWiderSeam,
- "the re-embed queue (queue::ensure_reembed_backfill, queue::requeue_failed_after_provider_change) has no capability family",
+ "queue::requeue_failed_after_provider_change has no capability family; the enqueue half moved onto Maintenance::reembed, which already was this call",
),
(
"src/openhuman/cron/scheduler.rs",
@@ -421,7 +430,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/inference/embeddings/rpc.rs",
Verdict::NeedsWiderSeam,
- "the re-embed queue (queue::ensure_reembed_backfill, queue::requeue_failed_after_provider_change) has no capability family",
+ "queue::requeue_failed_after_provider_change has no capability family; the enqueue half moved onto Maintenance::reembed, which already was this call",
),
(
"src/openhuman/integrations/composio/ops/memory_cleanup.rs",
@@ -546,7 +555,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/memory/sync_events_bridge.rs",
Verdict::NeedsWiderSeam,
- "the re-embed queue (queue::ensure_reembed_backfill, sync_events) has no capability family",
+ "sync_events is engine-owned vocabulary with no capability family; the enqueue half moved onto Maintenance::reembed",
),
(
"src/openhuman/memory/tools/flavour.rs",
@@ -591,7 +600,7 @@ const ALLOWED: &[(&str, Verdict, &str)] = &[
(
"src/openhuman/security/credentials/ops.rs",
Verdict::NeedsWiderSeam,
- "two blockers: the re-embed queue (queue::ensure_reembed_backfill), which has no capability family; and the in-process engine handle (global::init), which belongs to memory::binding",
+ "the in-process engine handle (global::init), which belongs to memory::binding; the re-embed enqueue that was the second blocker moved onto Maintenance::reembed",
),
(
"src/openhuman/skills/runtime/run_machinery.rs",
diff --git a/src/openhuman/memory/ops/maintenance.rs b/src/openhuman/memory/ops/maintenance.rs
new file mode 100644
index 0000000000..b67c2bd4e9
--- /dev/null
+++ b/src/openhuman/memory/ops/maintenance.rs
@@ -0,0 +1,76 @@
+//! Upkeep asked of the bound memory driver rather than of TinyCortex.
+//!
+//! The operations here are scheduler-driven housekeeping — the `Maintenance`
+//! capability family. Each one used to be a direct call into
+//! `tinymemory_core::queue`, which is a second door into the memory subsystem
+//! that skips the capability filter and the wire error table
+//! (`memory::direct_engine_refs_tests` is the ratchet over the ones that
+//! remain).
+//!
+//! Everything here is **best-effort by contract**. These are called after a
+//! save has already succeeded, so a failure must not fail the caller's
+//! operation — but it must not be silently swallowed either, which is why each
+//! returns a `Result` for the call site to log rather than logging here and
+//! handing back nothing.
+
+use crate::openhuman::config::Config;
+use crate::openhuman::memory::binding;
+
+/// Ask the bound driver to enqueue re-embedding for content whose embedding is
+/// missing or stale, and answer how much work that enqueued.
+///
+/// This is idempotent and coverage-gated at the driver: when the active
+/// embedding signature has not actually changed there is nothing uncovered, so
+/// it enqueues nothing and reports `0`. Calling it after every embedder-adjacent
+/// save is therefore the intended usage, not a cost.
+///
+/// `0` from a driver that does not serve `Maintenance` means the same thing it
+/// means from one that does — no work was enqueued — which is true of a driver
+/// with no re-embedding to do.
+///
+/// # Errors
+///
+/// Whatever the driver reports. Callers surface it and carry on; none of them
+/// can undo the save that preceded it.
+pub async fn reembed(config: &Config) -> Result<u64, String> {
+ let binding = binding::for_config(config)?;
+ let Some(maintenance) = binding.provider().as_maintenance() else {
+ log::debug!(
+ "[memory::maintenance] reembed: driver '{}' does not serve Maintenance; nothing enqueued",
+ binding.driver_id()
+ );
+ return Ok(0);
+ };
+ let report = maintenance
+ .reembed()
+ .await
+ .map_err(|error| format!("reembed: {error}"))?;
+ log::debug!(
+ "[memory::maintenance] reembed: driver '{}' examined={} enqueued={}",
+ binding.driver_id(),
+ report.examined,
+ report.changed
+ );
+ Ok(report.changed)
+}
+
+/// Log-and-continue wrapper for the call sites that have nothing to report the
+/// count to.
+///
+/// The engine call this replaced swallowed its own errors the same way, so this
+/// keeps those sites behaving identically instead of making them grow error
+/// handling they have nowhere to put.
+pub async fn reembed_best_effort(config: &Config, context: &str) {
+ match reembed(config).await {
+ Ok(enqueued) => {
+ log::debug!("[memory::maintenance] {context}: enqueued {enqueued} re-embedding job(s)")
+ }
+ Err(error) => {
+ log::warn!("[memory::maintenance] {context}: re-embed enqueue failed: {error}")
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "maintenance_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/ops/maintenance_tests.rs b/src/openhuman/memory/ops/maintenance_tests.rs
new file mode 100644
index 0000000000..ba03e38957
--- /dev/null
+++ b/src/openhuman/memory/ops/maintenance_tests.rs
@@ -0,0 +1,64 @@
+//! Tests for [`super`] — upkeep asked of the bound driver.
+//!
+//! A sibling file rather than an inline module: the memory-guard bypass
+//! scanner does not brace-track `#[cfg(test)]` blocks, so a test double built
+//! from `NullMemoryProvider` inside one reads as a production bypass. Sibling
+//! `*_tests.rs` files are excluded by name, which is also this repo's stated
+//! convention for tests that outgrow a few lines.
+
+use super::*;
+
+fn test_config() -> (tempfile::TempDir, Config) {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.workspace_dir = tmp.path().to_path_buf();
+ (tmp, cfg)
+}
+
+/// A driver with no `Maintenance` reports no work rather than refusing.
+///
+/// This is the shape every call site depends on: each one runs after a save
+/// that already succeeded, so an error here would have nowhere to go. The
+/// engine call this replaced swallowed its own failures, and the contract
+/// keeps the same promise for a driver that simply has no re-embedding to
+/// do.
+#[tokio::test]
+async fn a_driver_without_maintenance_enqueues_nothing_and_does_not_error() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::binding::install_for_test(
+ &cfg.workspace_dir,
+ &cfg.subsystems.memory,
+ std::sync::Arc::new(tinymemory_api::null::NullMemoryProvider::new()),
+ );
+
+ assert_eq!(
+ reembed(&cfg)
+ .await
+ .expect("a missing family is not an error"),
+ 0,
+ "no driver to enqueue work means no work enqueued, which is true \
+ rather than a refusal"
+ );
+}
+
+/// The driver's own count reaches the caller.
+///
+/// `reembed` is coverage-gated at the driver — it enqueues only what is
+/// uncovered — so the number is the only way a caller can tell "nothing to
+/// do" from "did something", and it has to be the driver's number rather
+/// than one this layer invents.
+#[tokio::test]
+async fn the_drivers_enqueued_count_reaches_the_caller() {
+ let (_tmp, cfg) = test_config();
+ crate::openhuman::memory::binding::install_diagnostics_for_test(
+ &cfg.workspace_dir,
+ &cfg.subsystems.memory,
+ Default::default(),
+ Default::default(),
+ );
+
+ // `FixedDiagnostics` answers the maintenance operations with an empty
+ // report, so this pins the plumbing: a driver that serves the family is
+ // asked, and its `changed` is what comes back.
+ assert_eq!(reembed(&cfg).await.expect("driver serves Maintenance"), 0);
+}
diff --git a/src/openhuman/memory/ops/mod.rs b/src/openhuman/memory/ops/mod.rs
index 1670245947..faafa03f26 100644
--- a/src/openhuman/memory/ops/mod.rs
+++ b/src/openhuman/memory/ops/mod.rs
@@ -30,6 +30,7 @@ pub mod guard;
pub mod helpers;
pub mod kv_graph;
pub mod learn;
+pub mod maintenance;
pub mod provider;
pub mod sync;
pub mod tool_memory;
diff --git a/src/openhuman/memory/sync_events_bridge.rs b/src/openhuman/memory/sync_events_bridge.rs
index ecb4fafd6e..2f2fdbfed4 100644
--- a/src/openhuman/memory/sync_events_bridge.rs
+++ b/src/openhuman/memory/sync_events_bridge.rs
@@ -80,7 +80,11 @@ impl EventHandler<DomainEvent> for SyncCompleteEmbedTrigger {
if let DomainEvent::MemorySyncStageChanged { stage, .. } = event {
if stage == "completed" {
log::debug!("[memory-sync] sync completed — triggering batch embedding backfill");
- tinymemory_core::queue::ensure_reembed_backfill(&self.config);
+ crate::openhuman::memory::ops::maintenance::reembed_best_effort(
+ &self.config,
+ "sync event",
+ )
+ .await;
}
}
}
diff --git a/src/openhuman/security/credentials/ops.rs b/src/openhuman/security/credentials/ops.rs
index cacba54a3d..28481b733e 100644
--- a/src/openhuman/security/credentials/ops.rs
+++ b/src/openhuman/security/credentials/ops.rs
@@ -640,7 +640,11 @@ async fn store_session_inner(
operation = "store_session",
"[credentials][auth-store] scheduler gate cleared; ensuring re-embed backfill after login"
);
- tinymemory_core::queue::ensure_reembed_backfill(&effective_config);
+ crate::openhuman::memory::ops::maintenance::reembed_best_effort(
+ &effective_config,
+ "session stored",
+ )
+ .await;
logs.push("memory re-embed backfill checked after login".to_string());
// Bind the Sentry scope to this user so background events that fire
diff --git a/src/openhuman/security/credentials/ops_tests.rs b/src/openhuman/security/credentials/ops_tests.rs
index a068769e7a..cbe488f005 100644
--- a/src/openhuman/security/credentials/ops_tests.rs
+++ b/src/openhuman/security/credentials/ops_tests.rs
@@ -40,12 +40,24 @@ impl Drop for EnvVarGuard {
}
fn test_config(tmp: &TempDir) -> Config {
- Config {
+ let config = Config {
workspace_dir: tmp.path().join("workspace"),
action_dir: tmp.path().join("workspace"),
config_path: tmp.path().join("config.toml"),
..Config::default()
- }
+ };
+ // Storing a session asks the memory driver to re-embed, and resolving a
+ // driver that nothing has installed means attempting to load the compiled
+ // module — which a unit test cannot do, but takes seconds to fail at.
+ // These are credentials tests; binding is not what they are about, and one
+ // of them asserts a latency budget that the attempt blows straight through.
+ crate::openhuman::memory::binding::install_diagnostics_for_test(
+ &config.workspace_dir,
+ &config.subsystems.memory,
+ Default::default(),
+ Default::default(),
+ );
+ config
}
fn jwt_with_payload(payload: serde_json::Value) -> String {
@@ -430,6 +442,14 @@ fn auth_me_store_validation_budget_reads_env_override() {
}
}
+/// Login asks the bound driver to re-embed.
+///
+/// This used to seed a chunk and count rows in `mem_tree_jobs`. The host asks
+/// the driver now, so the row is the driver's doing and belongs to the driver's
+/// suite — what is the host's, and what this pins, is that logging in asks at
+/// all. The seed stays because it is what makes the ask non-vacuous in the
+/// original scenario, and because the surrounding assertions still describe a
+/// workspace with content in it.
#[tokio::test]
async fn store_session_requeues_reembed_backfill_after_login() {
use chrono::TimeZone;
@@ -445,6 +465,15 @@ async fn store_session_requeues_reembed_backfill_after_login() {
let _home = EnvVarGuard::set_to_path("HOME", tmp.path());
let mut config = test_config(&tmp);
config.api_url = Some(spawn_auth_me_status(StatusCode::SERVICE_UNAVAILABLE).await);
+ // Without a driver installed, resolving one means loading the compiled
+ // module, which a unit test cannot do — so every ask would answer empty and
+ // this test would pass against nothing.
+ let driver = crate::openhuman::memory::binding::install_diagnostics_for_test(
+ &config.workspace_dir,
+ &config.subsystems.memory,
+ Default::default(),
+ Default::default(),
+ );
let ts = chrono::Utc.timestamp_millis_opt(1_700_000_000_000).unwrap();
let chunk = Chunk {
@@ -478,9 +507,9 @@ async fn store_session_requeues_reembed_backfill_after_login() {
.unwrap();
assert_eq!(
- count_reembed_backfill_jobs(&config),
+ driver.reembed_calls(),
0,
- "precondition: no active reembed backfill job exists before login"
+ "precondition: nothing has asked the driver to re-embed before login"
);
let token = jwt_with_payload(json!({
@@ -500,9 +529,10 @@ async fn store_session_requeues_reembed_backfill_after_login() {
"store_session should report the post-login backfill probe, got: {log_text}"
);
assert_eq!(
- count_reembed_backfill_jobs(&config),
+ driver.reembed_calls(),
1,
- "login must enqueue exactly one reembed_backfill chain for uncovered rows"
+ "login must ask the driver to re-embed exactly once — twice would enqueue \
+ a second chain over the same uncovered rows"
);
}