Skip to content

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

Merge remote-tracking branch 'upstream/main' into saas-profile-lifecycle

Steven Enamakela2fc4a1e072e
diff --cc crates/openhuman-core/src/profiles/README.md
index 4f031f149b,7ad9c9b6d0..aeda7bc458
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@@ -339,7 -321,8 +351,9 @@@ set
| `types.rs` | `ProfileId` and `ProfileIdMode`, `ProfileMeta`, and the operator-plane result types |
| `layout.rs` | The SaaS side of the shared `ProfileLayout`, archived profiles, and `profile_config`: the forced paths, memory binding (pinned to the legacy layout) and autonomy policy |
| `host.rs` | `ProfileHost`: provisioning, lazy open behind the lease, LRU and idle eviction (never of a profile in use), release, fencing, each profile's derived `CoreContext` and policy, `current()`, `ensure_hosted()` |
+| `lifecycle.rs` | Provisioning, deprovisioning and credential changes, and `ProfileLocks`: the per-profile lock that keeps one profile's lifecycle operations from interleaving (see [Lifecycle](#lifecycle)) |
+ | `fence.rs` | The profile's lease fence: the scopes its grant guards (its own scope and every `<profile>~<agent>` session scope), the skew margin, and how the host registers, renews, latches and retires it |
+ | `recovery.rs` | Workspace and session-store recovery after an unclean takeover |
| `lease.rs` | The profile lease as the host uses it: `OpenError`, the lease store choice (`DocumentLeases` over a backend, else `LocalLeases`), and the heartbeat that renews every open profile's lease and fences the ones lost |
| `registry.rs` | `ProfileRegistry`: which profiles are provisioned, in the backend's `cluster` scope or as `profile.toml` files |
| `gateway.rs` | Which context a gateway request runs under: the operator plane, or the profile of the user named in `X-OpenHuman-User`, after the signature check; the typed refusal (`409` holder) |
diff --cc crates/openhuman-core/src/profiles/host.rs
index b824275e8c,b329204418..843780db4b
--- a/crates/openhuman-core/src/profiles/host.rs
+++ b/crates/openhuman-core/src/profiles/host.rs
@@@ -26,12 -25,13 +25,14 @@@ use std::time::{Duration, Instant, Syst
use super::layout::{self, ProfileLayout};
use super::lease::{self as profile_lease, OpenError};
+use super::lifecycle::ProfileLocks;
+ use super::recovery::{recover_session_store, recover_workspace};
use super::registry::ProfileRegistry;
-use super::types::{ProfileId, ProfileMeta, ProfileSummary, LAYOUT_VERSION};
+use super::types::{ProfileId, ProfileMeta, ProfileSummary};
use crate::config::Config;
use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet, SaasConfig};
+ use crate::storage::fence::{FenceRegistry, LeaseFence};
-use crate::storage::lease::{LeaseError, LeaseGrant, LeaseStore};
+use crate::storage::lease::{LeaseGrant, LeaseStore};
use crate::storage::StorageBackend;
use crate::tools::toolpacks::ToolGroups;
@@@ -73,21 -78,17 +79,22 @@@ pub(super) struct Slot
/// The open profiles of one SaaS process.
pub struct ProfileHost {
- saas: SaasConfig,
- operator: Arc<CoreContext>,
- node: String,
- open: Mutex<HashMap<ProfileId, Slot>>,
+ pub(super) saas: SaasConfig,
+ pub(super) operator: Arc<CoreContext>,
+ pub(super) node: String,
+ pub(super) open: Mutex<HashMap<ProfileId, Slot>>,
/// Held across every operation that takes or gives back a lease (open,
- /// eviction, release, deprovision), so no two of them interleave on one
- /// profile. Lookups of an open profile never wait for it.
- gate: tokio::sync::Mutex<()>,
- leases: Arc<dyn LeaseStore>,
- fences: Arc<FenceRegistry>,
- registry: ProfileRegistry,
+ /// eviction, release, deprovision), so no two of them interleave and
+ /// the slot count stays exact. Lookups of an open profile never wait
+ /// for it. Taken after the profile's own lifecycle lock, never before.
+ pub(super) gate: tokio::sync::Mutex<()>,
+ /// One lock per profile, held for the whole of each lifecycle operation
+ /// on it (provision, open, credential changes, deprovision); see
+ /// [`super::lifecycle`].
+ pub(super) lifecycle: ProfileLocks,
+ pub(super) leases: Arc<dyn LeaseStore>,
++ pub(super) fences: Arc<FenceRegistry>,
+ pub(super) registry: ProfileRegistry,
}
impl std::fmt::Debug for ProfileHost {
@@@ -148,8 -149,8 +155,9 @@@ impl ProfileHost
node,
open: Mutex::new(HashMap::new()),
gate: tokio::sync::Mutex::new(()),
+ lifecycle: ProfileLocks::default(),
leases,
+ fences: crate::storage::fence::registry(),
registry,
})
}
@@@ -243,28 -349,9 +262,28 @@@
log::debug!("[profiles] lease of profile={id} refused: {error}");
OpenError::from(error)
})?;
+ // Read the registry again now that the lease is ours: a node that
+ // deprovisioned the profile held its lease until the record was
+ // gone, so an open that read the record before that must not
+ // recreate the archived directory.
+ match self.registry.get(id).await {
+ Ok(Some(_)) => {}
+ outcome => {
- profile_lease::release_all(self.leases(), vec![(id.clone(), grant)]).await;
++ profile_lease::release_all(self, vec![(id.clone(), grant)]).await;
+ return Err(match outcome {
+ Err(error) => OpenError::Storage(error),
+ _ => {
+ log::info!(
+ "[profiles] open profile={id}: deprovisioned meanwhile; not reopening"
+ );
+ OpenError::NotProvisioned(id.clone())
+ }
+ });
+ }
+ }
let layout = self.layout_of(id);
if let Err(error) = create_dirs(&layout) {
- profile_lease::release_all(self.leases(), vec![(id.clone(), grant)]).await;
+ profile_lease::release_all(self, vec![(id.clone(), grant)]).await;
return Err(OpenError::Storage(error));
}
let config = layout::profile_config(&layout, id);
@@@ -385,12 -479,19 +423,14 @@@
/// host it at once. Returns whether it was open here. A profile in use
/// is not released from under its work.
pub async fn release(&self, id: &ProfileId) -> Result<bool, String> {
+ // Lifecycle lock before the gate, as every lifecycle operation does.
+ let _profile = self.lifecycle.lock(id).await;
let _gate = self.gate.lock().await;
- let grant = {
- let mut open = self.lock();
- match open.get(id) {
- None => return Ok(false),
- Some(slot) if in_use(slot) => {
- return Err(format!("profile {id} is in use; try again shortly"))
- }
- Some(_) => open.remove(id).map(|slot| slot.grant),
- }
+ let Some(grant) = self.close_if_idle(id)? else {
+ return Ok(false);
};
- let grant = grant.expect("checked above");
++ // Retire the fence before the lease goes back, as `release_all` does.
+ self.fences.retire(id.as_str(), grant.epoch);
self.leases.release(grant).await.map_err(|error| {
log::warn!("[profiles] releasing profile={id} failed: {error}");
format!("releasing profile {id}: {error}")
diff --cc crates/openhuman-core/src/profiles/mod.rs
index c71bbb47e1,dae2fb7810..f4222d3bfa
--- a/crates/openhuman-core/src/profiles/mod.rs
+++ b/crates/openhuman-core/src/profiles/mod.rs
@@@ -28,8 -29,8 +29,9 @@@ pub mod gateway
pub mod host;
pub mod layout;
pub mod lease;
+pub mod lifecycle;
pub mod ops;
+ mod recovery;
pub mod registry;
pub mod schemas;
pub mod surface;
diff --cc tests/saas_mode_e2e.rs
index 3389d2e456,94139c95a3..84fb0374de
--- a/tests/saas_mode_e2e.rs
+++ b/tests/saas_mode_e2e.rs
@@@ -10,75 -9,16 +9,18 @@@ use std::time::{Duration, Instant}
use serde_json::{json, Value};
+ #[path = "saas_mode/support.rs"]
+ mod support;
+ use support::*;
+
#[path = "saas_mode/cluster.rs"]
mod cluster;
+#[path = "saas_mode/hashed_ids.rs"]
+mod hashed_ids;
-
- const BEARER: &str = "saas-e2e-gateway-bearer-0123456789abcdef";
-
- /// Environment a developer machine may carry that would point the child at a
- /// single user, or that the boot guard refuses outright.
- const SCRUBBED_ENV: &[&str] = &[
- "OPENHUMAN_WORKSPACE",
- "OPENHUMAN_DEV_CONNECT",
- "OPENHUMAN_BACKEND_SESSION_TOKEN",
- "OPENHUMAN_BACKEND_API_KEY",
- "OPENHUMAN_CORE_TOKEN",
- "OPENHUMAN_APPROVAL_GATE",
- "OPENHUMAN_SANDBOX",
- "OPENHUMAN_MODE",
- "OPENHUMAN_STORAGE_URL",
- "OPENHUMAN_NODE_ID",
- ];
-
- struct Deployment {
- tmp: tempfile::TempDir,
- root: PathBuf,
- config: PathBuf,
- }
-
- fn deployment(write_token: bool) -> Deployment {
- let tmp = tempfile::tempdir().expect("temp dir");
- let root = tmp.path().join("saas");
- std::fs::create_dir(&root).unwrap();
- set_mode(&root, 0o700);
- if write_token {
- let token = root.join("service.token");
- std::fs::write(&token, format!("{BEARER}\n")).unwrap();
- set_mode(&token, 0o600);
- }
- let config = tmp.path().join("operator.toml");
- std::fs::write(
- &config,
- format!("root = {:?}\n", root.display().to_string()),
- )
- .unwrap();
- Deployment { tmp, root, config }
- }
-
- #[cfg(unix)]
- fn set_mode(path: &Path, mode: u32) {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
- }
-
- #[cfg(not(unix))]
- fn set_mode(_: &Path, _: u32) {}
-
- fn core_command(d: &Deployment, extra: &[&str]) -> Command {
- let mut cmd = Command::new(env!("CARGO_BIN_EXE_openhuman-core"));
- cmd.args(["run", "--mode", "saas", "--saas-config"])
- .arg(&d.config)
- .args(extra)
- // Keep the child away from the developer's real `~/.openhuman`.
- .env("HOME", d.tmp.path())
- .env("USERPROFILE", d.tmp.path());
- for var in SCRUBBED_ENV {
- cmd.env_remove(var);
- }
- cmd
- }
+ #[path = "saas_mode/memory.rs"]
+ mod memory;
+ #[path = "saas_mode/mock_memory.rs"]
+ mod mock_memory;
#[test]
fn an_unsafe_deployment_is_refused_before_it_binds() {