Skip to content

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

feat(memory): add layout migration state tracking

Steven Enamakela17054846009
diff --git a/crates/openhuman-core/src/memory/layout_migration/state.rs b/crates/openhuman-core/src/memory/layout_migration/state.rs
index a534a5b2ee..c8e9c9421f 100644
--- a/crates/openhuman-core/src/memory/layout_migration/state.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/state.rs
@@ -1,7 +1,8 @@
-//! The migration's state on disk, `<workspace>/memory/layout_migration.json`.
+//! The migration's state, the `memory`/`state`/`layout_migration` storage
+//! value (once `<workspace>/memory/layout_migration.json`).
//!
-//! Written whole after every page, through a temporary file and a rename,
-//! so a crash leaves the previous state or the new one, never a torn file.
+//! Written whole after every page, so a crash leaves the previous state or
+//! the new one, never a torn value.
//! The state itself is `tinymemory_tools::layout_migration::MigrationState`.
use std::path::{Path, PathBuf};
@@ -11,10 +12,15 @@ use tinymemory_tools::layout_migration::{Error, Result};
use super::{MigrationState, MigrationStateStore};
use crate::memory::error::{MemoryError, MemoryResult};
-/// The state file of `workspace_dir`.
+const STATE: &str = "layout_migration";
+
+/// Whether a migration state exists in `workspace_dir`: the migration has
+/// begun there.
#[must_use]
-pub fn path(workspace_dir: &Path) -> PathBuf {
- workspace_dir.join("memory").join("layout_migration.json")
+pub fn exists(workspace_dir: &Path) -> bool {
+ crate::memory::state_store::load::<serde_json::Value>(workspace_dir, STATE)
+ .map(|state| state.is_some())
+ .unwrap_or(false)
}
/// The migration state kept in one workspace.
@@ -54,41 +60,26 @@ fn detail(error: MemoryError) -> String {
///
/// # Errors
///
-/// A state file that cannot be read or parsed: the migration must not start
-/// over and copy everything again on a damaged file.
+/// A state that cannot be read or parsed: the migration must not start
+/// over and copy everything again on a damaged value.
pub fn load(workspace_dir: &Path) -> MemoryResult<MigrationState> {
- let file = path(workspace_dir);
- match std::fs::read(&file) {
- Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| {
- MemoryError::Engine(format!("layout migration state unreadable: {error}"))
- }),
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(MigrationState::default()),
- Err(error) => Err(MemoryError::Engine(format!(
- "layout migration state unreadable: {error}"
- ))),
- }
+ crate::memory::state_store::load(workspace_dir, STATE)
+ .map(Option::unwrap_or_default)
+ .map_err(|error| {
+ MemoryError::Engine(format!("layout migration state unreadable: {error:#}"))
+ })
}
-/// Saves `state` whole: a temporary file, synced, then renamed over the old.
+/// Saves `state` whole (one storage write, so a crash leaves the previous
+/// state or the new one).
///
/// # Errors
///
-/// When the file cannot be written.
+/// When the state cannot be written.
pub fn save(workspace_dir: &Path, state: &MigrationState) -> MemoryResult<()> {
- let file = path(workspace_dir);
- let write = || -> std::io::Result<()> {
- if let Some(dir) = file.parent() {
- crate::memory::files::create_private_dir_all(dir)?;
- }
- let temp = file.with_extension("json.tmp");
- let bytes = serde_json::to_vec_pretty(state).map_err(std::io::Error::other)?;
- let mut out = crate::memory::files::create_private(&temp)?;
- std::io::Write::write_all(&mut out, &bytes)?;
- out.sync_all()?;
- std::fs::rename(&temp, &file)
- };
- write()
- .map_err(|error| MemoryError::Engine(format!("layout migration state not saved: {error}")))
+ crate::memory::state_store::save(workspace_dir, STATE, state).map_err(|error| {
+ MemoryError::Engine(format!("layout migration state not saved: {error:#}"))
+ })
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/memory/local_root.rs b/crates/openhuman-core/src/memory/local_root.rs
index f43725e0db..b3b1e4ae01 100644
--- a/crates/openhuman-core/src/memory/local_root.rs
+++ b/crates/openhuman-core/src/memory/local_root.rs
@@ -138,43 +138,33 @@ pub fn legacy_root(user_id: &str) -> String {
/// finished.
fn has_memory_under_legacy_root(config: &Config) -> bool {
super::scope::layout_is_v3(config)
- || super::layout_migration::state::path(&config.workspace_dir).exists()
+ || super::layout_migration::state::exists(&config.workspace_dir)
}
-fn read(file: &Path) -> std::io::Result<Option<LocalRoot>> {
- let text = match std::fs::read_to_string(file) {
- Ok(text) => text,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(error) => return Err(error),
- };
- let record: LocalRoot = serde_json::from_str(&text).map_err(std::io::Error::other)?;
+fn valid(record: &LocalRoot) -> std::io::Result<()> {
let id = record.root.strip_prefix(LOCAL_ROOT_PREFIX).unwrap_or("");
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_alphanumeric()) {
return Err(std::io::Error::other(
"the recorded local root is malformed",
));
}
- Ok(Some(record))
+ Ok(())
}
-/// Writes `record` to `file` unless one is already there, and returns the
-/// one that is: staged in a private temporary file, then hard-linked into
-/// place, which fails rather than replace another process's record.
-fn record_once(file: &Path, record: &LocalRoot) -> std::io::Result<LocalRoot> {
- let dir = file
- .parent()
- .ok_or_else(|| std::io::Error::other("the record has no directory"))?;
- super::files::create_private_dir_all(dir)?;
- let temp = tempfile::NamedTempFile::new_in(dir)?;
- serde_json::to_writer_pretty(temp.as_file(), record).map_err(std::io::Error::other)?;
- temp.as_file().sync_all()?;
- match std::fs::hard_link(temp.path(), file) {
- Ok(()) => Ok(record.clone()),
- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
- read(file)?.ok_or_else(|| std::io::Error::other("the local root record vanished"))
- }
- Err(error) => Err(error),
+fn read(workspace_dir: &Path) -> anyhow::Result<Option<LocalRoot>> {
+ let record: Option<LocalRoot> = super::state_store::load(workspace_dir, STATE)?;
+ if let Some(record) = &record {
+ valid(record)?;
}
+ Ok(record)
+}
+
+/// Writes `record` unless one is already stored, and returns the one that is:
+/// the insert fails rather than replace another process's record.
+fn record_once(workspace_dir: &Path, record: &LocalRoot) -> anyhow::Result<LocalRoot> {
+ let landed = super::state_store::record_once(workspace_dir, STATE, record)?;
+ valid(&landed)?;
+ Ok(landed)
}
#[cfg(test)]