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
test(storage): cover driver-level fencing against lease takeover
Steven Enamakel7e4eda168562
diff --git a/crates/openhuman-core/src/storage/fenced_backend_tests.rs b/crates/openhuman-core/src/storage/fenced_backend_tests.rsindex 3d8ea4cb06..a22732c59d 100644--- a/crates/openhuman-core/src/storage/fenced_backend_tests.rs+++ b/crates/openhuman-core/src/storage/fenced_backend_tests.rs@@ -208,3 +208,216 @@ async fn a_fence_over_file_leases_admits_until_release() {Err(FenceError::Superseded { .. })));}++/// Node A's lease store, with the pause the host check cannot see: its next+/// record read returns what it read and *then* lets node B take the key+/// over, as if A were paused between its check and its write.+struct PausedAfterCheck {+ inner: Arc<dyn LeaseStore>,+ thief: Arc<dyn LeaseStore>,+ armed: std::sync::atomic::AtomicBool,+}++#[async_trait]+impl LeaseStore for PausedAfterCheck {+ async fn acquire(+ &self,+ key: &str,+ now_ms: u64,+ ) -> std::result::Result<LeaseGrant, crate::storage::lease::LeaseError> {+ self.inner.acquire(key, now_ms).await+ }++ async fn renew(+ &self,+ grant: &LeaseGrant,+ now_ms: u64,+ ) -> std::result::Result<LeaseGrant, crate::storage::lease::LeaseError> {+ self.inner.renew(grant, now_ms).await+ }++ async fn release(+ &self,+ grant: LeaseGrant,+ ) -> std::result::Result<(), crate::storage::lease::LeaseError> {+ self.inner.release(grant).await+ }++ async fn holder(+ &self,+ key: &str,+ ) -> std::result::Result<+ Option<crate::storage::lease::LeaseRecord>,+ crate::storage::lease::LeaseError,+ > {+ let record = self.inner.holder(key).await?;+ if self.armed.swap(false, Ordering::SeqCst) {+ let stolen = self.thief.acquire(key, TTL.as_millis() as u64 + 1).await?;+ assert_eq!(stolen.epoch, 2);+ }+ Ok(record)+ }++ fn record_scope(&self) -> Option<Scope> {+ self.inner.record_scope()+ }+}++/// Node A holds `alice` on `shared`; returns A's fenced view, its fence,+/// and the switch that makes its next check go stale.+async fn paused_holder(+ shared: &Arc<dyn StorageBackend>,+) -> (FencedBackend, Arc<LeaseFence>, Arc<PausedAfterCheck>) {+ let leases = Arc::new(PausedAfterCheck {+ inner: Arc::new(DocumentLeases::cluster(shared.as_ref(), "node-a", None, TTL).unwrap()),+ thief: Arc::new(DocumentLeases::cluster(shared.as_ref(), "node-b", None, TTL).unwrap()),+ armed: std::sync::atomic::AtomicBool::new(false),+ });+ let grant = leases.acquire("alice", 0).await.unwrap();+ let fences = Arc::new(FenceRegistry::new(|| 1_000));+ let fence = Arc::new(LeaseFence::new(+ Arc::clone(&leases) as Arc<dyn LeaseStore>,+ "alice",+ "node-a",+ grant.epoch,+ grant.expires_at_ms,+ MARGIN_MS,+ vec![ScopeMatch::Exact("profile:alice".into())],+ ));+ fences.register(Arc::clone(&fence));+ (+ FencedBackend::new(Arc::clone(shared), fences),+ fence,+ leases,+ )+}++/// The race the host check alone leaves open: A's check passes, A pauses,+/// B takes over, A's write lands. The driver re-reads the lease record in+/// the write's own atomic step and refuses it.+async fn driver_refuses_the_write_the_host_check_admitted(shared: Arc<dyn StorageBackend>) {+ assert!(shared.capabilities().contains(Capability::Fencing));+ let (a, fence, leases) = paused_holder(&shared).await;+ let scoped = a.for_scope(&Scope::new("profile:alice").unwrap()).unwrap();+ scoped+ .documents()+ .put("notes", "n1", json!({"v": 1}), Precondition::None)+ .await+ .unwrap();++ leases.armed.store(true, Ordering::SeqCst);+ let refused = scoped+ .documents()+ .put("notes", "n1", json!({"v": 2}), Precondition::None)+ .await+ .unwrap_err();+ assert!(+ matches!(+ fence_error(&refused),+ Some(FenceError::Superseded {+ held: 1,+ stored: Some(2)+ })+ ),+ "{refused:?}"+ );+ assert!(fence.is_fenced(), "a driver refusal latches the fence");+ let stored = shared+ .for_scope(&Scope::new("profile:alice").unwrap())+ .unwrap()+ .documents()+ .get("notes", "n1")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(stored.doc["v"], 1, "the late write did not land");+ // Latched: every later write is refused before it reaches the driver.+ assert!(scoped.streams().append("log", json!(1)).await.is_err());+}++#[tokio::test]+async fn memory_driver_refuses_a_write_after_a_takeover_the_check_missed() {+ driver_refuses_the_write_the_host_check_admitted(shared()).await;+}++#[cfg(feature = "storage-sqlite")]+#[tokio::test]+async fn sqlite_driver_refuses_a_write_after_a_takeover_the_check_missed() {+ let dir = tempfile::tempdir().unwrap();+ let url = format!("sqlite:{}", dir.path().join("fenced.db").display());+ let backend = tinystoragedrivers::open(&tinystoragedrivers::StorageConfig::parse(&url).unwrap())+ .await+ .unwrap();+ driver_refuses_the_write_the_host_check_admitted(backend).await;+}++/// Streams and blobs go through the driver fence too.+#[tokio::test]+async fn stream_and_blob_writes_are_driver_fenced() {+ let backend = shared();+ let (a, _fence, leases) = paused_holder(&backend).await;+ let scoped = a.for_scope(&Scope::new("profile:alice").unwrap()).unwrap();+ leases.armed.store(true, Ordering::SeqCst);+ assert!(scoped.streams().append("log", json!(1)).await.is_err());+ let raw = backend+ .for_scope(&Scope::new("profile:alice").unwrap())+ .unwrap();+ assert_eq!(raw.streams().len("log").await.unwrap(), 0);++ let (b, _fence, leases) = paused_holder(&shared()).await;+ let scoped = b.for_scope(&Scope::new("profile:alice").unwrap()).unwrap();+ leases.armed.store(true, Ordering::SeqCst);+ assert!(scoped.blobs().put("k", b"x".to_vec(), None).await.is_err());+}++/// A named database cannot see the lease record, so its writes get the+/// host check only: the race stays open there, as the module docs say.+#[tokio::test]+async fn a_named_database_falls_back_to_the_host_check() {+ let backend = shared();+ let (a, fence, leases) = paused_holder(&backend).await;+ let scoped = a+ .database("sessions")+ .unwrap()+ .for_scope(&Scope::new("profile:alice").unwrap())+ .unwrap();+ leases.armed.store(true, Ordering::SeqCst);+ scoped+ .documents()+ .put("t", "x", json!({}), Precondition::None)+ .await+ .unwrap();+ assert!(!fence.is_fenced());+}++/// A driver without fencing gets the host check only, and writes through.+#[tokio::test]+async fn a_driver_without_fencing_falls_back_to_the_host_check() {+ let backend: Arc<dyn StorageBackend> = Arc::new(NoFencing(MemoryStorage::new()));+ let (a, _fence, _leases) = paused_holder(&backend).await;+ let scoped = a.for_scope(&Scope::new("profile:alice").unwrap()).unwrap();+ scoped+ .documents()+ .put("notes", "n", json!({}), Precondition::None)+ .await+ .unwrap();+}++/// The memory driver, reporting no fencing (MongoDB without transactions).+#[derive(Debug)]+struct NoFencing(MemoryStorage);++impl StorageBackend for NoFencing {+ fn driver(&self) -> &'static str {+ "no-fencing"+ }+ fn capabilities(&self) -> Capabilities {+ self.0.capabilities().without(Capability::Fencing)+ }+ fn for_scope(&self, scope: &Scope) -> Result<ScopedStorage> {+ self.0.for_scope(scope)+ }+ fn database(&self, name: &str) -> Result<Arc<dyn StorageBackend>> {+ self.0.database(name)+ }+}