The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(threads): split legacy import and transcript key out of storage schema
Steven Enamakel824b1e70a0f2
diff --git a/crates/openhuman-core/src/threads/store/legacy_import.rs b/crates/openhuman-core/src/threads/store/legacy_import.rsindex b047e39961..ddf8f87287 100644--- a/crates/openhuman-core/src/threads/store/legacy_import.rs+++ b/crates/openhuman-core/src/threads/store/legacy_import.rs@@ -4,8 +4,8 @@//! upsert/delete log) plus one `threads/<hex(thread_id)>.jsonl` per thread//! under `<workspace>/memory/conversations/`. The file store is gone, so the//! first use of a workspace's backend folds those files into it. The files are-//! only ever **read**: a marker document in the backend records completion, and-//! the legacy tree stays byte-identical (`storage::import` follows the same+//! only ever **read**: a `tsd.migrations` entry in the backend records+//! completion, and the legacy tree stays byte-identical (`storage::import` follows the same//! rule for the per-domain databases).use std::collections::BTreeMap;@@ -17,17 +17,22 @@ use sha2::{Digest, Sha256};use tinyagents_session::threads::{ConversationPersistence, CreateConversationThread, DriverConversationStore, ThreadMessage,};-use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition};+use tinystoragedrivers::CollectionSpec;use crate::storage::documents::Repo;+use crate::storage::import_state;-const MARKERS: &str = "threads_import";+/// The `tsd.migrations` owner of the import.+const OWNER: &str = "threads";+/// The old marker collection, now the `kind` of the import's step.+const IMPORT_KIND: &str = "threads_import";const MARKER_PREFIX: &str = "legacy-conversations";const LOG_PREFIX: &str = "[conversations:import]";-/// The collection that holds the completion marker.+/// The collections the thread host declares: the transcript keys. The import+/// state is in `tsd.migrations`, which `Registry::prepare` declares.pub(super) fn collections() -> Vec<CollectionSpec> {- vec![CollectionSpec::new(MARKERS)]+ vec![super::storage_schema::spec()]}/// The `threads.jsonl` records the importer needs; the stats records the old@@ -148,7 +153,7 @@ pub(super) fn import_once() -> Result<()> {let root = super::backend::legacy_root(workspace_dir);let source = crate::storage::source_key(&root);- let marker_id = format!("{MARKER_PREFIX}:{source}");+ let step = import_state::step_id(IMPORT_KIND, &format!("{MARKER_PREFIX}:{source}"));repo.once_per_backend(&format!("legacy-import:{source}"), || {match std::fs::metadata(root.join("threads.jsonl")) {Ok(meta) if meta.is_file() => {}@@ -158,52 +163,29 @@ pub(super) fn import_once(return Err(anyhow::Error::new(error).context("stat the legacy threads log"))}}- let marked = repo.run(|docs| {- let marker_id = marker_id.clone();- async move { docs.get(MARKERS, &marker_id).await }- })?;- if marked.is_some() {+ if import_state::is_done(repo, OWNER, &step)? {log::debug!("{LOG_PREFIX} already imported");return Ok(());}- let claimed =- crate::storage::import_claim::with_claim(repo, MARKERS, &marker_id.clone(), || {- let marked = repo.run(|docs| {- let marker_id = marker_id.clone();- async move { docs.get(MARKERS, &marker_id).await }- })?;- if marked.is_some() {- return Ok(());- }- let threads = fold_threads(&root)?;- let mut messages = Vec::with_capacity(threads.len());- for thread in &threads {- messages.push(read_jsonl::<ThreadMessage>(&messages_path(- &root, &thread.id,- ))?);- }- let store = store.clone();- let (threads_n, messages_n) = crate::storage::block_on_anyhow(async move {- copy(&store, threads, messages).await- })?;- repo.run(|docs| async move {- match docs- .put(- MARKERS,- &marker_id,- serde_json::json!({ "threads": threads_n, "messages": messages_n }),- Precondition::Absent,- )- .await- {- Ok(_) => Ok(()),- Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),- Err(error) => Err(error),- }- })?;- log::info!("{LOG_PREFIX} imported threads={threads_n} messages={messages_n}");- Ok(())+ let claimed = import_state::with_claim(repo, OWNER, &step, || {+ if import_state::is_done(repo, OWNER, &step)? {+ return Ok(());+ }+ let threads = fold_threads(&root)?;+ let mut messages = Vec::with_capacity(threads.len());+ for thread in &threads {+ messages.push(read_jsonl::<ThreadMessage>(&messages_path(+ &root, &thread.id,+ ))?);+ }+ let store = store.clone();+ let (threads_n, messages_n) = crate::storage::block_on_anyhow(async move {+ copy(&store, threads, messages).await})?;+ import_state::set_done(repo, OWNER, &step)?;+ log::info!("{LOG_PREFIX} imported threads={threads_n} messages={messages_n}");+ Ok(())+ })?;if claimed.is_none() {log::debug!("{LOG_PREFIX} another process is importing; skipped");}diff --git a/crates/openhuman-core/src/threads/store/storage_schema.rs b/crates/openhuman-core/src/threads/store/storage_schema.rsnew file mode 100644index 0000000000..4cf479eda1--- /dev/null+++ b/crates/openhuman-core/src/threads/store/storage_schema.rs@@ -0,0 +1,51 @@+//! The `threads` owner's storage schema: what the host keeps about a+//! conversation beside the conversation records TinyAgents owns+//! (`conversations.*`).+//!+//! | v1 | v2 | scope |+//! |---|---|---|+//! | `threads_transcript_keys` (id = thread id) | `threads.transcript_keys` (id `Key::of([thread_id])`) | tenant |+//!+//! The importer marker `threads_import` is not a collection any more: the+//! legacy JSONL import is a `tsd.migrations` entry+//! ([`crate::storage::import_state`]).++use tinystoragedrivers::schema::{Schema, ScopeClass, SourceRecord, Step, TargetRecord};+use tinystoragedrivers::{CollectionSpec, Result};++use crate::storage::schema_support::{key_of, owner};++pub(super) const TRANSCRIPT_KEYS: &str = "threads.transcript_keys";+pub(super) const LEGACY_TRANSCRIPT_KEYS: &str = "threads_transcript_keys";+const SCHEMA: u32 = 2;++/// What the thread host keeps and the step from the v1 collection.+#[must_use]+pub fn storage_schema() -> Schema {+ Schema::new(owner("threads"))+ .collection_with(SCHEMA, spec(), ScopeClass::Tenant)+ .step(+ Step::new("transcript_keys_v2", TRANSCRIPT_KEYS, 1, SCHEMA, transcript_keys_v2)+ .source(LEGACY_TRANSCRIPT_KEYS),+ )+}++pub(super) fn spec() -> CollectionSpec {+ CollectionSpec::new(TRANSCRIPT_KEYS)+}++fn transcript_keys_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ batch+ .into_iter()+ .map(|record| {+ Ok(+ TargetRecord::new(TRANSCRIPT_KEYS, key_of(&record.id)?, record.body)+ .created_ms(record.meta.created_ms),+ )+ })+ .collect()+}++#[cfg(test)]+#[path = "storage_schema_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/threads/store/storage_schema_tests.rs b/crates/openhuman-core/src/threads/store/storage_schema_tests.rsnew file mode 100644index 0000000000..5b882c8c2f--- /dev/null+++ b/crates/openhuman-core/src/threads/store/storage_schema_tests.rs@@ -0,0 +1,21 @@+use super::*;+use serde_json::{json, Value};+use tinystoragedrivers::Meta;++#[test]+fn a_recorded_key_moves_under_the_threads_owner_keeping_its_body() {+ let out = transcript_keys_v2(vec![SourceRecord {+ id: "thread/1".into(),+ body: json!({ "key": "profile~agent" }),+ meta: Meta::unknown(),+ }])+ .unwrap();+ assert_eq!(out[0].collection, TRANSCRIPT_KEYS);+ assert_eq!(out[0].id, "thread%2F1");+ assert_eq!(out[0].body, json!({ "key": "profile~agent" }) as Value);+}++#[test]+fn the_schema_composes_under_its_owner() {+ tinystoragedrivers::schema::Registry::compose([storage_schema()]).unwrap();+}diff --git a/crates/openhuman-core/src/threads/store/transcript_key.rs b/crates/openhuman-core/src/threads/store/transcript_key.rsindex 12ad20b3eb..18b2d6345b 100644--- a/crates/openhuman-core/src/threads/store/transcript_key.rs+++ b/crates/openhuman-core/src/threads/store/transcript_key.rs@@ -16,15 +16,16 @@ use serde_json::{json, Value};use tinystoragedrivers::{CollectionSpec, ErrorKind, Filter, Precondition};use super::backend::ConversationStore;+use super::storage_schema::{spec, TRANSCRIPT_KEYS as COLLECTION};use crate::storage::documents::Repo;+use crate::storage::schema_support::key_of;use crate::storage::{self};const DOMAIN: &str = "threads::transcript_key";-const COLLECTION: &str = "threads_transcript_keys";const LOG_PREFIX: &str = "[conversations:transcript-key]";fn collections() -> Vec<CollectionSpec> {- vec![CollectionSpec::new(COLLECTION)]+ vec![spec()]}impl ConversationStore {@@ -38,7 +39,7 @@ impl ConversationStore {/// The key `thread_id`'s transcripts were first written under, if recorded.pub fn transcript_key(&self, thread_id: &str) -> Result<Option<String>, String> {let repo = self.key_repo()?;- let id = thread_id.to_string();+ let id = key_of(thread_id).map_err(|e| format!("{LOG_PREFIX} {e}"))?;let doc = repo.run(|docs| async move { docs.get(COLLECTION, &id).await }).map_err(|e| format!("{LOG_PREFIX} read: {e:#}"))?;@@ -49,7 +50,8 @@ impl ConversationStore {/// recorded, and returns the key in effect (the first one recorded).pub fn record_transcript_key(&self, thread_id: &str, key: &str) -> Result<String, String> {let repo = self.key_repo()?;- let (id, wanted) = (thread_id.to_string(), key.to_string());+ let id = key_of(thread_id).map_err(|e| format!("{LOG_PREFIX} {e}"))?;+ let wanted = key.to_string();let recorded = repo.run(|docs| async move {let body: Value = json!({ "key": wanted });@@ -80,7 +82,7 @@ impl ConversationStore {/// Forgets `thread_id`'s recorded key (the thread was deleted).pub(super) fn forget_transcript_key(&self, thread_id: &str) {let outcome = self.key_repo().and_then(|repo| {- let id = thread_id.to_string();+ let id = key_of(thread_id).map_err(|e| e.to_string())?;repo.run(|docs| async move { docs.delete(COLLECTION, &id, Precondition::None).await }).map(|_| ()).map_err(|e| format!("{e:#}"))