Skip to content

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

fix(storage): reopen deleted stores and surface import failures

Steven Enamakel6111aa12cc09
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import.rs b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
index 0fb9692265..25e11c4754 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store_import.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
@@ -69,11 +69,14 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
if let Some(payload) = row.get::<_, Option<String>>(4)? {
doc.insert("payload".into(), json!(payload));
}
- doc.insert(
- "ingested_ms".into(),
- json!(DateTime::parse_from_rfc3339(&ingested_at)
- .map_or(0, |at| at.timestamp_millis())),
- );
+ let ingested = DateTime::parse_from_rfc3339(&ingested_at).map_err(|error| {
+ rusqlite::Error::FromSqlConversionFailure(
+ 5,
+ rusqlite::types::Type::Text,
+ Box::new(error),
+ )
+ })?;
+ doc.insert("ingested_ms".into(), json!(ingested.timestamp_millis()));
doc.insert("ingested_at".into(), json!(ingested_at));
Ok(ImportDoc {
collection: INGESTED,
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs b/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs
index f57b2ef682..b03a8ce4e1 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store_import_tests.rs
@@ -121,24 +121,35 @@ fn legacy_sources_and_ledger_are_imported_once_through_the_public_api() {
}
#[test]
-fn the_classic_opt_out_still_works_after_an_import() {
+fn switching_between_classic_and_default_keeps_working() {
let (_dir, classic, default) = workspace();
- live::add_source(
- &classic,
- ProviderSlug::Github,
- None,
- None,
- filter(),
- 600,
- SourceTarget::AgentTodoProactive,
- 10,
- )
- .unwrap();
+ let add = |config: &Config, interval: u64| {
+ live::add_source(
+ config,
+ ProviderSlug::Github,
+ None,
+ None,
+ filter(),
+ interval,
+ SourceTarget::AgentTodoProactive,
+ 10,
+ )
+ .unwrap()
+ };
+ add(&classic, 600);
assert_eq!(live::list_sources(&default).unwrap().len(), 1);
- // The retired tables are gone from the legacy name; the legacy store
- // starts again from a clean schema instead of trusting a stale version.
- forget(&live::db_path(&default));
+ // The tables were retired; a classic call starts a clean legacy schema
+ // (it does not trust a stale version stamp) ...
assert!(live::list_sources(&classic).unwrap().is_empty());
+ add(&classic, 900);
+ // ... and the next default call imports what it holds, on top of what the
+ // document tables already had.
+ assert_eq!(live::list_sources(&default).unwrap().len(), 2);
+}
+
+#[test]
+fn a_deleted_database_is_reopened_not_served_from_a_stale_handle() {
+ let (_dir, classic, default) = workspace();
live::add_source(
&classic,
ProviderSlug::Github,
@@ -150,6 +161,16 @@ fn the_classic_opt_out_still_works_after_an_import() {
10,
)
.unwrap();
+ assert_eq!(live::list_sources(&default).unwrap().len(), 1);
+ // A data reset removes the workspace while this process keeps running.
+ let db = live::db_path(&default);
+ for suffix in ["", "-wal", "-shm"] {
+ let mut file = db.clone().into_os_string();
+ file.push(suffix);
+ let _ = std::fs::remove_file(std::path::PathBuf::from(file));
+ }
+ assert!(live::list_sources(&default).unwrap().is_empty());
+ assert!(db.exists(), "the store was created again");
}
#[test]
@@ -176,9 +197,9 @@ fn an_undecodable_source_row_keeps_the_legacy_table_in_service() {
[],
)
.unwrap();
- // The import fails, so nothing is retired and the store serves the
- // legacy table (which cannot decode that row either).
- assert!(live::list_sources(&default).is_err());
+ // The import fails, so nothing is retired and the call reports it.
+ let error = live::list_sources(&default).unwrap_err();
+ assert!(format!("{error:#}").contains("importing the legacy tables failed"));
let tables = table_names(&db);
assert!(tables.contains(&"task_sources".to_string()));
assert!(!tables.contains(&"_legacy_task_sources".to_string()));
diff --git a/crates/openhuman-core/src/storage/local.rs b/crates/openhuman-core/src/storage/local.rs
index 70bfcd8a67..9f9ebc9762 100644
--- a/crates/openhuman-core/src/storage/local.rs
+++ b/crates/openhuman-core/src/storage/local.rs
@@ -102,9 +102,29 @@ impl Opened {
#[cfg(feature = "storage-sqlite")]
struct OpenedDb {
backend: Arc<dyn StorageBackend>,
+ /// The file the backend was opened on, so a deleted or replaced file (a
+ /// data reset in the same process) is noticed and reopened.
+ identity: Option<FileId>,
imported: bool,
}
+/// What names one file on disk, apart from its path.
+#[cfg(feature = "storage-sqlite")]
+type FileId = (u64, u64);
+
+#[cfg(all(feature = "storage-sqlite", unix))]
+fn file_id(path: &Path) -> Option<FileId> {
+ use std::os::unix::fs::MetadataExt;
+ let meta = std::fs::metadata(path).ok()?;
+ Some((meta.dev(), meta.ino()))
+}
+
+#[cfg(all(feature = "storage-sqlite", not(unix)))]
+fn file_id(path: &Path) -> Option<FileId> {
+ // No inode to compare: existence is the best available signal.
+ path.exists().then_some((0, 0))
+}
+
/// Databases opened by this process, by path.
#[cfg(feature = "storage-sqlite")]
static OPENED: LazyLock<Mutex<HashMap<PathBuf, OpenedDb>>> = LazyLock::new(Mutex::default);
@@ -132,7 +152,14 @@ pub fn open(
.with_context(|| format!("[{}] resolve the storage scope", plan.domain))?;
return Ok(Some(Opened { backend, scope }));
}
- if mode(config) != StorageMode::Default {
+ let selected = mode(config);
+ if selected != StorageMode::Default {
+ // A legacy call may recreate the old tables; the next default call
+ // must open and import afresh instead of trusting an earlier import.
+ #[cfg(feature = "storage-sqlite")]
+ if selected == StorageMode::Classic {
+ forget(db_path);
+ }
return Ok(None);
}
open_default(db_path, collections, plan)
@@ -176,6 +203,15 @@ 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);
+ // A file deleted or replaced since it was opened (a data reset in this
+ // process) is dropped, so its handle is released and the file is created
+ // and imported afresh.
+ if opened
+ .get(db_path)
+ .is_some_and(|entry| entry.identity != file_id(db_path))
+ {
+ opened.remove(db_path);
+ }
if !opened.contains_key(db_path) {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
@@ -186,15 +222,15 @@ fn open_default(
)
})?;
}
- 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 })
+ // Opened by path, not through a URL string, so a path that is not
+ // UTF-8 keeps naming the file the legacy tables are in.
+ let storage = tinystoragedrivers::sqlite::SqliteStorage::open(db_path)
.map_err(|error| anyhow!("[{}] open {}: {error}", plan.domain, db_path.display()))?;
opened.insert(
db_path.to_path_buf(),
OpenedDb {
- backend,
+ backend: Arc::new(storage),
+ identity: file_id(db_path),
imported: false,
},
);
@@ -207,30 +243,22 @@ fn open_default(
if entry.imported {
return Ok(Some(handle));
}
- match import(db_path, &handle, collections, plan) {
- Ok(count) => {
- tracing::debug!(
- domain = plan.domain,
- path = %db_path.display(),
- imported = count,
- "[storage::local] opened the default store"
- );
- 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)
- }
- }
+ let count = import(db_path, &handle, collections, plan).with_context(|| {
+ format!(
+ "[{}] importing the legacy tables failed; they are untouched and the import is \
+ retried on the next call (set storage url `{}` to keep using them as they are)",
+ plan.domain,
+ super::config::CLASSIC
+ )
+ })?;
+ tracing::debug!(
+ domain = plan.domain,
+ path = %db_path.display(),
+ imported = count,
+ "[storage::local] opened the default store"
+ );
+ entry.imported = true;
+ Ok(Some(handle))
}
/// Copies `plan`'s old rows into `handle` and retires the old tables.
@@ -287,8 +315,8 @@ fn import(
}
/// Forgets that `db_path` was opened, so the next call opens (and imports)
-/// it afresh: how a test models a restart.
-#[cfg(all(test, feature = "storage-sqlite"))]
+/// it afresh; also how a test models a restart.
+#[cfg(feature = "storage-sqlite")]
pub(crate) fn forget(db_path: &Path) {
OPENED
.lock()
@@ -339,8 +367,13 @@ fn retire_tables(db_path: &Path, tables: &[&str]) -> Result<()> {
let mut conn = Connection::open(db_path)
.with_context(|| format!("open {} to retire legacy tables", db_path.display()))?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
- let tx = conn.transaction()?;
+ // Immediate, and each table is checked inside it: another process on the
+ // same workspace may have retired it already.
+ let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
for table in tables {
+ if !table_exists(&tx, table)? {
+ continue;
+ }
let mut target = format!("_legacy_{table}");
let mut n = 1;
while table_exists(&tx, &target)? {
diff --git a/crates/openhuman-core/src/storage/local_tests.rs b/crates/openhuman-core/src/storage/local_tests.rs
index 8375477869..d36c4bb528 100644
--- a/crates/openhuman-core/src/storage/local_tests.rs
+++ b/crates/openhuman-core/src/storage/local_tests.rs
@@ -103,7 +103,7 @@ fn classic_and_the_empty_file_do_not_import() {
}
#[test]
-fn an_import_that_cannot_read_is_retried_not_remembered() {
+fn an_import_that_cannot_read_is_an_error_and_is_retried() {
let dir = TempDir::new().unwrap();
let path = legacy_file(&dir);
let fails = || -> Result<Vec<ImportDoc>> { Err(anyhow!("boom")) };
@@ -112,8 +112,10 @@ fn an_import_that_cannot_read_is_retried_not_remembered() {
tables: TABLES,
read: &fails,
};
- let opened = open(&config(None), &path, collections, &failing).unwrap();
- assert!(opened.is_none(), "the legacy tables keep serving");
+ let error = open(&config(None), &path, collections, &failing)
+ .err()
+ .expect("a failed import is reported, not hidden behind the legacy tables");
+ assert!(format!("{error:#}").contains("boom"), "{error:#}");
assert!(
table_names(&path).contains(&"old_things".to_string()),
"the old table is untouched"