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(storage): add task source import persistence
Steven Enamakel48fd7a3e026e
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex e717c3530c..510fddb953 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -195,6 +195,8 @@ path = "../../tests/cli_storage_url_e2e.rs"# Boots `openhuman-core serve` on a workspace with legacy approval rows.name = "storage_default_import_e2e"path = "../../tests/storage_default_import_e2e.rs"+# Without the SQLite driver the stores keep the legacy tables.+required-features = ["storage-sqlite"][[test]]name = "saas_mode_e2e"diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import.rs b/crates/openhuman-core/src/integrations/task_sources/store_import.rsindex e1b691c588..0fb9692265 100644--- a/crates/openhuman-core/src/integrations/task_sources/store_import.rs+++ b/crates/openhuman-core/src/integrations/task_sources/store_import.rs@@ -2,8 +2,8 @@//! (`store_documents.rs`): `task_sources` becomes one `task_sources` document//! per source (the store's own `to_doc`) and `ingested_tasks` one//! `ingested_tasks` document per dedup-ledger entry, with `ingested_ms`-//! derived from `ingested_at`. A source row that no longer decodes is logged-//! and left in the retired table instead of stopping the import. The driver+//! derived from `ingested_at`. A source row that no longer decodes fails the+//! import, leaving the legacy tables in service. The driver//! ([`crate::storage::local`]) writes the documents and then renames the//! tables to `_legacy_<name>`.@@ -37,16 +37,14 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {.query_map([], super::map_source_row).context("[task_sources::import] query task_sources")?;for row in rows {- match row {- Ok(source) => docs.push(ImportDoc {- collection: SOURCES,- id: source.id.clone(),- doc: to_doc(&source)?,- }),- Err(error) => tracing::warn!(- "[task_sources::import] skipping an undecodable source row: {error}"- ),- }+ // A row that does not decode fails the import, so the legacy+ // table is not retired with a source missing from the new one.+ let source = row.context("[task_sources::import] decode a task_sources row")?;+ docs.push(ImportDoc {+ collection: SOURCES,+ id: source.id.clone(),+ doc: to_doc(&source)?,+ });}}if table_exists(conn, "ingested_tasks")? {diff --git a/crates/openhuman-core/src/storage/local.rs b/crates/openhuman-core/src/storage/local.rsindex b1aa47d2eb..70bfcd8a67 100644--- a/crates/openhuman-core/src/storage/local.rs+++ b/crates/openhuman-core/src/storage/local.rs@@ -176,29 +176,37 @@ fn open_default() -> Result<Option<Opened>> {// Held across the import so two threads never both import one file.let mut opened = OPENED.lock().unwrap_or_else(PoisonError::into_inner);- if let Some(backend) = opened.get(db_path) {- return Ok(Some(Opened {- backend: Arc::clone(backend),- scope: Scope::local(),- }));- }- if let Some(parent) = db_path.parent() {- std::fs::create_dir_all(parent).with_context(|| {- format!(- "[{}] create the directory {}",- plan.domain,- parent.display()- )- })?;+ if !opened.contains_key(db_path) {+ if let Some(parent) = db_path.parent() {+ std::fs::create_dir_all(parent).with_context(|| {+ format!(+ "[{}] create the directory {}",+ plan.domain,+ parent.display()+ )+ })?;+ }+ let url =+ tinystoragedrivers::StorageConfig::parse(&format!("sqlite:{}", db_path.display()))+ .map_err(|error| anyhow!("[{}] storage url: {error}", plan.domain))?;+ let backend = super::block_on(async move { tinystoragedrivers::open(&url).await })+ .map_err(|error| anyhow!("[{}] open {}: {error}", plan.domain, db_path.display()))?;+ opened.insert(+ db_path.to_path_buf(),+ OpenedDb {+ backend,+ imported: false,+ },+ );}- let url = tinystoragedrivers::StorageConfig::parse(&format!("sqlite:{}", db_path.display()))- .map_err(|error| anyhow!("[{}] storage url: {error}", plan.domain))?;- let backend = super::block_on(async move { tinystoragedrivers::open(&url).await })- .map_err(|error| anyhow!("[{}] open {}: {error}", plan.domain, db_path.display()))?;+ let entry = opened.get_mut(db_path).expect("inserted above");let handle = Opened {- backend,+ backend: Arc::clone(&entry.backend),scope: Scope::local(),};+ if entry.imported {+ return Ok(Some(handle));+ }match import(db_path, &handle, collections, plan) {Ok(count) => {tracing::debug!(@@ -207,16 +215,22 @@ fn open_default(imported = count,"[storage::local] opened the default store");- opened.insert(db_path.to_path_buf(), Arc::clone(&handle.backend));+ entry.imported = true;+ Ok(Some(handle))+ }+ // The old tables are untouched (they are retired last), so the store+ // keeps serving them rather than showing an empty document store, and+ // the next call tries the import again.+ Err(error) => {+ tracing::error!(+ domain = plan.domain,+ path = %db_path.display(),+ "[storage::local] importing the legacy tables failed; \+ serving the legacy tables, will retry: {error:#}"+ );+ Ok(None)}- // Not remembered, so the next call retries; the import is resumable.- Err(error) => tracing::error!(- domain = plan.domain,- path = %db_path.display(),- "[storage::local] importing the legacy tables failed, will retry: {error:#}"- ),}- Ok(Some(handle))}/// Copies `plan`'s old rows into `handle` and retires the old tables.@@ -231,11 +245,14 @@ fn import(if !db_path.exists() {return Ok(0);}- let present = present_tables(db_path, plan.tables)?;- if present.is_empty() {+ if present_tables(db_path, plan.tables)?.is_empty() {return Ok(0);}let rows = (plan.read)().with_context(|| format!("[{}] read the legacy rows", plan.domain))?;+ // The reader brings an old schema forward, which can create tables that+ // were missing (empty); look again so every one is retired together and+ // none is left to trigger another import.+ let present = present_tables(db_path, plan.tables)?;let total = rows.len();let repo = Repo::on(&handle.backend, &handle.scope, plan.domain, collections)?;let written = repo.run(|docs| async move {@@ -333,6 +350,9 @@ fn retire_tables(db_path: &Path, tables: &[&str]) -> Result<()> {tx.execute_batch(&format!("ALTER TABLE \"{table}\" RENAME TO \"{target}\"")).with_context(|| format!("rename {table} to {target}"))?;}+ // The schema these tables belonged to is gone; a legacy open must not+ // trust a version stamp that says it is initialized.+ tx.pragma_update(None, "user_version", 0)?;tx.commit()?;Ok(())}diff --git a/crates/openhuman-core/src/storage/local_tests.rs b/crates/openhuman-core/src/storage/local_tests.rsindex 9eacbf5653..8375477869 100644--- a/crates/openhuman-core/src/storage/local_tests.rs+++ b/crates/openhuman-core/src/storage/local_tests.rs@@ -113,12 +113,12 @@ fn an_import_that_cannot_read_is_retried_not_remembered() {read: &fails,};let opened = open(&config(None), &path, collections, &failing).unwrap();- assert!(opened.is_some(), "the store stays usable");+ assert!(opened.is_none(), "the legacy tables keep serving");assert!(table_names(&path).contains(&"old_things".to_string()),"the old table is untouched");// The next call imports properly.- open_things(&config(None), &path).unwrap();+ assert!(open_things(&config(None), &path).is_some());assert!(table_names(&path).contains(&"_legacy_old_things".to_string()));}