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
fix(memory): keep the exit path's tests off the process-global state\n\nThe exit-path tests that landed with #6017 called the process-wide\n`shutdown_for_exit()`. In a test binary that is every other test's cached\ndriver (snapshotted, shut down and evicted mid-flight — the next lookup\nrebinds to the fallback and reads an empty store), the whole shutdown-hook\nregistry (drained and run, the shared memory engine's own shutdown hook\namong them), and the process's exit gate (raised, so every concurrent bind\nis refused). The coverage lane failed on a read_rpc test this branch does\nnot touch, and the same pairings failed locally on main.\n\nProduction behaviour is unchanged. `shutdown_for_exit()` is now the gate\nstep plus `run_exit(cached_bindings(), take_hooks())`, and the tests drive\n`run_exit` with bindings and hooks of their own. `core::shutdown` gains\n`take_hooks`, `run_hook_list` and `boxed_hook` (the signal path keeps its\nsequential `run_hooks`); the gate is an `ExitGate` with the process's\ninstance in a static, so the gate test exercises an instance of its own\nand the eviction test needs none. The test-only gate seams are gone.\n\nVerified: `memory::exit_tests` beside `memory::binding` three times and\nbeside `memory::read_rpc` twice, all green; both pairings failed before.\n
Shanu3124376aec33
diff --git a/src/core/shutdown.rs b/src/core/shutdown.rsindex aa1e14a438..1572fc6dca 100644--- a/src/core/shutdown.rs+++ b/src/core/shutdown.rs@@ -12,7 +12,7 @@ use std::sync::Mutex;use once_cell::sync::Lazy;/// A boxed async cleanup function.-type ShutdownHook = Box<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;+pub type ShutdownHook = Box<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;/// Global registry of shutdown hooks.static HOOKS: Lazy<Mutex<Vec<ShutdownHook>>> = Lazy::new(|| Mutex::new(Vec::new()));@@ -34,42 +34,55 @@ whereF: Fn() -> Fut + Send + Sync + 'static,Fut: Future<Output = ()> + Send + 'static,{- let boxed: ShutdownHook = Box::new(move || Box::pin(hook()));- HOOKS.lock().expect("shutdown hooks poisoned").push(boxed);+ HOOKS+ .lock()+ .expect("shutdown hooks poisoned")+ .push(boxed_hook(hook));+}++/// Box a cleanup function without registering it.+///+/// For a caller that wants to run a hook through [`run_hook_list`] itself —+/// a test above all, which must not reach into the process-wide registry: in+/// a test binary that registry holds every other test's hooks, the shared+/// memory engine's shutdown among them.+pub fn boxed_hook<F, Fut>(hook: F) -> ShutdownHook+where+ F: Fn() -> Fut + Send + Sync + 'static,+ Fut: Future<Output = ()> + Send + 'static,+{+ Box::new(move || Box::pin(hook()))+}++/// Take every registered hook, leaving the registry empty.+///+/// Draining is what makes the exit idempotent: a later take, or a signal+/// landing mid-teardown, finds nothing to run twice.+pub fn take_hooks() -> Vec<ShutdownHook> {+ let mut guard = HOOKS.lock().expect("shutdown hooks poisoned");+ std::mem::take(&mut *guard)}/// Run all registered hooks (called once during shutdown).////// This function drains the global `HOOKS` list and awaits each hook in sequence.async fn run_hooks() {- let hooks: Vec<ShutdownHook> = {- let mut guard = HOOKS.lock().expect("shutdown hooks poisoned");- // Use mem::take to clear the hooks list and take ownership of the vector.- std::mem::take(&mut *guard)- };- for hook in &hooks {+ for hook in &take_hooks() {hook().await;}}-/// Run every registered hook now, once, without waiting for a signal.-///-/// For the embedded server, whose graceful path is a cancellation token rather-/// than SIGTERM: [`signal`] never resolves there, so the hooks it would have-/// run — the memory engine releasing its queue leases, above all — never ran-/// on a normal quit. Drains the registry, so a later call, or a signal landing-/// mid-teardown, finds nothing to run twice.+/// Run `hooks` side by side.///-/// Side by side, unlike the signal path. The caller runs this under a-/// deadline, and in sequence one hook that never answers would keep every hook-/// registered after it — the lease release among them — from so much as-/// starting before the deadline dropped the lot. Run together, a hanging hook-/// costs only itself.-pub async fn run_hooks_now() {- let hooks: Vec<ShutdownHook> = {- let mut guard = HOOKS.lock().expect("shutdown hooks poisoned");- std::mem::take(&mut *guard)- };+/// For the embedded server's exit, whose graceful path is a cancellation token+/// rather than SIGTERM: [`signal`] never resolves there, so the hooks it would+/// have run — the memory engine releasing its queue leases, above all — never+/// ran on a normal quit. Concurrent, unlike the signal path, because the caller+/// runs this under a deadline, and in sequence one hook that never answers+/// would keep every hook after it — the lease release among them — from so+/// much as starting before the deadline dropped the lot. Run together, a+/// hanging hook costs only itself.+pub async fn run_hook_list(hooks: Vec<ShutdownHook>) {futures::future::join_all(hooks.iter().map(|hook| hook())).await;}diff --git a/src/openhuman/memory/exit.rs b/src/openhuman/memory/exit.rsindex d2de4622b6..e78468f1fc 100644--- a/src/openhuman/memory/exit.rs+++ b/src/openhuman/memory/exit.rs@@ -14,11 +14,14 @@//! lease that expires on its own.use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;use std::time::Duration;use futures::future::join_all;use tokio::time::Instant;+use crate::openhuman::memory::binding::MemoryBinding;+/// The whole of memory's exit work — every bound driver's `shutdown`, then/// the host's hook registry — must fit in this, together.///@@ -36,40 +39,68 @@ pub const EXIT_BUDGET: Duration = Duration::from_secs(2);/// not a driver, so the hooks are never skipped outright.const HOOKS_FLOOR: Duration = Duration::from_millis(250);-/// Whether a real server has started in this process.+/// The exit gate: whether a real server has started in this process, and+/// whether memory is on its way out.///-/// The exit gate below engages only then. Unit tests call-/// [`shutdown_for_exit`] without ever serving, and a process-wide refusal to-/// bind memory would reach every other test in the same process.-static SERVING: AtomicBool = AtomicBool::new(false);--/// Set when memory's exit work begins, cleared when a server starts.+/// `exiting` is read by the binding cache *inside its write lock* before every+/// insert. That ordering is what makes the exit snapshot complete: the flag+/// goes up, then the snapshot is taken under the same lock, so a builder+/// either inserted before the snapshot (and is in it) or sees the flag and is+/// refused. No number of re-snapshots could say that.///-/// Read by the binding cache *inside its write lock* before every insert. That-/// ordering is what makes the exit snapshot complete: the flag goes up, then-/// the snapshot is taken under the same lock, so a builder either inserted-/// before the snapshot (and is in it) or sees the flag and is refused. No-/// number of re-snapshots could say that.-static EXITING: AtomicBool = AtomicBool::new(false);+/// The gate engages only behind a server. Unit tests call the exit work+/// without ever serving, and a process-wide refusal to bind memory would+/// reach every other test in the same process — which is also why this is a+/// type with one production instance in [`GATE`] rather than two bare+/// statics: the tests exercise an instance of their own and never touch the+/// process's.+pub(crate) struct ExitGate {+ serving: AtomicBool,+ exiting: AtomicBool,+}++impl ExitGate {+ pub(crate) const fn new() -> Self {+ Self {+ serving: AtomicBool::new(false),+ exiting: AtomicBool::new(false),+ }+ }++ /// A server is starting: arm the gate for the eventual exit and clear one+ /// a previous server in this process may have left.+ pub(crate) fn server_starting(&self) {+ self.exiting.store(false, Ordering::SeqCst);+ self.serving.store(true, Ordering::SeqCst);+ }++ /// Memory's exit work is beginning: refuse new bindings from here on —+ /// but only behind a server.+ pub(crate) fn raise_if_serving(&self) {+ if self.serving.load(Ordering::SeqCst) {+ self.exiting.store(true, Ordering::SeqCst);+ }+ }++ /// Whether memory is on its way out.+ pub(crate) fn exiting(&self) -> bool {+ self.exiting.load(Ordering::SeqCst)+ }+}++/// The process's gate.+static GATE: ExitGate = ExitGate::new();/// Called by the embedded server as it starts serving. Arms the exit gate for/// the eventual exit and clears one left by a previous server in this process/// (the shell can respawn the core task without restarting the process).pub fn server_starting() {- EXITING.store(false, Ordering::SeqCst);- SERVING.store(true, Ordering::SeqCst);+ GATE.server_starting();}/// Whether memory is on its way out: new bindings are refused.pub(crate) fn exiting() -> bool {- EXITING.load(Ordering::SeqCst)-}--/// Test seam: put both flags back so one test's exit cannot leak into another.-#[cfg(test)]-pub(crate) fn reset_gate_for_tests() {- EXITING.store(false, Ordering::SeqCst);- SERVING.store(false, Ordering::SeqCst);+ GATE.exiting()}/// Ask every bound memory driver to shut down, then run the hooks the@@ -87,12 +118,32 @@ pub(crate) fn reset_gate_for_tests() {/// server the shell starts next in this same process binds anew instead of/// reusing a driver whose workers are stopped.pub async fn shutdown_for_exit() {- if SERVING.load(Ordering::SeqCst) {- EXITING.store(true, Ordering::SeqCst);- }+ // The snapshot is taken only after the gate is up (see [`ExitGate`]).+ GATE.raise_if_serving();+ run_exit(+ crate::openhuman::memory::binding::cached_bindings(),+ crate::core::shutdown::take_hooks(),+ )+ .await;+}++/// The exit work over an explicit set of bindings and hooks: every driver's+/// `shutdown` concurrently on the shared deadline, eviction of exactly those+/// bindings, then the hooks.+///+/// Split from [`shutdown_for_exit`] so the tests can drive it with bindings+/// and hooks of their own. The process-wide snapshot and the registry drain+/// are right for a process on its way out and wrong for a test binary: one+/// test's exit would shut down and evict every other test's cached driver+/// mid-flight — the next lookup handing that test the null fallback and an+/// empty store — and would run every other test's hooks, the shared memory+/// engine's own shutdown among them.+pub(crate) async fn run_exit(+ bindings: Vec<Arc<MemoryBinding>>,+ hooks: Vec<crate::core::shutdown::ShutdownHook>,+) {let deadline = Instant::now() + EXIT_BUDGET;- let bindings = crate::openhuman::memory::binding::cached_bindings();if !bindings.is_empty() {let shutdowns = join_all(bindings.iter().map(|binding| async move {let driver = binding.driver_id().to_string();@@ -118,7 +169,7 @@ pub async fn shutdown_for_exit() {}let hooks_deadline = deadline.max(Instant::now() + HOOKS_FLOOR);- if tokio::time::timeout_at(hooks_deadline, crate::core::shutdown::run_hooks_now())+ if tokio::time::timeout_at(hooks_deadline, crate::core::shutdown::run_hook_list(hooks)).await.is_err(){diff --git a/src/openhuman/memory/exit_tests.rs b/src/openhuman/memory/exit_tests.rsindex 74172637d9..8ec26ee798 100644--- a/src/openhuman/memory/exit_tests.rs+++ b/src/openhuman/memory/exit_tests.rs@@ -1,77 +1,80 @@//! Tests for the memory exit path.+//!+//! Every test drives `run_exit` with bindings and hooks of its own, never the+//! process-wide snapshot and registry drain `shutdown_for_exit` performs: in a+//! test binary the snapshot is every other test's cached driver, and the+//! registry holds the shared memory engine's own shutdown hook — shutting those+//! down mid-flight hands the other tests the null fallback and a dead store.+//! The gate is exercised on an instance of its own for the same reason: with+//! the process's gate raised, every other test's bind is refused.use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use std::time::Duration;use super::binding::{cached_bindings, for_subtree};-use super::exit::{exiting, reset_gate_for_tests, server_starting, shutdown_for_exit, EXIT_BUDGET};+use super::exit::{run_exit, ExitGate, EXIT_BUDGET};use crate::openhuman::config::schema::MemorySubsystemConfig;-/// The hook registry is process-global, so the two tests below must not see-/// each other's hooks: each registers and drains under this lock.-static REGISTRY: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());--/// With no binding ever built, the exit path is the hook registry alone — and-/// the registry drains, so the hooks run once however many times exit is asked-/// for (the app-update restart path asks twice).+/// With no binding, the exit path is the hooks alone — each run once. What an+/// exit took from the registry is gone from it (`take_hooks` drains), so a+/// second exit — the app-update restart path asks twice — finds nothing to+/// run again.#[tokio::test]-async fn exit_runs_registered_hooks_once() {- let _serial = REGISTRY.lock().await;+async fn exit_runs_each_hook_once() {let runs = Arc::new(AtomicUsize::new(0));let counter = Arc::clone(&runs);- crate::core::shutdown::register(move || {+ let hook = crate::core::shutdown::boxed_hook(move || {let counter = Arc::clone(&counter);async move {counter.fetch_add(1, Ordering::SeqCst);}});- shutdown_for_exit().await;- shutdown_for_exit().await;+ run_exit(Vec::new(), vec![hook]).await;+ run_exit(Vec::new(), Vec::new()).await;assert_eq!(runs.load(Ordering::SeqCst),1,- "the registry drains on the first exit; the second finds nothing"+ "a hook runs on the exit that took it, and never again");}/// The gate that refuses new bindings goes up only once a real server has/// started — a bare exit (every unit test in this process) must never leave/// memory refusing to bind — and a server starting again takes it down.-#[tokio::test]-async fn the_exit_gate_engages_only_behind_a_server() {- let _serial = REGISTRY.lock().await;- reset_gate_for_tests();+#[test]+fn the_exit_gate_engages_only_behind_a_server() {+ let gate = ExitGate::new();- shutdown_for_exit().await;+ gate.raise_if_serving();assert!(- !exiting(),+ !gate.exiting(),"no server ever started, so exit must not gate bindings");- server_starting();- shutdown_for_exit().await;- assert!(exiting(), "behind a server, exit refuses new bindings");-- server_starting();- assert!(!exiting(), "a server starting again takes the gate down");+ gate.server_starting();+ gate.raise_if_serving();+ assert!(gate.exiting(), "behind a server, exit refuses new bindings");- reset_gate_for_tests();+ gate.server_starting();+ assert!(+ !gate.exiting(),+ "a server starting again takes the gate down"+ );}/// A hook that never answers must not hold the quit: exit returns within its/// budget (plus the hooks' floor) and the process goes on without it.#[tokio::test]async fn exit_is_bounded_even_when_a_hook_hangs() {- let _serial = REGISTRY.lock().await;- crate::core::shutdown::register(|| async {+ let hang = crate::core::shutdown::boxed_hook(|| async {tokio::time::sleep(Duration::from_secs(30)).await;});let started = std::time::Instant::now();- shutdown_for_exit().await;+ run_exit(Vec::new(), vec![hang]).await;assert!(started.elapsed() < EXIT_BUDGET + Duration::from_secs(2),@@ -86,8 +89,6 @@ async fn exit_is_bounded_even_when_a_hook_hangs() {/// bind builds anew.#[tokio::test]async fn exit_evicts_the_drivers_it_shut_down() {- let _serial = REGISTRY.lock().await;- reset_gate_for_tests();let workspace = tempfile::tempdir().expect("tempdir");let cfg = MemorySubsystemConfig {driver: "null".into(),@@ -101,8 +102,7 @@ async fn exit_evicts_the_drivers_it_shut_down() {"the binding is cached before exit");- server_starting();- shutdown_for_exit().await;+ run_exit(vec![Arc::clone(&before)], Vec::new()).await;assert!(!cached_bindings().iter()@@ -110,11 +110,9 @@ async fn exit_evicts_the_drivers_it_shut_down() {"exit must drop the driver it shut down");- server_starting();let after = for_subtree(workspace.path(), "memory", &cfg).expect("binds again after a restart");assert!(!Arc::ptr_eq(&before, &after),"a restarted server must not be handed back a driver exit already stopped");- reset_gate_for_tests();}