Skip to content

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

refactor(agent): update background delivery and store logic

Steven Enamakel373719b44c32
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs b/crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs
index b082e963aa..8f25b8ed0a 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions/store_adapter.rs
@@ -32,13 +32,16 @@ pub(in crate::agent::orchestration) fn open_driver_store(
ctx: &DispatchCtx,
workspace_dir: &Path,
) -> anyhow::Result<Arc<dyn CompletionStore>> {
- with_storage_context(ctx, || {
- let opened = crate::storage::local::open("background_completions", workspace_dir)?;
- let scoped = opened.scoped()?;
- let store = DriverCompletionStore::new(Arc::clone(scoped.documents()))
- .map_err(|error| anyhow::anyhow!("start the completion store bridge: {error}"))?;
- Ok(Arc::new(store) as Arc<dyn CompletionStore>)
- })
+ let tenant = ctx
+ .tenant()
+ .map_err(|error| anyhow::anyhow!("resolve the completion-store tenant: {error}"))?;
+ let backend = crate::storage::local::backend_for(workspace_dir)?;
+ let store = DriverCompletionStore::new(
+ backend,
+ crate::storage::sessions::session_scope(&crate::core::runtime::session_key(&tenant)),
+ )
+ .map_err(|error| anyhow::anyhow!("start the completion store bridge: {error}"))?;
+ Ok(Arc::new(store) as Arc<dyn CompletionStore>)
}
/// Scope storage access to the explicit context when one exists. A genuinely
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 5f01cf74ec..b6cd8dc038 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -161,7 +161,7 @@ fn schedule_delivery_inner(
// delayed task must run under the profile that scheduled it.
ctx.clone().spawn(async move {
let outcome = try_deliver(ctx.clone(), thread_id.clone(), fence.clone(), wait_idle).await;
- if outcome == DeliveryOutcome::Busy {
+ if outcome == DeliveryOutcome::ParentBusy {
// Still running past the ceiling: leave the record pending and
// wait again rather than overlap the user's turn.
log::debug!(
@@ -299,10 +299,15 @@ async fn try_deliver(
let turn_thread_id = thread_id.clone();
let give_up_thread_id = thread_id.clone();
let give_up_log_thread_id = thread_id.clone();
- let scoped_thread = crate::core::runtime::tenant::profile_key_in(
- &super::busy_guard::caller(&busy_ctx),
- &thread_id,
- );
+ let owner = match busy_ctx.tenant() {
+ Ok(tenant) => tenant.profile_only(),
+ Err(error) => {
+ log::debug!("[background_delivery] no tenant for completion delivery: {error}");
+ return DeliveryOutcome::Fenced;
+ }
+ };
+ let tenant_key = crate::core::runtime::tenant::profile_key_in(&owner, "");
+ let scoped_thread = crate::core::runtime::tenant::profile_key_in(&owner, &thread_id);
let deliver = move |records: &[CompletionRecord]| {
let notice = format_router.formatter().format_batch(records);
let ctx = ctx.clone();
@@ -342,6 +347,7 @@ async fn try_deliver(
let target = DeliveryTarget {
router: &router,
parent_key: &thread_id,
+ tenant_key: &tenant_key,
thread_key: &scoped_thread,
};
let outcome = if recovering {
@@ -476,8 +482,15 @@ where
// A busy thread defers *before* the claim: the claim counts a delivery
// attempt, and a user who keeps typing must not burn a record's budget.
if let Some(batch) = claim_ready(ctx, &router, &thread_id) {
- let task_ids: Vec<String> = batch.iter().map(|c| c.task_id.clone()).collect();
- slot.hold(&task_ids);
+ let receipts: Vec<_> = batch.iter().filter_map(CompletionRecord::receipt).collect();
+ if receipts.len() != batch.len() {
+ log::error!(
+ "[background_delivery] claimed completion batch contains a record without a receipt; refusing delivery thread_id={thread_id}"
+ );
+ router.release(&receipts);
+ return None;
+ }
+ slot.hold(&receipts);
// A user turn can start between the idle check inside `claim_ready` and
// the awaited turn below; re-check so a system turn is never streamed
// concurrently with it. Dropping the slot releases the lease (the claim
@@ -496,14 +509,14 @@ where
);
match deliver(thread_id.clone(), notice).await {
Ok(_) => {
- if let Err(error) = router.mark_delivered(&task_ids) {
+ if let Err(error) = router.mark_delivered(&receipts) {
// The reply is already in the thread; the record stays
// pending, so a later drain or a restart delivers it again
// (at-least-once).
log::error!(
"[background_delivery] delivered but could not settle records \
thread_id={thread_id} tasks=[{}] error={error}",
- task_ids.join(",")
+ receipts.iter().map(|receipt| receipt.task_id.as_str()).collect::<Vec<_>>().join(",")
);
}
}
@@ -516,7 +529,7 @@ where
// into the thread rather than discarded. A checkout failure
// publishes no `AgentError`, so it cannot drive the self-retrigger
// loop on its own; it only ever spends the budget.
- match router.mark_failed(&task_ids) {
+ match router.mark_failed(&receipts) {
Ok(gave_up) if !gave_up.is_empty() => {
// Stop retrying, but do NOT drop: the results exist and
// the user is owed them. Hand them to the give-up sink,
@@ -543,7 +556,7 @@ where
log::warn!(
"[background_delivery] delivery turn failed thread_id={thread_id} \
tasks=[{}] max_attempts={} error={e}",
- task_ids.join(","),
+ receipts.iter().map(|receipt| receipt.task_id.as_str()).collect::<Vec<_>>().join(","),
router.max_attempts()
);
let attempts = router
@@ -559,7 +572,7 @@ where
"[background_delivery] could not record the failed delivery \
thread_id={thread_id} error={error}"
);
- router.release(&task_ids);
+ router.release(&receipts);
}
}
// A batch can mix records at different attempt counts: some gave
diff --git a/crates/openhuman-core/src/artifacts/tiny_store.rs b/crates/openhuman-core/src/artifacts/tiny_store.rs
index 421f745ec0..b9a5d24bba 100644
--- a/crates/openhuman-core/src/artifacts/tiny_store.rs
+++ b/crates/openhuman-core/src/artifacts/tiny_store.rs
@@ -29,8 +29,8 @@ use std::sync::Arc;
use async_trait::async_trait;
use tiny_artifacts::{
- ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, Artifacts,
- Author, Content, FileStore,
+ ArtifactEvent, ArtifactEventKind, ArtifactKind, ArtifactObserver, ArtifactRecord, ArtifactStore,
+ Artifacts, Author, Content, FileRef, FileStore,
};
use super::files::FileRoots;
@@ -91,6 +91,74 @@ pub fn versioned_store(workspace_dir: &Path) -> super::version_documents::Docume
super::version_documents::DocumentArtifactStore::new(workspace_dir)
}
+/// Imports version records written by earlier OpenHuman builds, whose file
+/// references held host paths, through the owner's guarded legacy importer.
+struct LegacyFileImportStore {
+ records: Arc<dyn ArtifactStore>,
+ files: Arc<dyn FileStore>,
+ roots: tiny_artifacts::FileRoots,
+}
+
+impl LegacyFileImportStore {
+ async fn import_record(&self, mut record: ArtifactRecord) -> anyhow::Result<ArtifactRecord> {
+ let mut changed = false;
+ for version in &mut record.versions {
+ let Some(legacy) = version.file.clone() else {
+ continue;
+ };
+ if !Path::new(&legacy.key).is_absolute() {
+ continue;
+ }
+ let ext = Path::new(&legacy.key)
+ .extension()
+ .and_then(|ext| ext.to_str())
+ .unwrap_or("bin");
+ let key = format!("artifacts/files/{}/v{}.{}", record.id, version.version, ext);
+ let imported = tiny_artifacts::import_legacy_file(
+ self.files.as_ref(),
+ &self.roots,
+ &legacy,
+ &key,
+ )
+ .await?;
+ version.body = imported.key.clone();
+ version.file = Some(imported);
+ changed = true;
+ }
+ if changed {
+ self.records.upsert(&record).await?;
+ }
+ Ok(record)
+ }
+}
+
+#[async_trait]
+impl ArtifactStore for LegacyFileImportStore {
+ async fn list(&self) -> anyhow::Result<Vec<ArtifactRecord>> {
+ let mut imported = Vec::new();
+ for record in self.records.list().await? {
+ imported.push(self.import_record(record).await?);
+ }
+ Ok(imported)
+ }
+
+ async fn get(&self, id: &str) -> anyhow::Result<Option<ArtifactRecord>> {
+ self.records
+ .get(id)
+ .await?
+ .map(|record| self.import_record(record))
+ .transpose()
+ }
+
+ async fn upsert(&self, record: &ArtifactRecord) -> anyhow::Result<()> {
+ self.records.upsert(record).await
+ }
+
+ async fn delete(&self, id: &str) -> anyhow::Result<bool> {
+ self.records.delete(id).await
+ }
+}
+
/// Where an earlier build kept versioned records, one `<id>.json` each.
pub fn legacy_versioned_dir(workspace_dir: &Path) -> PathBuf {
workspace_dir.join("artifacts").join(VERSIONED_SUBDIR)
@@ -320,7 +388,15 @@ pub fn artifacts_service(
) -> Artifacts {
let roots = file_roots(workspace_dir, &files, action_dir);
let file_store = file_store_for(workspace_dir, ctx);
- let mut artifacts = Artifacts::new(Arc::new(versioned_store(workspace_dir)))
+ let mut records: Arc<dyn ArtifactStore> = Arc::new(versioned_store(workspace_dir));
+ if let Some(store) = file_store.as_ref() {
+ records = Arc::new(LegacyFileImportStore {
+ records,
+ files: store.clone(),
+ roots: guarded_roots(roots.clone()),
+ });
+ }
+ let mut artifacts = Artifacts::new(records)
.with_observer(Arc::new(LegacyUiBridge::new(
workspace_dir,
files,