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
feat(artifacts): add document versioning to artifact storage
Steven Enamakelf1e909c7de77
diff --git a/crates/openhuman-core/src/agent/artifacts/storage_schema.rs b/crates/openhuman-core/src/agent/artifacts/storage_schema.rsnew file mode 100644index 0000000000..829e59cbfe--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/storage_schema.rs@@ -0,0 +1,166 @@+//! The `artifacts` owner's storage schema: the artifact cards, the arguments+//! that regenerate them, and the versioned records, with the steps that bring+//! the v1 collections forward.+//!+//! | v1 | v2 | change |+//! |---|---|---|+//! | `artifacts` (`created_at` RFC 3339 beside `created_ms`) | `artifacts.records` | `created_at` dropped |+//! | `artifact_args` (`{args}`) | `artifacts.args` | `args` unwrapped: the body is the argument object |+//! | `artifact_versions` (camelCase `ArtifactRecord`) | `artifacts.versions` | snake_case keys, `*AtMillis` becomes `*_ms` |+//!+//! Arguments that are not a JSON object (no producer writes any) are kept as+//! `{"_args": <value>}`, so the body is always an object and+//! [`args_of_body`] reads either form back.++use serde_json::{json, Value};+use tinystoragedrivers::schema::{Schema, ScopeClass, SourceRecord, Step, TargetRecord};+use tinystoragedrivers::{CollectionSpec, IndexSpec, Result};++use super::types::ArtifactMeta;+use crate::storage::schema_support::{camel_keys, key_of, owner, snake_keys, time_ms};++pub(super) const RECORDS: &str = "artifacts.records";+pub(super) const ARGS: &str = "artifacts.args";+pub(super) const VERSIONS: &str = "artifacts.versions";+pub(super) const LEGACY_RECORDS: &str = "artifacts";+pub(super) const LEGACY_ARGS: &str = "artifact_args";+pub(super) const LEGACY_VERSIONS: &str = "artifact_versions";+const SCHEMA: u32 = 2;++/// The v2 names of the `*AtMillis` fields of `tiny_artifacts::ArtifactRecord`.+const RECORD_TIME_KEYS: [(&str, &str); 4] = [+ ("createdAtMillis", "created_ms"),+ ("updatedAtMillis", "updated_ms"),+ ("expiresAtMillis", "expires_ms"),+ ("publishedAtMillis", "published_ms"),+];++/// What the artifact stores keep and the steps from the v1 collections.+#[must_use]+pub fn storage_schema() -> Schema {+ Schema::new(owner("artifacts"))+ .collection_with(SCHEMA, records_spec(), ScopeClass::Tenant)+ .collection_with(SCHEMA, CollectionSpec::new(ARGS), ScopeClass::Tenant)+ .collection_with(SCHEMA, CollectionSpec::new(VERSIONS), ScopeClass::Tenant)+ .step(Step::new("records_v2", RECORDS, 1, SCHEMA, records_v2).source(LEGACY_RECORDS))+ .step(Step::new("args_v2", ARGS, 1, SCHEMA, args_v2).source(LEGACY_ARGS))+ .step(Step::new("versions_v2", VERSIONS, 1, SCHEMA, versions_v2).source(LEGACY_VERSIONS))+}++pub(super) fn records_spec() -> CollectionSpec {+ CollectionSpec::new(RECORDS).index(IndexSpec::new("by_thread", ["thread_id", "created_ms"]))+}++/// A card as its stored body: its fields with `created_at` replaced by+/// `created_ms`.+///+/// # Errors+///+/// When the card does not serialize.+pub(super) fn meta_to_body(meta: &ArtifactMeta) -> anyhow::Result<Value> {+ let mut doc = serde_json::to_value(meta)?;+ if let Some(fields) = doc.as_object_mut() {+ fields.remove("created_at");+ fields.insert("created_ms".into(), meta.created_at.timestamp_millis().into());+ }+ Ok(doc)+}++/// The card a stored body holds.+///+/// # Errors+///+/// When the body is not a card.+pub(super) fn meta_from_body(mut doc: Value) -> anyhow::Result<ArtifactMeta> {+ if let Some(fields) = doc.as_object_mut() {+ let created_ms = fields+ .remove("created_ms")+ .and_then(|v| v.as_i64())+ .unwrap_or_default();+ let at = chrono::DateTime::from_timestamp_millis(created_ms).unwrap_or_default();+ fields.insert("created_at".into(), json!(at));+ }+ Ok(serde_json::from_value(doc)?)+}++/// The stored body of arguments `args`.+pub(super) fn args_body(args: &Value) -> Value {+ if args.is_object() {+ args.clone()+ } else {+ json!({ "_args": args })+ }+}++/// The arguments a stored body holds.+pub(super) fn args_of_body(body: &Value) -> Value {+ match body.as_object() {+ Some(fields) if fields.len() == 1 && fields.contains_key("_args") => {+ body["_args"].clone()+ }+ _ => body.clone(),+ }+}++/// The stored body of a versioned record, and back.+pub(super) fn version_body(record: &Value) -> Value {+ snake_keys(record, &RECORD_TIME_KEYS)+}++pub(super) fn version_record(body: &Value) -> Value {+ camel_keys(body, &RECORD_TIME_KEYS)+}++fn records_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ batch+ .into_iter()+ .map(|record| {+ let mut body = record.body;+ let created_ms = body+ .get("created_ms")+ .and_then(Value::as_i64)+ .or_else(|| time_ms(&body, "created_at"))+ .unwrap_or(record.meta.created_ms);+ if let Some(fields) = body.as_object_mut() {+ fields.remove("created_at");+ fields.insert("created_ms".into(), created_ms.into());+ }+ Ok(TargetRecord::new(RECORDS, key_of(&record.id)?, body).created_ms(created_ms))+ })+ .collect()+}++fn args_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ batch+ .into_iter()+ .map(|record| {+ let args = record.body.get("args").cloned().unwrap_or(Value::Null);+ Ok(+ TargetRecord::new(ARGS, key_of(&record.id)?, args_body(&args))+ .created_ms(record.meta.created_ms),+ )+ })+ .collect()+}++fn versions_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ batch+ .into_iter()+ .map(|record| {+ // v1 added `updated_ms` beside the record's own `updatedAtMillis`;+ // the renamed field replaces it.+ let mut body = record.body;+ if let Some(fields) = body.as_object_mut() {+ fields.remove("updated_ms");+ }+ Ok(+ TargetRecord::new(VERSIONS, key_of(&record.id)?, version_body(&body))+ .created_ms(record.meta.created_ms),+ )+ })+ .collect()+}++#[cfg(test)]+#[path = "storage_schema_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/artifacts/storage_schema_tests.rs b/crates/openhuman-core/src/agent/artifacts/storage_schema_tests.rsnew file mode 100644index 0000000000..50d9313722--- /dev/null+++ b/crates/openhuman-core/src/agent/artifacts/storage_schema_tests.rs@@ -0,0 +1,77 @@+use super::*;+use tinystoragedrivers::Meta;++fn source(id: &str, body: Value) -> SourceRecord {+ SourceRecord {+ id: id.to_string(),+ body,+ meta: Meta::unknown(),+ }+}++#[test]+fn a_card_loses_its_formatted_creation_time() {+ let out = records_v2(vec![source(+ "a1",+ json!({+ "id": "a1", "kind": "document", "title": "T", "path": "a1/t.md", "size_bytes": 3,+ "status": "ready", "created_at": "1970-01-01T00:00:01Z", "created_ms": 1000,+ "thread_id": "th",+ }),+ )])+ .unwrap();+ assert_eq!(out[0].collection, RECORDS);+ assert_eq!(out[0].id, "a1");+ assert!(out[0].body.get("created_at").is_none());+ assert_eq!(out[0].body["created_ms"], 1000);+ assert_eq!(out[0].body["thread_id"], "th");+}++#[test]+fn arguments_are_unwrapped() {+ let out = args_v2(vec![+ source("a1", json!({ "args": { "prompt": "x" } })),+ source("a2", json!({ "args": [1, 2] })),+ ])+ .unwrap();+ assert_eq!(out[0].body, json!({ "prompt": "x" }));+ assert_eq!(out[1].body, json!({ "_args": [1, 2] }));+ assert_eq!(args_of_body(&out[0].body), json!({ "prompt": "x" }));+ assert_eq!(args_of_body(&out[1].body), json!([1, 2]));+}++#[test]+fn a_versioned_record_gets_snake_case_keys_and_ms_times() {+ let v1 = json!({+ "id": "r1", "title": "T", "kind": "document", "status": "ready",+ "createdAtMillis": 1, "updatedAtMillis": 2, "updated_ms": 2,+ "versions": [{+ "version": 1, "body": "b", "author": "agent", "authorId": "x",+ "createdAtMillis": 1,+ "published": { "url": "u", "publishedAtMillis": 3, "expiresAtMillis": 9, "public": true },+ }],+ });+ let out = versions_v2(vec![source("r1", v1.clone())]).unwrap();+ assert_eq!(out[0].collection, VERSIONS);+ assert_eq!(+ out[0].body,+ json!({+ "id": "r1", "title": "T", "kind": "document", "status": "ready",+ "created_ms": 1, "updated_ms": 2,+ "versions": [{+ "version": 1, "body": "b", "author": "agent", "author_id": "x",+ "created_ms": 1,+ "published": { "url": "u", "published_ms": 3, "expires_ms": 9, "public": true },+ }],+ })+ );+ // The same mapping reads it back as the library's camelCase record.+ let mut expected = v1;+ expected.as_object_mut().unwrap().remove("updated_ms");+ assert_eq!(version_record(&out[0].body), expected);+}++#[test]+fn the_schema_composes_under_its_owner() {+ tinystoragedrivers::schema::Registry::compose([storage_schema()]).unwrap();+}diff --git a/crates/openhuman-core/src/agent/artifacts/store_documents.rs b/crates/openhuman-core/src/agent/artifacts/store_documents.rsindex 85d5b18f40..b90fff6bb7 100644--- a/crates/openhuman-core/src/agent/artifacts/store_documents.rs+++ b/crates/openhuman-core/src/agent/artifacts/store_documents.rs@@ -10,8 +10,10 @@//!//! | Collection | Document id | Holds |//! | --- | --- | --- |-//! | `artifacts` | artifact id | the [`ArtifactMeta`] fields, plus `created_ms` for ordering |-//! | `artifact_args` | artifact id | `args`: the producer-tool arguments (the `args.json` sidecar) |+//! | `artifacts.records` | `Key::of([artifact id])` | the [`ArtifactMeta`] fields with `created_ms` in place of `created_at` |+//! | `artifacts.args` | `Key::of([artifact id])` | the producer-tool arguments (the `args.json` sidecar), unwrapped |+//!+//! The shapes and the v1 -> v2 steps are in [`super::storage_schema`].//!//! # Content files//!@@ -33,23 +35,21 @@use std::path::Path;use anyhow::{Context, Result};-use serde_json::{json, Value};-use tinystoragedrivers::{CollectionSpec, Filter, IndexSpec, Precondition, Query, Sort};+use serde_json::Value;+use tinystoragedrivers::{CollectionSpec, Filter, Precondition, Query, Sort};+use super::storage_schema::{+ args_body, args_of_body, meta_from_body, meta_to_body, records_spec, ARGS, RECORDS as ARTIFACTS,+};use super::types::ArtifactMeta;use crate::storage::documents::Repo;+use crate::storage::schema_support::key_of;use crate::storage::DocumentStoreExt;-const ARTIFACTS: &str = "artifacts";-const ARGS: &str = "artifact_args";const DOMAIN: &str = "artifacts::store";fn collections() -> Vec<CollectionSpec> {- vec![- CollectionSpec::new(ARTIFACTS)- .index(IndexSpec::new("by_thread", ["thread_id", "created_ms"])),- CollectionSpec::new(ARGS),- ]+ vec![records_spec(), CollectionSpec::new(ARGS)]}/// The document store for this call: the installed backend, else the@@ -88,9 +88,8 @@ impl Docs {}pub(super) fn put_meta(&self, meta: &ArtifactMeta) -> Result<()> {- let mut doc = serde_json::to_value(meta).context("serialize artifact meta")?;- doc["created_ms"] = Value::from(meta.created_at.timestamp_millis());- let id = meta.id.clone();+ let doc = meta_to_body(meta).context("serialize artifact meta")?;+ let id = key_of(&meta.id)?;self.0.run(|docs| async move {docs.put(ARTIFACTS, &id, doc, Precondition::None).await@@ -102,23 +101,22 @@ impl Docs {/// not overwrite a record created since, by this core or another)./// `false` when one was already there.fn put_meta_if_absent(&self, meta: &ArtifactMeta) -> Result<bool> {- let mut doc = serde_json::to_value(meta).context("serialize artifact meta")?;- doc["created_ms"] = Value::from(meta.created_at.timestamp_millis());- let id = meta.id.clone();+ let doc = meta_to_body(meta).context("serialize artifact meta")?;+ let id = key_of(&meta.id)?;self.0.run(|docs| async move { put_absent(&docs, ARTIFACTS, &id, doc).await })}/// The arguments' counterpart of [`Self::put_meta_if_absent`].fn put_args_if_absent(&self, id: &str, args: &Value) -> Result<bool> {- let id = id.to_string();- let doc = json!({ "args": args });+ let id = key_of(id)?;+ let doc = args_body(args);self.0.run(|docs| async move { put_absent(&docs, ARGS, &id, doc).await })}pub(super) fn get_meta(&self, id: &str) -> Result<Option<ArtifactMeta>> {- let id = id.to_string();+ let id = key_of(id)?;let stored = self.0.run(|docs| async move { docs.get(ARTIFACTS, &id).await })?;@@ -146,7 +144,7 @@ impl Docs {.run(|docs| async move { docs.query_all(ARTIFACTS, &query).await })?;Ok(stored.into_iter()- .filter_map(|item| match serde_json::from_value(item.doc) {+ .filter_map(|item| match meta_from_body(item.doc) {Ok(meta) => Some(meta),Err(error) => {log::warn!(@@ -160,8 +158,8 @@ impl Docs {}pub(super) fn put_args(&self, id: &str, args: &Value) -> Result<()> {- let id = id.to_string();- let doc = json!({ "args": args });+ let id = key_of(id)?;+ let doc = args_body(args);self.0.run(|docs| async move {docs.put(ARGS, &id, doc, Precondition::None).await@@ -170,11 +168,11 @@ impl Docs {}pub(super) fn get_args(&self, id: &str) -> Result<Option<Value>> {- let id = id.to_string();+ let id = key_of(id)?;let stored = self.0.run(|docs| async move { docs.get(ARGS, &id).await })?;- Ok(stored.and_then(|stored| stored.doc.get("args").cloned()))+ Ok(stored.map(|stored| args_of_body(&stored.doc)))}/// Removes the record and its arguments; `false` when there was no record.@@ -182,7 +180,7 @@ impl Docs {/// finds no record and only an orphaned arguments document is left, never/// a listed artifact that lost its regenerate arguments.pub(super) fn delete(&self, id: &str) -> Result<bool> {- let id = id.to_string();+ let id = key_of(id)?;self.0.run(|docs| async move {let existed = docs.delete(ARTIFACTS, &id, Precondition::None).await?;docs.delete(ARGS, &id, Precondition::None).await?;diff --git a/crates/openhuman-core/src/agent/artifacts/version_documents.rs b/crates/openhuman-core/src/agent/artifacts/version_documents.rsindex 93afb9efde..642f003033 100644--- a/crates/openhuman-core/src/agent/artifacts/version_documents.rs+++ b/crates/openhuman-core/src/agent/artifacts/version_documents.rs@@ -9,7 +9,7 @@//!//! | Collection | Document id | Holds |//! | --- | --- | --- |-//! | `artifact_versions` | artifact id | the whole `ArtifactRecord`, plus `updated_ms` for ordering |+//! | `artifacts.versions` | `Key::of([artifact id])` | the whole `ArtifactRecord` with snake_case keys and `*_ms` times ([`super::storage_schema`]) |//!//! Only the records move. A file version's bytes stay in a file//! (`ArtifactVersion::file`), as the legacy card's do.@@ -28,10 +28,11 @@ use serde_json::Value;use tiny_artifacts::{ArtifactRecord, ArtifactStore};use tinystoragedrivers::{CollectionSpec, Precondition, Query, Sort};+use super::storage_schema::{version_body, version_record, VERSIONS};use crate::storage::documents::Repo;+use crate::storage::schema_support::key_of;use crate::storage::DocumentStoreExt;-const VERSIONS: &str = "artifact_versions";const DOMAIN: &str = "artifacts::versions";fn collections() -> Vec<CollectionSpec> {@@ -106,7 +107,7 @@ impl ArtifactStore for DocumentArtifactStore {async fn get(&self, id: &str) -> Result<Option<ArtifactRecord>> {let repo = self.repo().await?;- let id = id.to_string();+ let id = key_of(id)?;let stored = on_blocking(repo, move |repo| {repo.run(|docs| async move { docs.get(VERSIONS, &id).await })})@@ -116,7 +117,7 @@ impl ArtifactStore for DocumentArtifactStore {async fn upsert(&self, artifact: &ArtifactRecord) -> Result<()> {let repo = self.repo().await?;- let id = artifact.id.clone();+ let id = key_of(&artifact.id)?;let doc = doc_of(artifact)?;on_blocking(repo, move |repo| {repo.run(|docs| async move {@@ -142,7 +143,7 @@ impl ArtifactStore for DocumentArtifactStore {}}let repo = self.repo().await?;- let id = id.to_string();+ let id = key_of(id)?;on_blocking(repo, move |repo| {repo.run(|docs| async move { docs.delete(VERSIONS, &id, Precondition::None).await })})@@ -151,16 +152,13 @@ impl ArtifactStore for DocumentArtifactStore {}fn doc_of(record: &ArtifactRecord) -> Result<Value> {- let mut doc = serde_json::to_value(record).context("serialize artifact record")?;- doc["updated_ms"] = Value::from(record.updated_at_millis);- Ok(doc)+ Ok(version_body(+ &serde_json::to_value(record).context("serialize artifact record")?,+ ))}-fn record_of(mut doc: Value) -> Result<ArtifactRecord> {- if let Some(fields) = doc.as_object_mut() {- fields.remove("updated_ms");- }- serde_json::from_value(doc).context("parse artifact record")+fn record_of(doc: Value) -> Result<ArtifactRecord> {+ serde_json::from_value(version_record(&doc)).context("parse artifact record")}/// Imports the legacy `<id>.json` records in `dir` that the store does not@@ -196,7 +194,7 @@ fn import_legacy(repo: &Repo, dir: &Path) -> Result<usize> {if path.file_stem().and_then(|s| s.to_str()) != Some(record.id.as_str()) {continue;}- let id = record.id.clone();+ let id = key_of(&record.id)?;let doc = doc_of(&record)?;let created = repo.run(|docs| async move {match docs.put(VERSIONS, &id, doc, Precondition::Absent).await {