Skip to content

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

feat(storage): add tinyflows import support

Steven Enamakelab0bbb3491f8
diff --git a/crates/openhuman-core/src/storage/import/mod.rs b/crates/openhuman-core/src/storage/import/mod.rs
index 1a134ef26c..8d8bd915c7 100644
--- a/crates/openhuman-core/src/storage/import/mod.rs
+++ b/crates/openhuman-core/src/storage/import/mod.rs
@@ -39,6 +39,7 @@
//! the libraries that own those formats; see the storage README.
mod snapshot;
+pub mod tinyflows;
use std::path::Path;
use std::sync::Arc;
@@ -158,7 +159,12 @@ pub async fn run(config: &Config) -> Vec<Report> {
return Vec::new();
}
let config = config.clone();
- let joined = tokio::task::spawn_blocking(move || run_with(&backend, &config, &sources())).await;
+ let joined = tokio::task::spawn_blocking(move || {
+ let mut reports = run_with(&backend, &config, &sources());
+ reports.extend(tinyflows::run_with(&backend, &config));
+ reports
+ })
+ .await;
match joined {
Ok(reports) => reports,
Err(error) => {
diff --git a/crates/openhuman-core/src/storage/import/tinyflows.rs b/crates/openhuman-core/src/storage/import/tinyflows.rs
new file mode 100644
index 0000000000..dadc1bfc88
--- /dev/null
+++ b/crates/openhuman-core/src/storage/import/tinyflows.rs
@@ -0,0 +1,291 @@
+//! The tinyflows stores: cron jobs (with their run history and policies), the
+//! flow catalog with its drafts, and the flow checkpoints.
+//!
+//! tinyflows used to own these as SQLite files and JSON drafts under the
+//! workspace (`cron/jobs.db`, `agents/<id>/cron/jobs.db`, `flows/flows.db`,
+//! `flows/drafts/*.json`, `flows/checkpoints.db`). It no longer has a storage
+//! backend of its own, so the host copies what those files hold into the
+//! port-backed stores with `tinyflows-import`, which keeps every record under
+//! the id it had, writes only what is absent, and reads copies of the files
+//! (the originals are never opened for writing).
+//!
+//! Each store has a marker like the small stores' (see the parent module), so
+//! it is copied once: a flow or job deleted afterwards is not resurrected from
+//! the untouched legacy file. A failed import leaves no marker and is retried.
+//!
+//! Where the records land:
+//!
+//! - the workspace's `cron/jobs.db` and `flows/` go to [`Scope::local`], the
+//! operator's scope;
+//! - an embedded agent's `agents/<id>/cron/jobs.db` goes to that agent's scope
+//! ([`crate::storage::scope_for_agent`]), the one its cron calls resolve to.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use anyhow::{anyhow, Context, Result};
+use serde_json::json;
+use tinystoragedrivers::{ErrorKind, Precondition};
+
+use super::{marker_id, marker_spec, Outcome, Report, MARKER_COLLECTION, MARKER_VERSION};
+use crate::config::Config;
+use crate::storage::documents::Repo;
+use crate::storage::{Scope, StorageBackend};
+
+/// The marker name of the flow catalog (flows, revisions, runs, state,
+/// suggestions, drafts) and checkpoints.
+pub const FLOWS_DOMAIN: &str = "flows";
+
+/// The marker name of the workspace's own cron store; an agent's is
+/// `cron/<agent id>`.
+pub const CRON_DOMAIN: &str = "cron";
+
+/// The legacy cron database under `scope_dir` (the workspace, or an agent's
+/// directory under it).
+pub fn legacy_jobs_db(scope_dir: &Path) -> PathBuf {
+ scope_dir.join("cron").join("jobs.db")
+}
+
+/// Runs `body` unless the marker for `domain` says it already finished, then
+/// records the marker. `body` returns `None` when there is nothing to import
+/// (no marker is written then, so a file that appears later is still seen) and
+/// otherwise `(found, written)`.
+fn marked(
+ backend: &Arc<dyn StorageBackend>,
+ workspace: &Path,
+ domain: &str,
+ body: impl FnOnce() -> Result<Option<(usize, usize)>>,
+) -> Result<Outcome> {
+ let marker = marker_id(domain, workspace);
+ let markers = Repo::on(backend, &Scope::local(), "storage::import", marker_spec)?;
+ let id = marker.clone();
+ let done = markers
+ .run(move |docs| async move { docs.get(MARKER_COLLECTION, &id).await })?
+ .is_some();
+ if done {
+ return Ok(Outcome::AlreadyDone);
+ }
+ let Some((found, written)) = body()? else {
+ return Ok(Outcome::NoSource);
+ };
+ let body = json!({
+ "version": MARKER_VERSION,
+ "domain": domain,
+ "found": found,
+ "written": written,
+ "at": chrono::Utc::now().to_rfc3339(),
+ });
+ markers.run(move |docs| async move {
+ match docs
+ .put(MARKER_COLLECTION, &marker, body, Precondition::Absent)
+ .await
+ {
+ Ok(_) => Ok(()),
+ // Another process finished first.
+ Err(error) if error.kind() == ErrorKind::Conflict => Ok(()),
+ Err(error) => Err(error),
+ }
+ })?;
+ Ok(Outcome::Imported { found, written })
+}
+
+/// `(found, written)` of a `tinyflows-import` report; problems are logged by
+/// id only, never with record content.
+#[cfg(feature = "flows")]
+fn counts(domain: &str, report: &tinyflows_import::ImportReport) -> (usize, usize) {
+ for problem in report.problems() {
+ tracing::warn!(
+ target: "openhuman::storage_import",
+ domain,
+ problem = %problem,
+ "[storage::import] a legacy record was skipped"
+ );
+ }
+ let found = report
+ .kinds()
+ .map(|(_, tally)| tally.written + tally.existing + tally.invalid)
+ .sum();
+ (found, report.total_written())
+}
+
+/// Copies the flow catalog and its checkpoints from `<workspace>/flows` into
+/// `backend` under `scope`.
+///
+/// # Errors
+///
+/// When a legacy file exists but cannot be read, or the backend fails. The
+/// legacy files are untouched either way.
+#[cfg(feature = "flows")]
+pub fn import_flows(
+ backend: &Arc<dyn StorageBackend>,
+ scope: &Scope,
+ config: &Config,
+) -> Result<Outcome> {
+ use tinyflows_drivers::{catalog::FlowCatalogDocuments, DriverCheckpointer};
+
+ let dir = config.workspace_dir.join("flows");
+ marked(backend, &config.workspace_dir, FLOWS_DOMAIN, || {
+ let present = ["flows.db", "checkpoints.db", "drafts"]
+ .iter()
+ .any(|name| dir.join(name).exists());
+ if !present {
+ return Ok(None);
+ }
+ let scoped = backend
+ .for_scope(scope)
+ .map_err(|error| anyhow!("open the storage scope: {error}"))?;
+ let docs = Arc::clone(scoped.documents());
+ let catalog = FlowCatalogDocuments::new(Arc::clone(&docs));
+ let checkpointer = DriverCheckpointer::<serde_json::Value>::new(docs);
+ let (catalog_report, checkpoint_report) = crate::storage::block_on_anyhow({
+ let dir = dir.clone();
+ async move {
+ let catalog_report = tinyflows_import::import_flow_catalog(&dir, &catalog)
+ .await
+ .context("import the flow catalog")?;
+ let checkpoint_report = tinyflows_import::import_sqlite_checkpoints(
+ &dir.join("checkpoints.db"),
+ &checkpointer,
+ )
+ .await
+ .context("import the flow checkpoints")?;
+ Ok((catalog_report, checkpoint_report))
+ }
+ })?;
+ let (found_a, written_a) = counts(FLOWS_DOMAIN, &catalog_report);
+ let (found_b, written_b) = counts(FLOWS_DOMAIN, &checkpoint_report);
+ Ok(Some((found_a + found_b, written_a + written_b)))
+ })
+}
+
+/// Copies the cron jobs, runs and policies of `scope_dir/cron/jobs.db` into
+/// `backend` under `scope`. `label` names the store in its marker: empty for
+/// the workspace's own, the agent id for an agent's.
+///
+/// # Errors
+///
+/// When the legacy file exists but cannot be read, or the backend fails. The
+/// legacy file is untouched either way.
+#[cfg(feature = "flows")]
+pub fn import_cron(
+ backend: &Arc<dyn StorageBackend>,
+ scope: &Scope,
+ config: &Config,
+ scope_dir: &Path,
+ label: &str,
+) -> Result<Outcome> {
+ use tinyflows_drivers::schedule::CronDocuments;
+
+ let domain = if label.is_empty() {
+ CRON_DOMAIN.to_string()
+ } else {
+ format!("{CRON_DOMAIN}/{label}")
+ };
+ let jobs_db = legacy_jobs_db(scope_dir);
+ marked(backend, &config.workspace_dir, &domain, || {
+ if !jobs_db.is_file() {
+ return Ok(None);
+ }
+ let scoped = backend
+ .for_scope(scope)
+ .map_err(|error| anyhow!("open the storage scope: {error}"))?;
+ let cron = CronDocuments::new(Arc::clone(scoped.documents()));
+ let report = crate::storage::block_on_anyhow({
+ let jobs_db = jobs_db.clone();
+ async move {
+ tinyflows_import::import_cron(&jobs_db, &cron)
+ .await
+ .context("import the cron jobs")
+ }
+ })?;
+ Ok(Some(counts(&domain, &report)))
+ })
+}
+
+/// Every agent directory under the workspace that kept its own cron database,
+/// as `(agent id, directory)`.
+fn agent_cron_dirs(workspace: &Path) -> Vec<(String, PathBuf)> {
+ let Ok(entries) = std::fs::read_dir(workspace.join("agents")) else {
+ return Vec::new();
+ };
+ let mut dirs: Vec<(String, PathBuf)> = entries
+ .filter_map(|entry| entry.ok())
+ .filter(|entry| legacy_jobs_db(&entry.path()).is_file())
+ .filter_map(|entry| Some((entry.file_name().into_string().ok()?, entry.path())))
+ .collect();
+ dirs.sort();
+ dirs
+}
+
+/// Imports every tinyflows legacy store of `config`'s workspace into
+/// `backend`: the flow catalog and checkpoints, the workspace's cron jobs and
+/// each agent's. One [`Report`] per store; a failure in one does not stop the
+/// rest.
+#[cfg(feature = "flows")]
+pub fn run_with(backend: &Arc<dyn StorageBackend>, config: &Config) -> Vec<Report> {
+ let mut reports = vec![finish(
+ FLOWS_DOMAIN,
+ import_flows(backend, &Scope::local(), config),
+ )];
+ reports.push(finish(
+ CRON_DOMAIN,
+ import_cron(backend, &Scope::local(), config, &config.workspace_dir, ""),
+ ));
+ for (agent, dir) in agent_cron_dirs(&config.workspace_dir) {
+ let scope = crate::storage::scope_for_agent(&agent);
+ reports.push(finish(
+ CRON_DOMAIN,
+ import_cron(backend, &scope, config, &dir, &agent),
+ ));
+ }
+ reports
+}
+
+/// Without `flows` there is no reader for the tinyflows formats; say so
+/// instead of silently dropping cron jobs.
+#[cfg(not(feature = "flows"))]
+pub fn run_with(_backend: &Arc<dyn StorageBackend>, config: &Config) -> Vec<Report> {
+ if legacy_jobs_db(&config.workspace_dir).is_file()
+ || !agent_cron_dirs(&config.workspace_dir).is_empty()
+ {
+ tracing::warn!(
+ target: "openhuman::storage_import",
+ "[storage::import] built without `flows`; the legacy cron databases are not imported"
+ );
+ }
+ Vec::new()
+}
+
+#[cfg(feature = "flows")]
+fn finish(domain: &'static str, outcome: Result<Outcome>) -> Report {
+ match &outcome {
+ Ok(Outcome::Imported { found, written }) => tracing::info!(
+ target: "openhuman::storage_import",
+ domain,
+ found,
+ written,
+ "[storage::import] imported the legacy store; the files were not modified"
+ ),
+ Ok(Outcome::AlreadyDone) => tracing::debug!(
+ target: "openhuman::storage_import",
+ domain,
+ "[storage::import] already imported"
+ ),
+ Ok(Outcome::NoSource) => tracing::debug!(
+ target: "openhuman::storage_import",
+ domain,
+ "[storage::import] no legacy file"
+ ),
+ Err(error) => tracing::error!(
+ target: "openhuman::storage_import",
+ domain,
+ error = %format!("{error:#}"),
+ "[storage::import] import failed; the legacy files are untouched and it is retried on the next boot"
+ ),
+ }
+ Report { domain, outcome }
+}
+
+#[cfg(test)]
+#[path = "tinyflows_tests.rs"]
+mod tests;