Skip to content

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

refactor(memory): hold workspace queues and owner state weakly

Steven Enamakel8cca39c10f53
diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
index 6d01b48d58..27f78bd9e3 100644
--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs
@@ -19,7 +19,7 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
use tinymemory_api::Namespace;
use tinymemory_tools::queue::{JobQueue as Queue, QueueError, QueueState, QueueStore};
@@ -79,19 +79,20 @@ impl QueueStore for FileQueueStore {
type WorkspaceQueue = Queue<FileQueueStore>;
/// One queue per workspace, so its lock serialises every run in the process.
-static QUEUES: LazyLock<Mutex<HashMap<PathBuf, Arc<WorkspaceQueue>>>> =
+static QUEUES: LazyLock<Mutex<HashMap<PathBuf, Weak<WorkspaceQueue>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
fn queue_of(workspace_dir: &Path) -> Arc<WorkspaceQueue> {
let mut queues = QUEUES.lock().unwrap_or_else(|e| e.into_inner());
- queues
- .entry(workspace_dir.to_path_buf())
- .or_insert_with(|| {
- Arc::new(Queue::new(FileQueueStore {
- file: path(workspace_dir),
- }))
- })
- .clone()
+ queues.retain(|_, queue| queue.strong_count() > 0);
+ if let Some(queue) = queues.get(workspace_dir).and_then(Weak::upgrade) {
+ return queue;
+ }
+ let queue = Arc::new(Queue::new(FileQueueStore {
+ file: path(workspace_dir),
+ }));
+ queues.insert(workspace_dir.to_path_buf(), Arc::downgrade(&queue));
+ queue
}
/// Queues `jobs` under `root`; a job already queued is kept once, at its
diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
index 9ff58f2207..3ecbfef3fd 100644
--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs
@@ -17,6 +17,9 @@ fn workspace_queues_are_released_after_the_last_holder_drops() {
drop(queues);
+ let sentinel = temp.path().join("sentinel");
+ drop(queue_of(&sentinel));
+
let queues = QUEUES.lock().unwrap();
assert!(workspaces.iter().all(|workspace| !queues.contains_key(workspace)));
}
diff --git a/crates/openhuman-core/src/memory/tool_writes.rs b/crates/openhuman-core/src/memory/tool_writes.rs
index 55dc1a773b..eb4dd63f2a 100644
--- a/crates/openhuman-core/src/memory/tool_writes.rs
+++ b/crates/openhuman-core/src/memory/tool_writes.rs
@@ -13,7 +13,7 @@
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::{Arc, LazyLock, Mutex, Weak};
use std::time::Duration;
use async_trait::async_trait;
@@ -45,21 +45,21 @@ struct DrainState {
/// One owner's erasure state: the module's gate (generation, fences) and the
/// barrier an erasure takes exclusively to wait for the write in flight.
-/// Kept for the life of the process (a few bytes per owner) because a fence
-/// token borrows its gate.
+/// Kept alive by active mutations and fences; the registry only holds a weak
+/// reference so owners with no active work can be released.
struct OwnerState {
gate: WriteGate,
barrier: Arc<tokio::sync::RwLock<()>>,
}
-type Owners = HashMap<PathBuf, &'static OwnerState>;
+type Owners = HashMap<PathBuf, Weak<OwnerState>>;
static OWNERS: LazyLock<Mutex<Owners>> = LazyLock::new(|| Mutex::new(HashMap::new()));
type DrainLocks = HashMap<PathBuf, std::sync::Weak<DrainState>>;
static DRAINS: LazyLock<Mutex<DrainLocks>> = LazyLock::new(|| Mutex::new(HashMap::new()));
type Queue = PendingWrites<FileStore>;
-static QUEUES: LazyLock<Mutex<HashMap<PathBuf, Arc<Queue>>>> =
+static QUEUES: LazyLock<Mutex<HashMap<PathBuf, Weak<Queue>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
/// An entry as older builds wrote it: the owner and layout as two fields.
@@ -275,20 +275,21 @@ fn queue(file: &Path) -> Arc<Queue> {
let mut queues = QUEUES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- queues
- .entry(file.to_path_buf())
- .or_insert_with(|| {
- Arc::new(PendingWrites::new(
- FileStore {
- file: file.to_path_buf(),
- },
- Limits {
- max_entries: MAX_PENDING,
- max_bytes: MAX_BYTES,
- },
- ))
- })
- .clone()
+ queues.retain(|_, queue| queue.strong_count() > 0);
+ if let Some(queue) = queues.get(file).and_then(Weak::upgrade) {
+ return queue;
+ }
+ let queue = Arc::new(PendingWrites::new(
+ FileStore {
+ file: file.to_path_buf(),
+ },
+ Limits {
+ max_entries: MAX_PENDING,
+ max_bytes: MAX_BYTES,
+ },
+ ));
+ queues.insert(file.to_path_buf(), Arc::downgrade(&queue));
+ queue
}
fn map_pending(error: PendingError) -> MemoryError {
@@ -330,7 +331,7 @@ fn drain_state(workspace: &Path) -> Arc<DrainState> {
lock
}
-fn owner_state(config: &Config) -> &'static OwnerState {
+fn owner_state(config: &Config) -> Arc<OwnerState> {
let key = config
.workspace_dir
.join("memory")
@@ -338,12 +339,16 @@ fn owner_state(config: &Config) -> &'static OwnerState {
let mut owners = OWNERS
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- owners.entry(key).or_insert_with(|| {
- Box::leak(Box::new(OwnerState {
- gate: WriteGate::new(PROCESS_EPOCH.clone()),
- barrier: Arc::default(),
- }))
- })
+ owners.retain(|_, owner| owner.strong_count() > 0);
+ if let Some(owner) = owners.get(&key).and_then(Weak::upgrade) {
+ return owner;
+ }
+ let owner = Arc::new(OwnerState {
+ gate: WriteGate::new(PROCESS_EPOCH.clone()),
+ barrier: Arc::default(),
+ });
+ owners.insert(key, Arc::downgrade(&owner));
+ owner
}
fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {
@@ -374,7 +379,7 @@ fn partitions(config: &Config) -> MemoryResult<Vec<PathBuf>> {
/// wait in the prefetch queue. Erasure retires older work and waits for active
/// mutations while subsequent work waits behind the exclusive barrier.
pub(crate) struct AutomaticMutation {
- state: &'static OwnerState,
+ state: Arc<OwnerState>,
generation: u64,
}
@@ -404,12 +409,42 @@ pub(crate) fn automatic_mutation(config: &Config) -> AutomaticMutation {
/// Subsequent queued writes resume only after the outer erasure finishes.
pub(crate) struct WriteFence {
guard: Option<tokio::sync::OwnedRwLockWriteGuard<()>>,
- token: Option<FenceToken<'static>>,
- state: &'static OwnerState,
+ token: Option<OwnedFenceToken>,
+ state: Arc<OwnerState>,
config: Arc<Config>,
ctx: crate::core::runtime::DispatchCtx,
}
+/// An owned fence token. The token borrows its gate, so keep the owner alive
+/// and drop the token before releasing that owner.
+struct OwnedFenceToken {
+ _state: Arc<OwnerState>,
+ token: Option<FenceToken<'static>>,
+}
+
+impl OwnedFenceToken {
+ fn new(state: Arc<OwnerState>) -> Self {
+ let token = state.gate.begin_fence();
+ // SAFETY: `state` owns the borrowed gate and remains alive in this
+ // wrapper. `Drop` takes the token before Rust drops the state field.
+ let token = unsafe { std::mem::transmute::<FenceToken<'_>, FenceToken<'static>>(token) };
+ Self {
+ _state: state,
+ token: Some(token),
+ }
+ }
+
+ fn generation(&self) -> u64 {
+ self.token.as_ref().expect("live fence token").generation()
+ }
+}
+
+impl Drop for OwnedFenceToken {
+ fn drop(&mut self) {
+ drop(self.token.take());
+ }
+}
+
impl Drop for WriteFence {
fn drop(&mut self) {
drop(self.token.take());
@@ -428,7 +463,7 @@ pub(crate) async fn fence_and_clear(
config: &Config,
) -> MemoryResult<WriteFence> {
let state = owner_state(config);
- let token = state.gate.begin_fence();
+ let token = OwnedFenceToken::new(state.clone());
let fencing_generation = token.generation();
let mut fence = WriteFence {
guard: None,
diff --git a/crates/openhuman-core/src/memory/tool_writes_tests.rs b/crates/openhuman-core/src/memory/tool_writes_tests.rs
index 17af41244c..ea497734ad 100644
--- a/crates/openhuman-core/src/memory/tool_writes_tests.rs
+++ b/crates/openhuman-core/src/memory/tool_writes_tests.rs
@@ -13,6 +13,7 @@ fn facts(config: &Config) -> CallFacts {
fn owner_states_are_released_after_the_last_write_holder_drops() {
let temp = tempfile::tempdir().unwrap();
let mut keys = Vec::new();
+ let mut queue_files = Vec::new();
let states = (0..32)
.map(|index| {
let workspace = temp.path().join(index.to_string());
@@ -22,15 +23,31 @@ fn owner_states_are_released_after_the_last_write_holder_drops() {
workspace_dir: workspace.clone(),
..config
};
+ let file = workspace
+ .join("memory")
+ .join(format!("{}-writes.json", owner_prefix(&config)));
keys.push(workspace.join("memory").join(owner_prefix(&config)));
+ queue_files.push(file.clone());
+ drop(queue(&file));
owner_state(&config)
})
.collect::<Vec<_>>();
drop(states);
+ let sentinel_workspace = temp.path().join("sentinel");
+ std::fs::create_dir_all(&sentinel_workspace).unwrap();
+ let sentinel_config = Config {
+ workspace_dir: sentinel_workspace.clone(),
+ ..config_in(&temp)
+ };
+ drop(owner_state(&sentinel_config));
+ drop(queue(&sentinel_workspace.join("memory").join("sentinel-writes.json")));
let owners = OWNERS.lock().unwrap();
assert!(keys.iter().all(|key| !owners.contains_key(key)));
+ drop(owners);
+ let queues = QUEUES.lock().unwrap();
+ assert!(queue_files.iter().all(|file| !queues.contains_key(file)));
}
#[tokio::test]