Skip to content

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

fix(orchestration): store subagent sessions as per-session documents

Steven Enamakele604bdae7571
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs
index f861adf9bc..8c159f1d66 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs
@@ -180,6 +180,17 @@ pub(crate) fn list_task_records(workspace_dir: &Path) -> Vec<OrchestrationTaskRe
/// errors (e.g. a record that raced to terminal) are logged and skipped, and a
/// store-open failure simply reconciles nothing. Returns the count reconciled.
pub(crate) fn reconcile_orphaned_tasks_on_boot(workspace_dir: &Path) -> usize {
+ // On a backend several cores share, a non-terminal task in the ledger may
+ // belong to another live process, not to a dead one of ours; settling it
+ // would fail work that is still running. Only a backend this process owns
+ // (files, SQLite, memory) can be swept.
+ if crate::storage::installed_is_shared() {
+ log::debug!(
+ "[running_subagents] skipping orphan reconcile: storage backend is shared workspace_dir={}",
+ workspace_dir.display()
+ );
+ return 0;
+ }
let store = task_store_for_workspace(workspace_dir);
// The sweep itself — which statuses are live, and which terminal state each
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
index 65c9535e03..66b3df78f1 100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents.rs
@@ -9,20 +9,25 @@
//!
//! | Collection | Document id | Holds |
//! | --- | --- | --- |
-//! | `subagent_sessions` | `all` | `sessions`: the whole list the file held |
+//! | `subagent_sessions` | the session id | one [`DurableSubagentSession`] plus `created_at` for ordering |
//!
-//! The file store loads and saves the whole list, last writer wins; this keeps
-//! that contract so the callers in `ops.rs` are unchanged.
+//! The file store loads and saves the whole list, last writer wins. `save`
+//! keeps that contract for the callers in `ops.rs`, but writes each session as
+//! its own document (and deletes the ones the list no longer holds), so a
+//! session's history stays well under any document-size limit and two
+//! processes only collide on a session they both changed.
use anyhow::Result;
-use serde_json::json;
-use tinystoragedrivers::{CollectionSpec, Precondition};
+use std::collections::HashSet;
+
+use serde_json::Value;
+use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};
use super::types::DurableSubagentSession;
use crate::storage::documents::Repo;
+use crate::storage::DocumentStoreExt;
const SESSIONS: &str = "subagent_sessions";
-const LIST_ID: &str = "all";
const DOMAIN: &str = "subagent_sessions::store";
fn collections() -> Vec<CollectionSpec> {
@@ -44,23 +49,41 @@ impl Docs {
}
pub(super) fn load(&self) -> Result<Vec<DurableSubagentSession>> {
- let stored = self
- .0
- .run(|docs| async move { docs.get(SESSIONS, LIST_ID).await })?;
- let Some(stored) = stored else {
- return Ok(Vec::new());
- };
- let sessions = stored.doc.get("sessions").cloned().unwrap_or_default();
- Ok(serde_json::from_value(sessions)?)
+ let stored = self.0.run(|docs| async move {
+ docs.query_all(
+ SESSIONS,
+ &Query::all()
+ .sort(Sort::asc("created_at"))
+ .sort(Sort::asc("_id")),
+ )
+ .await
+ })?;
+ stored
+ .into_iter()
+ .map(|item| Ok(serde_json::from_value(item.doc)?))
+ .collect()
}
pub(super) fn save(&self, sessions: &[DurableSubagentSession]) -> Result<()> {
- let doc = json!({ "sessions": sessions });
- log::debug!("[subagent_sessions] document save count={}", sessions.len());
+ let mut writes = Vec::with_capacity(sessions.len());
+ for session in sessions {
+ let mut doc = serde_json::to_value(session)?;
+ doc["created_at"] = Value::from(session.created_at.as_str());
+ writes.push((session.subagent_session_id.clone(), doc));
+ }
+ log::debug!("[subagent_sessions] document save count={}", writes.len());
self.0.run(|docs| async move {
- docs.put(SESSIONS, LIST_ID, doc, Precondition::None)
- .await
- .map(|_| ())
+ let keep: HashSet<String> = writes.iter().map(|(id, _)| id.clone()).collect();
+ for (id, doc) in writes {
+ docs.put(SESSIONS, &id, doc, Precondition::None).await?;
+ }
+ for stored in docs.query_all(SESSIONS, &Query::all()).await? {
+ if !keep.contains(&stored.id) {
+ docs.delete(SESSIONS, &stored.id, Precondition::None)
+ .await?;
+ }
+ }
+ Ok(())
})
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs
index 70bb85bdba..6a34a83fbb 100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/store_documents_tests.rs
@@ -48,7 +48,7 @@ fn save_replaces_the_whole_list() {
assert_eq!(loaded.len(), 2);
assert_eq!(loaded[0].subagent_session_id, "a");
assert_eq!(loaded[1].status, DurableSubagentStatus::Idle);
- docs.save(&[session("c")]).unwrap();
+ docs.save(&[session("c")]).unwrap(); // a, b are deleted
let loaded = docs.load().unwrap();
assert_eq!(loaded.len(), 1);
assert_eq!(loaded[0].subagent_session_id, "c");
@@ -74,3 +74,20 @@ fn the_file_store_still_works_with_no_backend() {
.exists());
assert_eq!(store.load().unwrap().len(), 1);
}
+
+#[test]
+fn sessions_come_back_in_creation_order() {
+ let docs = docs_in(&MemoryStorage::new(), "local");
+ let mut early = session("z");
+ early.created_at = "2026-01-01T00:00:00Z".into();
+ let mut late = session("a");
+ late.created_at = "2026-02-01T00:00:00Z".into();
+ docs.save(&[late, early]).unwrap();
+ let ids: Vec<_> = docs
+ .load()
+ .unwrap()
+ .into_iter()
+ .map(|s| s.subagent_session_id)
+ .collect();
+ assert_eq!(ids, ["z", "a"]);
+}