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 lease document storage
Steven Enamakela5de9683a121
diff --git a/crates/openhuman-core/src/storage/lease.rs b/crates/openhuman-core/src/storage/lease.rsindex 0c1508a0d8..09def54fc4 100644--- a/crates/openhuman-core/src/storage/lease.rs+++ b/crates/openhuman-core/src/storage/lease.rs@@ -21,7 +21,13 @@//! Otherwise it fails with [`LeaseError::Held`] carrying the live record.//! A fresh key starts at epoch 1; every acquisition other than a//! re-entrant one (this same store instance already holds that epoch)-//! writes `epoch + 1`, so epochs only grow and fence stale holders.+//! writes `epoch + 1`, so epochs only grow. An expired takeover does not+//! stop the previous holder: resources a lease protects must reject writes+//! carrying an epoch below the current one, and a holder must stop work+//! before `expires_at_ms` minus the maximum clock skew between nodes (each+//! node supplies its own `now_ms`). Nothing in this module checks epochs at+//! the protected resource. An epoch at `u64::MAX` cannot be advanced, so a+//! takeover of it fails with a storage error instead of repeating it.//! - **renew** extends a grant by compare-and-swap on the version it holds.//! Any write since (a takeover, a release) makes it [`LeaseError::Lost`].//! - **release** marks the record `released = true` under the same CAS and@@ -198,6 +204,8 @@ pub(crate) enum Takeover {Take { epoch: u64, unclean: bool },/// Someone else's live record stands.Refuse,+ /// The record's epoch cannot be advanced.+ Exhausted,}/// The acquire rule both stores share. `held_epoch` is the epoch this store@@ -214,7 +222,19 @@ pub(crate) fn decide(unclean: false,};};- let next = record.epoch.saturating_add(1);+ let live_reentrant = record.owner == node+ && held_epoch == Some(record.epoch)+ && !record.released+ && now_ms < record.expires_at_ms;+ if live_reentrant {+ return Takeover::Take {+ epoch: record.epoch,+ unclean: false,+ };+ }+ let Some(next) = record.epoch.checked_add(1) else {+ return Takeover::Exhausted;+ };if record.released {return Takeover::Take {epoch: next,@@ -222,12 +242,6 @@ pub(crate) fn decide(};}if record.owner == node {- if held_epoch == Some(record.epoch) {- return Takeover::Take {- epoch: record.epoch,- unclean: false,- };- }return Takeover::Take {epoch: next,unclean: true,@@ -243,8 +257,13 @@ pub(crate) fn decide(}/// The directory a [`LocalLeases`] keeps `key`'s lock and record in.+///+/// The directory name is the SHA-256 of the key, so keys that differ only by+/// case, trailing dots or reserved device names never alias on+/// case-insensitive or Windows filesystems.pub(crate) fn local_dir(root: &std::path::Path, key: &str) -> PathBuf {- root.join(key)+ use sha2::{Digest, Sha256};+ root.join(hex::encode(Sha256::digest(key.as_bytes())))}#[cfg(test)]diff --git a/crates/openhuman-core/src/storage/lease_documents.rs b/crates/openhuman-core/src/storage/lease_documents.rsindex 7c1f32d0e7..5118e79a66 100644--- a/crates/openhuman-core/src/storage/lease_documents.rs+++ b/crates/openhuman-core/src/storage/lease_documents.rs@@ -61,7 +61,9 @@ impl DocumentLeases {docs,node: node.into(),endpoint,- ttl_ms: u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX),+ // A sub-millisecond TTL rounds up so a grant never expires at+ // the instant it is issued.+ ttl_ms: u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1),held: Mutex::new(HashMap::new()),declared: tokio::sync::OnceCell::new(),}@@ -122,6 +124,18 @@ impl DocumentLeases {};}+ /// Drops the held entry only while it still names `epoch`, so a release+ /// finishing late cannot erase a newer acquisition's state.+ fn clear_held_if(&self, key: &str, epoch: u64) {+ let mut held = self+ .held+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if held.get(key) == Some(&epoch) {+ held.remove(key);+ }+ }+fn record(&self, epoch: u64, expires_at_ms: u64, released: bool) -> LeaseRecord {LeaseRecord {owner: self.node.clone(),@@ -163,6 +177,16 @@ impl DocumentLeases {released: bool,) -> Result<Version, LeaseError> {validate_key(&grant.key)?;+ if self.held_epoch(&grant.key) != Some(grant.epoch) {+ tracing::info!(+ target: "openhuman::storage::lease",+ key = %grant.key,+ node = %self.node,+ epoch = grant.epoch,+ "[lease] grant lost: not held by this instance"+ );+ return Err(LeaseError::Lost);+ }self.declare().await?;let record = self.record(grant.epoch, expires_at_ms, released);match self@@ -202,6 +226,12 @@ impl LeaseStore for DocumentLeases {now_ms,) {Takeover::Take { epoch, unclean } => (epoch, unclean),+ Takeover::Exhausted => {+ return Err(StorageError::conflict(format!(+ "lease {key} epoch space exhausted"+ ))+ .into());+ }Takeover::Refuse => {let (_, record) = found.expect("refuse implies a record");tracing::debug!(@@ -257,6 +287,16 @@ impl LeaseStore for DocumentLeases {}async fn renew(&self, grant: &LeaseGrant, now_ms: u64) -> Result<LeaseGrant, LeaseError> {+ if now_ms >= grant.expires_at_ms {+ tracing::info!(+ target: "openhuman::storage::lease",+ key = %grant.key,+ node = %self.node,+ epoch = grant.epoch,+ "[lease] renew refused: grant already expired"+ );+ return Err(LeaseError::Lost);+ }let expires_at_ms = now_ms.saturating_add(self.ttl_ms);let version = self.rewrite(grant, expires_at_ms, false).await?;tracing::trace!(@@ -275,7 +315,7 @@ impl LeaseStore for DocumentLeases {async fn release(&self, grant: LeaseGrant) -> Result<(), LeaseError> {self.rewrite(&grant, grant.expires_at_ms, true).await?;- self.set_held(&grant.key, None);+ self.clear_held_if(&grant.key, grant.epoch);tracing::debug!(target: "openhuman::storage::lease",key = %grant.key,diff --git a/crates/openhuman-core/src/storage/lease_documents_tests.rs b/crates/openhuman-core/src/storage/lease_documents_tests.rsindex 7dab21ebea..5dc38be358 100644--- a/crates/openhuman-core/src/storage/lease_documents_tests.rs+++ b/crates/openhuman-core/src/storage/lease_documents_tests.rs@@ -1,6 +1,6 @@-use std::time::Duration;-use super::*;++use std::time::Duration;use crate::storage::MemoryStorage;const TTL: Duration = Duration::from_millis(1_000);diff --git a/crates/openhuman-core/src/storage/lease_local.rs b/crates/openhuman-core/src/storage/lease_local.rsindex 645578b13f..3e44cb1726 100644--- a/crates/openhuman-core/src/storage/lease_local.rs+++ b/crates/openhuman-core/src/storage/lease_local.rs@@ -183,7 +183,19 @@ impl LeaseStore for LocalLeases {}let previous = self.read_record(key);let unclean = previous.as_ref().is_some_and(|record| !record.released);- let epoch = previous.map_or(1, |record| record.epoch.saturating_add(1));+ let epoch = match previous {+ None => 1,+ Some(record) => match record.epoch.checked_add(1) {+ Some(next) => next,+ None => {+ let _ = FileExt::unlock(&file);+ return Err(StorageError::conflict(format!(+ "lease {key} epoch space exhausted"+ ))+ .into());+ }+ },+ };let record = LeaseRecord {owner: self.node.clone(),endpoint: None,