Skip to content

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

feat(subagent-sessions): persist subagent session documents to store

Steven Enamakelee43a702c7ad
diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs
index e19299551a..f6fbf3920e 100644
--- a/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/subagent_sessions/mod.rs
@@ -1,5 +1,6 @@
mod ops;
mod store;
+mod storage_schema;
mod store_documents;
mod types;
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 445c93f1b8..1689fa9ebd 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,8 +9,12 @@
//!
//! | Collection | Document id | Holds |
//! | --- | --- | --- |
-//! | `subagent_sessions` | the session id | one [`DurableSubagentSession`] plus `created_at` for ordering |
-//! | `subagent_sessions_import` | `subagent_sessions.json:<workspace key>` | marker: the legacy file was imported (it is left byte-identical) |
+//! | `subagents.sessions` | `Key::of([session id])` | one [`DurableSubagentSession`] as a snake_case [`StoredSession`] with `_ms` times |
+//!
+//! The one-time import of the legacy `subagent_sessions.json` is recorded in
+//! `tsd.migrations` ([`crate::storage::import_state`]), not in a marker
+//! collection, so `load` never sees it as a session. Shapes and the v1 -> v2
+//! step are in [`super::storage_schema`].
//!
//! The callers in `ops.rs` load and save the whole list. `save` writes each session as
//! its own document, so a session's history stays well under any document-size
@@ -20,28 +24,128 @@
//! remove sessions another process added meanwhile.
use anyhow::Result;
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
use serde_json::Value;
-use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};
+use tinystoragedrivers::{CollectionSpec, Query, Sort};
+use tinyagents_session::transcript::TranscriptMessage;
-use super::types::DurableSubagentSession;
-use crate::storage::documents::Repo;
+use super::storage_schema::{spec, SESSIONS};
+use super::types::{DurableSubagentSession, DurableSubagentStatus};
+use crate::storage::documents::{compare_and_swap, Repo};
+use crate::storage::import_state;
+use crate::storage::schema_support::{key_of, ms_rfc3339, rfc3339_ms};
use crate::storage::DocumentStoreExt;
-const SESSIONS: &str = "subagent_sessions";
-/// Holds the marker document that records the one-time legacy file import, in
-/// a collection of its own so `load` never sees it as a session.
-const IMPORTED: &str = "subagent_sessions_import";
+/// The `tsd.migrations` owner of the legacy-file import.
+const OWNER: &str = "subagents";
+/// The old marker collection, now the `kind` of the import's step.
+const IMPORT_KIND: &str = "subagent_sessions_import";
const LEGACY_MARKER: &str = "subagent_sessions.json";
-/// The marker id for one workspace's legacy file, so workspaces sharing a
+/// The step id for one workspace's legacy file, so workspaces sharing a
/// backend each import their own.
-fn marker_id(source: &std::path::Path) -> String {
- format!("{LEGACY_MARKER}:{}", crate::storage::source_key(source))
+fn import_step(source: &std::path::Path) -> String {
+ import_state::step_id(
+ IMPORT_KIND,
+ &format!("{LEGACY_MARKER}:{}", crate::storage::source_key(source)),
+ )
}
const DOMAIN: &str = "subagent_sessions::store";
fn collections() -> Vec<CollectionSpec> {
- vec![CollectionSpec::new(SESSIONS), CollectionSpec::new(IMPORTED)]
+ vec![spec()]
+}
+
+/// A session as stored: snake_case, `_ms` times. The RPC shape
+/// ([`DurableSubagentSession`]) is camelCase with RFC 3339 strings.
+#[derive(Serialize, Deserialize)]
+struct StoredSession {
+ subagent_session_id: String,
+ parent_session: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ parent_thread_id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ worker_thread_id: Option<String>,
+ agent_id: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ display_name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ model: Option<String>,
+ sandbox_mode: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ action_root: Option<String>,
+ task_key: String,
+ task_title: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ current_task_id: Option<String>,
+ status: DurableSubagentStatus,
+ reusable: bool,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ with = "crate::agent::messages::history_wire::option"
+ )]
+ latest_history: Option<Vec<TranscriptMessage>>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ latest_error: Option<String>,
+ created_ms: i64,
+ updated_ms: i64,
+ last_used_ms: i64,
+}
+
+impl From<&DurableSubagentSession> for StoredSession {
+ fn from(s: &DurableSubagentSession) -> Self {
+ let created_ms = rfc3339_ms(&s.created_at).unwrap_or_default();
+ let updated_ms = rfc3339_ms(&s.updated_at).unwrap_or(created_ms);
+ Self {
+ subagent_session_id: s.subagent_session_id.clone(),
+ parent_session: s.parent_session.clone(),
+ parent_thread_id: s.parent_thread_id.clone(),
+ worker_thread_id: s.worker_thread_id.clone(),
+ agent_id: s.agent_id.clone(),
+ display_name: s.display_name.clone(),
+ model: s.model.clone(),
+ sandbox_mode: s.sandbox_mode.clone(),
+ action_root: s.action_root.clone(),
+ task_key: s.task_key.clone(),
+ task_title: s.task_title.clone(),
+ current_task_id: s.current_task_id.clone(),
+ status: s.status,
+ reusable: s.reusable,
+ latest_history: s.latest_history.clone(),
+ latest_error: s.latest_error.clone(),
+ created_ms,
+ updated_ms,
+ last_used_ms: rfc3339_ms(&s.last_used_at).unwrap_or(updated_ms),
+ }
+ }
+}
+
+impl From<StoredSession> for DurableSubagentSession {
+ fn from(s: StoredSession) -> Self {
+ Self {
+ subagent_session_id: s.subagent_session_id,
+ parent_session: s.parent_session,
+ parent_thread_id: s.parent_thread_id,
+ worker_thread_id: s.worker_thread_id,
+ agent_id: s.agent_id,
+ display_name: s.display_name,
+ model: s.model,
+ sandbox_mode: s.sandbox_mode,
+ action_root: s.action_root,
+ task_key: s.task_key,
+ task_title: s.task_title,
+ current_task_id: s.current_task_id,
+ status: s.status,
+ reusable: s.reusable,
+ latest_history: s.latest_history,
+ latest_error: s.latest_error,
+ created_at: ms_rfc3339(s.created_ms),
+ updated_at: ms_rfc3339(s.updated_ms),
+ last_used_at: ms_rfc3339(s.last_used_ms),
+ }
+ }
}
/// The document store for this call: the installed backend, else the
@@ -84,60 +188,38 @@ impl Docs {
docs.query_all(
SESSIONS,
&Query::all()
- .sort(Sort::asc("created_at"))
+ .sort(Sort::asc("created_ms"))
.sort(Sort::asc("_id")),
)
.await
})?;
stored
.into_iter()
- .map(|item| Ok(serde_json::from_value(item.doc)?))
+ .map(|item| Ok(serde_json::from_value::<StoredSession>(item.doc)?.into()))
.collect()
}
/// Whether the one-time legacy file import finished in this scope.
pub(super) fn legacy_imported(&self, source: &std::path::Path) -> Result<bool> {
- let id = marker_id(source);
- let found = self
- .0
- .run(|docs| async move { docs.get(IMPORTED, &id).await })?;
- Ok(found.is_some())
+ import_state::is_done(&self.0, OWNER, &import_step(source))
}
/// Imports `sessions` read from the legacy file (a stored newer copy
- /// wins), then records the import in a marker document.
+ /// wins), then records the import in `tsd.migrations`.
pub(super) fn import_legacy(
&self,
source: &std::path::Path,
sessions: &[DurableSubagentSession],
) -> Result<()> {
- let id = marker_id(source);
- let claimed =
- crate::storage::import_claim::with_claim(&self.0, IMPORTED, &id.clone(), || {
- // The process that held the claim before us may have finished.
- if self.legacy_imported(source)? {
- return Ok(());
- }
- self.save(sessions)?;
- let id = id.clone();
- self.0.run(|docs| async move {
- match docs
- .put(
- IMPORTED,
- &id,
- serde_json::json!({ "imported": true }),
- Precondition::Absent,
- )
- .await
- {
- Ok(_) => Ok(()),
- Err(error) if error.kind() == tinystoragedrivers::ErrorKind::Conflict => {
- Ok(())
- }
- Err(error) => Err(error),
- }
- })
- })?;
+ let step = import_step(source);
+ let claimed = import_state::with_claim(&self.0, OWNER, &step, || {
+ // The process that held the claim before us may have finished.
+ if self.legacy_imported(source)? {
+ return Ok(());
+ }
+ self.save(sessions)?;
+ import_state::set_done(&self.0, OWNER, &step)
+ })?;
if claimed.is_none() {
log::debug!(
"[subagent_sessions] another process is importing the legacy file; skipped"
@@ -149,10 +231,10 @@ impl Docs {
pub(super) fn save(&self, sessions: &[DurableSubagentSession]) -> Result<()> {
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());
- let updated = chrono::DateTime::parse_from_rfc3339(&session.updated_at).ok();
- writes.push((session.subagent_session_id.clone(), doc, updated));
+ let stored = StoredSession::from(session);
+ let updated = stored.updated_ms;
+ let id = key_of(&session.subagent_session_id)?;
+ writes.push((id, serde_json::to_value(&stored)?, updated));
}
log::debug!("[subagent_sessions] document save count={}", writes.len());
self.0.run(|docs| async move {
@@ -172,33 +254,29 @@ async fn write_if_newer(
docs: &std::sync::Arc<dyn crate::storage::DocumentStore>,
id: &str,
doc: Value,
- updated: Option<chrono::DateTime<chrono::FixedOffset>>,
+ updated_ms: i64,
) -> Result<(), crate::storage::StorageError> {
- use tinystoragedrivers::ErrorKind;
- for _ in 0..crate::storage::documents::CAS_ATTEMPTS {
- let precondition = match docs.get(SESSIONS, id).await? {
- None => Precondition::Absent,
- Some(stored) => {
- let stored_at = stored
- .doc
- .get("updatedAt")
- .and_then(Value::as_str)
- .and_then(|raw| chrono::DateTime::parse_from_rfc3339(raw).ok());
- if matches!((stored_at, updated), (Some(have), Some(ours)) if have >= ours) {
- return Ok(());
- }
- stored.unchanged()
- }
- };
- match docs.put(SESSIONS, id, doc.clone(), precondition).await {
- Ok(_) => return Ok(()),
- Err(error) if error.kind() == ErrorKind::Conflict => {}
- Err(error) => return Err(error),
+ use crate::storage::Precondition;
+ // A missing session is inserted; an existing one is replaced only while it
+ // is older than ours. Both go through tsd's one retrying compare-and-swap.
+ let repo = tinystoragedrivers::Repo::<Value>::new(docs, SESSIONS)?;
+ repo.update(id, |stored| {
+ if stored
+ .as_ref()
+ .and_then(|stored| stored.get("updated_ms"))
+ .and_then(Value::as_i64)
+ .is_some_and(|have| have >= updated_ms)
+ {
+ return Ok(None);
}
- }
- Err(crate::storage::StorageError::conflict(format!(
- "{SESSIONS}/{id} kept changing"
- )))
+ Ok(Some(doc.clone()))
+ })
+ .await
+ .map(|_| ())
+ .map_err(|error| {
+ let _ = Precondition::None;
+ error
+ })
}
#[cfg(test)]