Skip to content

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

feat(modules): add tinyjuice storage import with savings tracking

Steven Enamakel2c0ca9aee22b
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index 27cd8ffd72..9cc11f6cd0 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -107,6 +107,7 @@ mod storage_import_tinybox;
mod storage_import_tinyconnectors;
#[cfg(feature = "modules")]
mod storage_import_tinyjuice;
+mod storage_import_tinyjuice_savings;
#[cfg(feature = "modules")]
mod storage_import_tinymcp;
#[cfg(all(feature = "modules", feature = "web3"))]
@@ -203,6 +204,12 @@ settled_outcome!(
storage_import_tinybox,
storage_import_tinyjuice
);
+#[cfg(feature = "modules")]
+impl Settled for storage_import_tinyjuice_savings::Outcome {
+ fn settled(&self) -> bool {
+ matches!(self, Self::AlreadyDone | Self::Imported { .. })
+ }
+}
#[cfg(all(feature = "modules", feature = "web3"))]
settled_outcome!(storage_import_tinywallet);
@@ -397,6 +404,39 @@ pub async fn import_legacy_tinyjuice(
let _ = (ctx, root, ttl);
}
+/// Hands the legacy `state/tokenjuice_savings.json` under `workspace_dir` to
+/// the tinyjuice module (`ImportSavings`), once per file. Never fails the
+/// caller: an error is logged and the import is retried at the next install.
+pub async fn import_legacy_tinyjuice_savings(
+ ctx: &crate::core::runtime::DispatchCtx,
+ client: &tinybus::module::ModuleClient,
+ workspace_dir: &std::path::Path,
+) {
+ #[cfg(feature = "modules")]
+ {
+ let file = storage_import_tinyjuice_savings::legacy_file(workspace_dir);
+ import_once(
+ ctx,
+ "tinyjuice-savings",
+ storage_grant_schemas::tinyjuice::MODULE_ID,
+ &file,
+ storage_import_tinyjuice_savings::import_legacy(ctx, &file, |aggregate| async move {
+ client
+ .call::<bool>(
+ "tinyjuice",
+ tinyjuice_bus::names::methods::IMPORT_SAVINGS,
+ (aggregate,),
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("ImportSavings: {e}"))
+ }),
+ )
+ .await;
+ }
+ #[cfg(not(feature = "modules"))]
+ let _ = (ctx, client, workspace_dir);
+}
+
#[cfg(all(test, feature = "modules"))]
#[path = "import_once_tests.rs"]
mod import_once_tests;
diff --git a/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs b/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
index 4f974bcd10..d920bc47fe 100644
--- a/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
+++ b/crates/openhuman-core/src/modules/storage_import_tinyjuice.rs
@@ -151,7 +151,7 @@ fn is_token(name: &str) -> bool {
/// The modified time and bytes of a regular file, or `None` for a link,
/// directory or anything else; the file is never reached through a symlink.
-fn read_regular(path: &Path) -> Result<Option<(SystemTime, Vec<u8>)>> {
+pub(super) fn read_regular(path: &Path) -> Result<Option<(SystemTime, Vec<u8>)>> {
use std::io::Read;
let mut options = std::fs::File::options();
options.read(true);
diff --git a/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rs b/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rs
new file mode 100644
index 0000000000..1b64cc4cdb
--- /dev/null
+++ b/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings.rs
@@ -0,0 +1,107 @@
+//! One-time import of tinyjuice's legacy savings snapshot.
+//!
+//! The savings totals used to live in `<workspace>/state/tokenjuice_savings.json`
+//! (a camelCase `SavingsAggregate`). The module now keeps them as one document
+//! in its own `juice.savings` collection, so the host reads the old file and
+//! hands the aggregate to the module (`ImportSavings`), which adopts it only
+//! while it has recorded nothing.
+//!
+//! * **The file is only read.** It is never modified or deleted here; the
+//! layout migration archives it with the rest of `state/` (classified `Move`,
+//! "runtime state files", in `storage/layout/plan.rs`).
+//! * **The path is fixed.** It is `state/tokenjuice_savings.json` under the
+//! workspace, read without following a symlink and capped in size; nothing
+//! in the file can name another path.
+//! * **Runs once per file.** A marker in `tsd.migrations` records it. A
+//! snapshot that does not parse is marked too (the old ledger ignored it as
+//! well), so a corrupt file is not retried forever. A failed hand-over writes
+//! no marker and is retried at the next install.
+
+use std::future::Future;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use tinyjuice_bus::savings::SavingsAggregate;
+use tinystoragedrivers::ScopedStorage;
+
+use super::storage_grant_tinyjuice::MODULE_ID;
+use super::storage_import_support as support;
+use super::storage_import_tinyjuice::read_regular;
+use crate::core::runtime::DispatchCtx;
+
+const LOG_PREFIX: &str = "[tinyjuice-savings-import]";
+/// Marker collection name, shared with the CCR importer's host-only family.
+const MARKER_KIND: &str = "tinyjuice_host_import";
+/// A real snapshot is a few KiB; anything past this is not one.
+const MAX_BYTES: usize = 4 * 1024 * 1024;
+
+/// The legacy snapshot's location under `workspace`.
+pub(crate) fn legacy_file(workspace: &Path) -> PathBuf {
+ workspace.join("state").join("tokenjuice_savings.json")
+}
+
+/// How one import attempt ended.
+#[derive(Debug, PartialEq, Eq)]
+pub(crate) enum Outcome {
+ /// No storage backend is installed; the module is not using this storage.
+ NoBackend,
+ /// The marker says this file was already imported.
+ AlreadyDone,
+ /// There is no snapshot file.
+ NoSource,
+ /// The file was handled; `adopted` is whether the module took its totals.
+ Imported { adopted: bool },
+}
+
+/// Hands the snapshot at `file` to the module through `adopt`.
+pub(crate) async fn import_legacy<F, Fut>(
+ ctx: &DispatchCtx,
+ file: &Path,
+ adopt: F,
+) -> Result<Outcome>
+where
+ F: FnOnce(SavingsAggregate) -> Fut,
+ Fut: Future<Output = Result<bool>>,
+{
+ let Some(scoped) = support::module_scope(ctx, MODULE_ID)? else {
+ return Ok(Outcome::NoBackend);
+ };
+ import_into(&scoped, file, adopt).await
+}
+
+async fn import_into<F, Fut>(scoped: &ScopedStorage, file: &Path, adopt: F) -> Result<Outcome>
+where
+ F: FnOnce(SavingsAggregate) -> Fut,
+ Fut: Future<Output = Result<bool>>,
+{
+ let marker = support::marker_id("savings", file);
+ if support::already_imported(scoped, MARKER_KIND, &marker).await? {
+ return Ok(Outcome::AlreadyDone);
+ }
+ let path = file.to_owned();
+ let bytes = tokio::task::spawn_blocking(move || read_regular(&path))
+ .await
+ .context("the legacy reader panicked")??;
+ let Some((_, bytes)) = bytes else {
+ return Ok(Outcome::NoSource);
+ };
+ let parsed = if bytes.len() > MAX_BYTES {
+ None
+ } else {
+ serde_json::from_slice::<SavingsAggregate>(&bytes).ok()
+ };
+ let adopted = match parsed {
+ Some(aggregate) => adopt(aggregate).await?,
+ None => {
+ log::warn!("{LOG_PREFIX} snapshot unreadable or too large, skipped");
+ false
+ }
+ };
+ support::mark_imported(scoped, MARKER_KIND, &marker).await?;
+ log::debug!("{LOG_PREFIX} adopted={adopted}");
+ Ok(Outcome::Imported { adopted })
+}
+
+#[cfg(test)]
+#[path = "storage_import_tinyjuice_savings_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings_tests.rs b/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings_tests.rs
new file mode 100644
index 0000000000..1233486861
--- /dev/null
+++ b/crates/openhuman-core/src/modules/storage_import_tinyjuice_savings_tests.rs
@@ -0,0 +1,125 @@
+use super::*;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use tinystoragedrivers::{MemoryStorage, Scope, StorageBackend};
+
+const SNAPSHOT: &str = r#"{
+ "total":{"events":2,"originalTokens":4000,"compactedTokens":2000,"tokensSaved":2000,"costSavedUsd":0.006},
+ "byModel":{"m":{"events":2,"originalTokens":4000,"compactedTokens":2000,"tokensSaved":2000,"costSavedUsd":0.006}},
+ "byCompressor":{"smartcrusher":{"events":2,"originalTokens":4000,"compactedTokens":2000,"tokensSaved":2000,"costSavedUsd":0.006}}
+}"#;
+
+fn scoped() -> ScopedStorage {
+ MemoryStorage::new()
+ .for_scope(&Scope::new("module:tinyjuice@local").unwrap())
+ .unwrap()
+}
+
+fn workspace_with(snapshot: Option<&str>) -> tempfile::TempDir {
+ let dir = tempfile::tempdir().unwrap();
+ if let Some(text) = snapshot {
+ std::fs::create_dir_all(dir.path().join("state")).unwrap();
+ std::fs::write(legacy_file(dir.path()), text).unwrap();
+ }
+ dir
+}
+
+#[tokio::test]
+async fn the_legacy_snapshot_is_handed_to_the_module_once_and_left_in_place() {
+ let ws = workspace_with(Some(SNAPSHOT));
+ let file = legacy_file(ws.path());
+ let scoped = scoped();
+ let calls = AtomicUsize::new(0);
+ let got = std::sync::Mutex::new(None);
+ let outcome = import_into(&scoped, &file, |aggregate| {
+ calls.fetch_add(1, Ordering::SeqCst);
+ *got.lock().unwrap() = Some(aggregate);
+ async { Ok(true) }
+ })
+ .await
+ .unwrap();
+ assert_eq!(outcome, Outcome::Imported { adopted: true });
+ let aggregate = got.lock().unwrap().take().unwrap();
+ assert_eq!(aggregate.total.tokens_saved, 2000);
+ assert_eq!(aggregate.by_model["m"].events, 2);
+ assert!(file.exists(), "the importer never deletes the legacy file");
+
+ let again = import_into(&scoped, &file, |_| async { Ok(true) })
+ .await
+ .unwrap();
+ assert_eq!(again, Outcome::AlreadyDone);
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn a_missing_snapshot_is_no_source_and_writes_no_marker() {
+ let ws = workspace_with(None);
+ let file = legacy_file(ws.path());
+ let scoped = scoped();
+ let outcome = import_into(&scoped, &file, |_| async { Ok(true) })
+ .await
+ .unwrap();
+ assert_eq!(outcome, Outcome::NoSource);
+ std::fs::create_dir_all(ws.path().join("state")).unwrap();
+ std::fs::write(&file, SNAPSHOT).unwrap();
+ let later = import_into(&scoped, &file, |_| async { Ok(true) })
+ .await
+ .unwrap();
+ assert_eq!(later, Outcome::Imported { adopted: true });
+}
+
+#[tokio::test]
+async fn a_corrupt_snapshot_is_skipped_and_not_retried() {
+ let ws = workspace_with(Some("{not json"));
+ let file = legacy_file(ws.path());
+ let scoped = scoped();
+ let outcome = import_into(&scoped, &file, |_| async {
+ panic!("a corrupt snapshot must not reach the module");
+ #[allow(unreachable_code)]
+ Ok(true)
+ })
+ .await
+ .unwrap();
+ assert_eq!(outcome, Outcome::Imported { adopted: false });
+ let again = import_into(&scoped, &file, |_| async { Ok(true) })
+ .await
+ .unwrap();
+ assert_eq!(again, Outcome::AlreadyDone);
+}
+
+#[tokio::test]
+async fn a_failed_hand_over_leaves_no_marker_so_the_next_start_retries() {
+ let ws = workspace_with(Some(SNAPSHOT));
+ let file = legacy_file(ws.path());
+ let scoped = scoped();
+ let failed = import_into(&scoped, &file, |_| async { Err(anyhow::anyhow!("bus down")) }).await;
+ assert!(failed.is_err());
+ let retry = import_into(&scoped, &file, |_| async { Ok(false) })
+ .await
+ .unwrap();
+ assert_eq!(retry, Outcome::Imported { adopted: false });
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn a_symlinked_snapshot_is_not_followed() {
+ let ws = workspace_with(None);
+ let secret = ws.path().join("elsewhere.json");
+ std::fs::write(&secret, SNAPSHOT).unwrap();
+ std::fs::create_dir_all(ws.path().join("state")).unwrap();
+ let file = legacy_file(ws.path());
+ std::os::unix::fs::symlink(&secret, &file).unwrap();
+ let outcome = import_into(&scoped(), &file, |_| async {
+ panic!("a symlink must not be read");
+ #[allow(unreachable_code)]
+ Ok(true)
+ })
+ .await
+ .unwrap();
+ assert_eq!(outcome, Outcome::NoSource);
+}
+
+#[test]
+fn the_legacy_path_is_fixed_under_the_workspace_state_dir() {
+ let path = legacy_file(Path::new("/w"));
+ assert_eq!(path, Path::new("/w/state/tokenjuice_savings.json"));
+}