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
chore(ci): declare the tinymemory pin drift, and correct the memory README\n\n**Pin gate.** `check-module-pins.mjs` compares the version `modules::registry`\nnames against the submodule's `git describe`, because a module is pinned twice —\nas the contract this build compiles against and as the artifact loaded at\nruntime — and when the two disagree the build is green and the failure lands on\na user's machine (openhuman#5727). The submodule now sits 15 commits past\nv1.15.2 while the registry keeps the published v1.15.2 artifact, so the gate\nfires.\n\nThe exemption states why that cannot become a runtime mismatch, and the claim\nwas checked rather than asserted: the entire v1.15.2..5c55431 delta to the\ncrates this build ships is one additive re-export (`pub use\ntinymemory_bus::chrono` in tinymemory-api, so a driver crate depending on the\ncontract alone can name the `DateTime<Utc>` two `MemoryTree` methods already\ntake), one `#[cfg(test)] mod summarise_tests;` line in tinymemory-core, and 31\nlines of doc comment. Zero removals, no method added or changed, no wire slot\nmoved, `CONTRACT_VERSION` untouched. Everything else in the range is\n`tinymemory-conformance`, a test-only crate that is not in the artifact at all.\n\n`expect` pins the exact describe output, so the drift cannot widen without\nanother reviewable edit, and the entry says to delete it at tinymemory's next\nrelease.\n\n**README.** It described a module that is mostly `pub use tinymemory_core::…`\nand told the reader to prefer that crate in new code. Neither has been true\nsince openhuman#5560 drained the product callers, and after this branch the\ncrate is in neither the normal nor the dev graph — so the advice pointed at\nsomething unreachable. It now says what AGENTS.md says: prefer\n`tinymemory_api`, never `tinymemory_core`. The dead `host_impls.rs` link is\ngone with it (the file went with the engine), which is what the Markdown Link\nCheck caught.\n\nThe layer rules are corrected the same way: persistence goes through the bound\ndriver and its capability families, not through `tinymemory_core::store::*`.\n
Shanue652c77e48ac
diff --git a/scripts/ci/module-pin-exemptions.json b/scripts/ci/module-pin-exemptions.jsonindex 433c132484..78b09f7619 100644--- a/scripts/ci/module-pin-exemptions.json+++ b/scripts/ci/module-pin-exemptions.json@@ -9,7 +9,7 @@"is a deliberate edit to this file, which is a reviewable diff.","","Delete an entry the moment the pins are reconciled. An exemption that has",- "stopped being true fails the gate too — `expect` must still match."+ "stopped being true fails the gate too \u2014 `expect` must still match."],"exemptions": [{@@ -29,6 +29,12 @@"submodule": "vendor/tinymcp","expect": "v0.3.2-2-g8b0627d","reason": "The host compiles the MCP contract against tinyhumansai/tinymcp#13 (Supervisor::tick returns a TickReport; needed by openhuman#5931), merged to tinymcp main but not yet in a tagged release, while the registry keeps the published v0.3.2 artifact. The drift is compile-only: the tinymcp module is registry-entered but not wired (AGENTS.md, 'step two of the extraction'), so no build downloads or loads that artifact. Delete this entry when tinymcp cuts its next release and the registry pin moves onto it."+ },+ {+ "id": "tinymemory",+ "submodule": "vendor/tinymemory",+ "expect": "v1.15.2-15-g5c55431",+ "reason": "The host compiles the memory contract against tinymemory main (tinyhumansai/tinymemory#148, #150 and #151 \u2014 the engine-free conformance driver openhuman#6161 binds in place of an in-process engine), merged upstream but not yet in a tagged release, while the registry keeps the published v1.15.2 artifact. The drift cannot reach a runtime mismatch, and that was checked rather than assumed: the entire v1.15.2..5c55431 delta to the crates this build ships is (a) one additive re-export, `pub use tinymemory_bus::chrono` in tinymemory-api, so a driver crate depending on the contract alone can name the `DateTime<Utc>` two MemoryTree methods already take, (b) a `#[cfg(test)] mod summarise_tests;` line in tinymemory-core, and (c) 31 lines of doc comment on MemoryDocuments::list_documents and delete_document. Zero removals, no method added or changed, no wire slot moved, CONTRACT_VERSION untouched \u2014 so the v1.15.2 artifact serves exactly the contract compiled here. Everything else in the range is tinymemory-conformance, a test-only crate that is a dev-dependency here and is not in the module artifact at all. Delete this entry when tinymemory cuts its next release and the registry pin moves onto it."}]}diff --git a/src/bin/library_profile/harness.rs b/src/bin/library_profile/harness.rsnew file mode 100644index 0000000000..e094462743--- /dev/null+++ b/src/bin/library_profile/harness.rs@@ -0,0 +1,495 @@+//! Shared profiling harness: hermetic fixture, RSS sampling, and the+//! `measure()` wrapper that every scenario runs its workload through.+//!+//! All diagnostics go to **stderr** (stdout must stay pure JSON) using the+//! stable `[library-profile]` prefix.++use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use anyhow::{Context, Result};+use openhuman_core::openhuman::config::Config;+use openhuman_core::openhuman::platform::proc_metrics::{self, ProcSample, TreeSample};+use serde::Serialize;++/// One sampled point inside a measured workload. `delta_kib` is the RSS change+/// versus the *previous* checkpoint (or the baseline for the first one).+#[derive(Debug, Clone, Serialize)]+pub struct Checkpoint {+ pub label: String,+ pub at_ms: u128,+ pub rss_kib: u64,+ pub delta_kib: i64,+}++/// Turn wall-latency percentiles (milliseconds) collected under overlapping+/// load by the `fleet` scenario.+#[derive(Debug, Clone, Copy, Serialize)]+pub struct TurnLatency {+ pub p50: u128,+ pub p95: u128,+ pub p99: u128,+ pub max: u128,+}++/// Per-descendant RSS entry in a [`TreeReport`].+#[derive(Debug, Clone, Serialize)]+pub struct TreeChild {+ pub name: String,+ pub rss_kib: u64,+}++/// Process-*tree* RSS reporting: this process plus every descendant+/// (interpreter children such as `node` / `python` a skill run spawns). Folds a+/// [`TreeSample`] down to the reported shape. `tree_rss_kib` counts self + all+/// descendants, so it exceeds `settled.rss_kib` whenever a child was live at+/// sample time.+#[derive(Debug, Clone, Serialize)]+pub struct TreeReport {+ pub tree_rss_kib: u64,+ pub child_count: usize,+ pub children: Vec<TreeChild>,+}++impl TreeReport {+ pub fn from_sample(sample: &TreeSample) -> Self {+ Self {+ tree_rss_kib: sample.tree_rss_kib,+ child_count: sample.children.len(),+ children: sample+ .children+ .iter()+ .map(|child| TreeChild {+ name: child.name.clone(),+ rss_kib: child.rss_kib,+ })+ .collect(),+ }+ }+}++/// Fleet capacity budget math (purely informational — scripts turn `fits` into+/// pass/fail). `projected_rss_mib_at_target = settled_base + marginal * target`.+#[derive(Debug, Clone, Copy, Serialize)]+pub struct FleetBudget {+ pub target_agents: u64,+ pub ram_budget_mib: u64,+ pub projected_rss_mib_at_target: f64,+ pub fits: bool,+}++/// Pinned JSON output contract (schema_version = 2). New optional fields are+/// skipped when absent so the two original scenarios stay byte-identical.+#[derive(Debug, Serialize)]+pub struct ProfileResult {+ pub schema_version: u32,+ pub scenario: &'static str,+ pub workload_units: usize,+ pub duration_ms: u128,+ pub baseline: ProcSample,+ pub settled: ProcSample,+ pub peak_rss_kib: u64,+ pub retained_delta_kib: i64,+ pub peak_delta_kib: u64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub turns: Option<usize>,+ /// (`fleet`) requested live-agent count.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub agents: Option<usize>,+ /// (`fleet`) agents actually constructed (may be < `agents` on fd/OOM).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub agents_built: Option<usize>,+ /// (`fleet`) marginal RSS cost per agent (`baseline → constructed`), KiB.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub marginal_rss_kib_per_agent: Option<f64>,+ /// (`fleet`) user+system CPU delta over the 10 s idle window, ms.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub idle_cpu_ms: Option<u64>,+ /// (`fleet`) turn wall-latency percentiles under overlapping load.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub turn_latency_ms: Option<TurnLatency>,+ /// (`fleet`) capacity budget projection.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub budget: Option<FleetBudget>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub checkpoints: Option<Vec<Checkpoint>>,+ /// (`subagent-storm`) K parallel researcher subagents fanned out in the turn.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub subagents: Option<usize>,+ /// (`skill-run`) process-tree RSS including interpreter child processes.+ /// Reports the richest tree seen — the peak-during-workload sample when a+ /// short-lived child (e.g. `node`) has already exited by settle time.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub tree: Option<TreeReport>,+ /// Present (and `true`) only when the dhat heap profiler is active, since+ /// RSS/time numbers are perturbed by dhat's global allocator.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub dhat: Option<bool>,+}++/// Restores (or removes) an environment variable on drop.+pub struct EnvGuard {+ key: &'static str,+ old: Option<String>,+}++impl EnvGuard {+ pub fn set(key: &'static str, value: &str) -> Self {+ let old = std::env::var(key).ok();+ std::env::set_var(key, value);+ Self { key, old }+ }+}++impl Drop for EnvGuard {+ fn drop(&mut self) {+ match &self.old {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+}++/// A hermetic config rooted in a throwaway temp workspace. Local inference,+/// Python, spaCy, and embeddings are all disabled so runs are offline.+pub struct Fixture {+ pub config: Config,+ _workspace_env: EnvGuard,+ _keyring_env: EnvGuard,+ _action_env: EnvGuard,+ _tmp: tempfile::TempDir,+}++pub fn fixture() -> Result<Fixture> {+ let tmp = tempfile::tempdir().context("create profile workspace")?;+ let root = tmp.path();+ let workspace = root.join("workspace");+ std::fs::create_dir_all(&workspace)?;+ // A real, writable action sandbox so acting tools (e.g. `node_exec`, which+ // spawns `node` in the action dir) have a valid cwd. Harmless for scenarios+ // that never act.+ let action_dir = root.join("action");+ std::fs::create_dir_all(&action_dir)?;++ let mut config_toml = r#"api_url = "http://127.0.0.1:9"+default_model = "profile-mock"+default_temperature = 0.0+chat_onboarding_completed = true++[secrets]+encrypt = false++[local_ai]+enabled = false+runtime_enabled = false++[runtime_python]+enabled = false++[memory_tree]+spacy_enabled = false+"#+ .to_string();+ if std::env::var_os("OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES").is_some() {+ config_toml.push_str(+ r#"+[memory]+auto_save = false++[learning]+episodic_capture_enabled = false+"#,+ );+ }+ // `skill-run` executes real acting tools (`node_exec`); those need the Full+ // autonomy tier so the write-class gate does not park the turn on approval.+ // Config::load_or_init inside the detached workflow run re-reads this file,+ // so the tier must live in config.toml (not just the in-memory Config).+ if std::env::var_os("OPENHUMAN_PROFILE_FULL_AUTONOMY").is_some() {+ config_toml.push_str(+ r#"+[autonomy]+level = "full"+"#,+ );+ }+ std::fs::write(root.join("config.toml"), &config_toml)?;++ let workspace_env = EnvGuard::set("OPENHUMAN_WORKSPACE", &root.to_string_lossy());+ let keyring_env = EnvGuard::set("OPENHUMAN_KEYRING_BACKEND", "file");+ let action_env = EnvGuard::set("OPENHUMAN_ACTION_DIR", &action_dir.to_string_lossy());+ let mut config: Config = toml::from_str(&config_toml)?;+ config.workspace_dir = workspace;+ config.action_dir = action_dir;+ config.memory_tree.embedding_endpoint = None;+ config.memory_tree.embedding_model = None;+ config.memory_tree.embedding_strict = false;++ Ok(Fixture {+ config,+ _workspace_env: workspace_env,+ _keyring_env: keyring_env,+ _action_env: action_env,+ _tmp: tmp,+ })+}++/// Background task that polls `proc_metrics::sample_self()` every 5 ms and+/// keeps the running peak RSS.+pub struct PeakSampler {+ peak: Arc<AtomicU64>,+ stop: Arc<AtomicU64>,+ task: tokio::task::JoinHandle<()>,+}++impl PeakSampler {+ pub fn start(initial_kib: u64) -> Self {+ let peak = Arc::new(AtomicU64::new(initial_kib));+ let stop = Arc::new(AtomicU64::new(0));+ let task_peak = Arc::clone(&peak);+ let task_stop = Arc::clone(&stop);+ let task = tokio::spawn(async move {+ while task_stop.load(Ordering::Relaxed) == 0 {+ if let Ok(sample) = proc_metrics::sample_self() {+ task_peak.fetch_max(sample.rss_kib, Ordering::Relaxed);+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ });+ Self { peak, stop, task }+ }++ pub async fn stop(self) -> u64 {+ self.stop.store(1, Ordering::Relaxed);+ let _ = self.task.await;+ self.peak.load(Ordering::Relaxed)+ }+}++/// Background task that polls `proc_metrics::sample_tree()` and keeps the+/// [`TreeSample`] with the highest `tree_rss_kib` seen — capturing the moment a+/// short-lived interpreter child (e.g. a `node -e` step) is resident, which a+/// settle-time-only sample would miss because the child has already exited.+pub struct TreePeakSampler {+ best: Arc<Mutex<Option<TreeSample>>>,+ stop: Arc<AtomicU64>,+ task: tokio::task::JoinHandle<()>,+}++impl TreePeakSampler {+ pub fn start() -> Self {+ let best: Arc<Mutex<Option<TreeSample>>> = Arc::new(Mutex::new(None));+ let stop = Arc::new(AtomicU64::new(0));+ let task_best = Arc::clone(&best);+ let task_stop = Arc::clone(&stop);+ let task = tokio::spawn(async move {+ while task_stop.load(Ordering::Relaxed) == 0 {+ if let Ok(sample) = proc_metrics::sample_tree() {+ let mut guard = task_best.lock().expect("tree peak lock");+ let replace = guard+ .as_ref()+ .map(|prev| sample.tree_rss_kib > prev.tree_rss_kib)+ .unwrap_or(true);+ if replace {+ *guard = Some(sample);+ }+ }+ tokio::time::sleep(Duration::from_millis(15)).await;+ }+ });+ Self { best, stop, task }+ }++ pub async fn stop(self) -> Option<TreeSample> {+ self.stop.store(1, Ordering::Relaxed);+ let _ = self.task.await;+ self.best.lock().expect("tree peak lock").clone()+ }+}++/// Collects per-phase / per-turn checkpoints inside a measured workload.+/// Cloneable (shares one buffer) so it can be handed to closures freely.+#[derive(Clone)]+pub struct Recorder {+ inner: Arc<Mutex<RecorderState>>,+ started: Instant,+}++struct RecorderState {+ checkpoints: Vec<Checkpoint>,+ last_rss_kib: u64,+}++impl Recorder {+ fn new(baseline_kib: u64, started: Instant) -> Self {+ Self {+ inner: Arc::new(Mutex::new(RecorderState {+ checkpoints: Vec::new(),+ last_rss_kib: baseline_kib,+ })),+ started,+ }+ }++ /// Sample RSS now and append a labelled checkpoint whose `delta_kib` is+ /// relative to the previous checkpoint (baseline for the first).+ pub fn checkpoint(&self, label: impl Into<String>) -> Result<()> {+ let label = label.into();+ let sample = proc_metrics::sample_self()?;+ let at_ms = self.started.elapsed().as_millis();+ let mut state = self.inner.lock().expect("recorder lock");+ let delta_kib = sample.rss_kib as i64 - state.last_rss_kib as i64;+ state.last_rss_kib = sample.rss_kib;+ eprintln!(+ "[library-profile] checkpoint label={label} at_ms={at_ms} rss_kib={} delta_kib={delta_kib}",+ sample.rss_kib+ );+ state.checkpoints.push(Checkpoint {+ label,+ at_ms,+ rss_kib: sample.rss_kib,+ delta_kib,+ });+ Ok(())+ }++ fn take(self) -> Vec<Checkpoint> {+ self.inner+ .lock()+ .expect("recorder lock")+ .checkpoints+ .clone()+ }+}++/// Run `workload` between a settled baseline and a settled post-run sample,+/// tracking peak RSS throughout. `turns` and any checkpoints pushed via the+/// `Recorder` are folded into the result (both `None`/omitted when unused).+pub async fn measure<F, Fut>(+ scenario: &'static str,+ workload_units: usize,+ turns: Option<usize>,+ workload: F,+) -> Result<ProfileResult>+where+ F: FnOnce(Recorder) -> Fut,+ Fut: std::future::Future<Output = Result<()>>,+{+ measure_impl(scenario, workload_units, turns, false, workload).await+}++/// Like [`measure`], but also samples the process **tree** (self + descendant+/// interpreter processes). A [`TreePeakSampler`] runs alongside the RSS peak+/// sampler, and the settle-time tree is captured too; the reported `tree` is+/// whichever of the two has the higher `tree_rss_kib`, so a `node` child that+/// exits before settle is still attributed. Used by `skill-run`.+pub async fn measure_with_tree<F, Fut>(+ scenario: &'static str,+ workload_units: usize,+ turns: Option<usize>,+ workload: F,+) -> Result<ProfileResult>+where+ F: FnOnce(Recorder) -> Fut,+ Fut: std::future::Future<Output = Result<()>>,+{+ measure_impl(scenario, workload_units, turns, true, workload).await+}++async fn measure_impl<F, Fut>(+ scenario: &'static str,+ workload_units: usize,+ turns: Option<usize>,+ sample_tree: bool,+ workload: F,+) -> Result<ProfileResult>+where+ F: FnOnce(Recorder) -> Fut,+ Fut: std::future::Future<Output = Result<()>>,+{+ tokio::time::sleep(Duration::from_millis(250)).await;+ let baseline = proc_metrics::sample_self()?;+ if let Some(seconds) = std::env::var("OPENHUMAN_PROFILE_HOLD_BEFORE_SECS")+ .ok()+ .and_then(|value| value.parse::<u64>().ok())+ .filter(|seconds| *seconds > 0)+ {+ eprintln!(+ "[library-profile] pid={} holding at baseline for {seconds}s",+ std::process::id()+ );+ tokio::time::sleep(Duration::from_secs(seconds)).await;+ }+ let sampler = PeakSampler::start(baseline.rss_kib);+ let tree_sampler = if sample_tree {+ Some(TreePeakSampler::start())+ } else {+ None+ };+ let started = Instant::now();+ let recorder = Recorder::new(baseline.rss_kib, started);+ eprintln!("[library-profile] scenario={scenario} workload starting");+ workload(recorder.clone()).await?;+ let duration_ms = started.elapsed().as_millis();+ eprintln!("[library-profile] scenario={scenario} workload done duration_ms={duration_ms}");+ tokio::time::sleep(Duration::from_millis(500)).await;+ let settled = proc_metrics::sample_self()?;+ let peak_rss_kib = sampler.stop().await.max(settled.rss_kib);++ // Fold the process-tree samples (peak-during-workload + settle-time) into a+ // single report: whichever has the higher tree RSS wins, so a short-lived+ // interpreter child that already exited by settle is still attributed.+ let tree = if let Some(tree_sampler) = tree_sampler {+ let peak_tree = tree_sampler.stop().await;+ let settle_tree = proc_metrics::sample_tree().ok();+ let best = match (peak_tree, settle_tree) {+ (Some(peak), Some(settle)) => {+ if peak.tree_rss_kib >= settle.tree_rss_kib {+ Some(peak)+ } else {+ Some(settle)+ }+ }+ (peak, settle) => peak.or(settle),+ };+ if let Some(best) = best.as_ref() {+ eprintln!(+ "[library-profile] scenario={scenario} tree_rss_kib={} child_count={}",+ best.tree_rss_kib,+ best.children.len()+ );+ }+ best.map(|sample| TreeReport::from_sample(&sample))+ } else {+ None+ };+ let checkpoints = recorder.take();+ let checkpoints = if checkpoints.is_empty() {+ None+ } else {+ Some(checkpoints)+ };+ Ok(ProfileResult {+ schema_version: 2,+ scenario,+ workload_units,+ duration_ms,+ baseline,+ settled,+ peak_rss_kib,+ retained_delta_kib: settled.rss_kib as i64 - baseline.rss_kib as i64,+ peak_delta_kib: peak_rss_kib.saturating_sub(baseline.rss_kib),+ turns,+ agents: None,+ agents_built: None,+ marginal_rss_kib_per_agent: None,+ idle_cpu_ms: None,+ turn_latency_ms: None,+ budget: None,+ checkpoints,+ subagents: None,+ tree,+ dhat: None,+ })+}diff --git a/src/bin/library_profile/main.rs b/src/bin/library_profile/main.rsnew file mode 100644index 0000000000..bbc5512bbb--- /dev/null+++ b/src/bin/library_profile/main.rs@@ -0,0 +1,128 @@+//! Hermetic, Rust-only library profiling workloads.+//!+//! This binary never enters shipped builds (it requires the default-off+//! `rss-bench` feature). It measures production code paths in fresh processes+//! with network inference replaced by a deterministic provider.+//!+//! Scenarios (`library-profile <scenario>`):+//! - `memory-ingest` — ingest 100 chat messages, drain the memory queue.+//! - `agent-turn` — a single cold agent turn (minimal library unit).+//! - `long-agent` — N warmed sequential turns with a per-turn checkpoint series.+//! - `workflow` — a real flows trigger->transform->agent graph, end to end.+//! - `cold-phases` — per-phase checkpoints of the cold bootstrap in one region.+//! - `fleet` — N live agents: marginal RSS, idle CPU, fd/thread growth, turn latency.+//! - `skill-run` — a skill step executing on a real `node` child: process-tree RSS.+//! - `subagent-storm`— K parallel researcher subagents in one instance: marginal RSS per subagent.+//!+//! stdout is ALWAYS a single pretty JSON object (the pinned schema in+//! `harness::ProfileResult`); every diagnostic goes to stderr with the stable+//! `[library-profile]` prefix.+//!+//! With the `rss-bench-dhat` feature, dhat's global allocator + profiler are+//! active: RSS/time numbers are perturbed, the result carries `"dhat": true`,+//! and a `dhat-<scenario>.json` heap profile is written under+//! `target/profile/rust-library/` (override via `OPENHUMAN_PROFILE_DHAT_OUT`).++mod harness;+mod mock;+mod scenarios;++use std::time::Duration;++use anyhow::{Context, Result};++use harness::ProfileResult;++#[cfg(feature = "rss-bench-dhat")]+#[global_allocator]+static ALLOC: dhat::Alloc = dhat::Alloc;++/// Builds the dhat profiler (feature-gated), writing to the requested path.+/// Kept alive by the caller until after the JSON result is printed.+#[cfg(feature = "rss-bench-dhat")]+fn start_dhat(scenario: &str) -> Result<dhat::Profiler> {+ let out = std::env::var("OPENHUMAN_PROFILE_DHAT_OUT")+ .unwrap_or_else(|_| format!("target/profile/rust-library/dhat-{scenario}.json"));+ if let Some(parent) = std::path::Path::new(&out).parent() {+ std::fs::create_dir_all(parent).context("create dhat output directory")?;+ }+ eprintln!("[library-profile] dhat active — heap profile -> {out}");+ Ok(dhat::Profiler::builder().file_name(&out).build())+}++async fn dispatch(scenario: &str) -> Result<ProfileResult> {+ match scenario {+ "memory-ingest" => scenarios::memory_ingest::run().await,+ "agent-turn" => scenarios::agent_turn::run().await,+ "long-agent" => scenarios::long_agent::run().await,+ "workflow" => scenarios::workflow::run().await,+ "cold-phases" => scenarios::cold_phases::run().await,+ "fleet" => scenarios::fleet::run().await,+ "skill-run" => scenarios::skill_run::run().await,+ "subagent-storm" => scenarios::subagent_storm::run().await,+ other => anyhow::bail!("unknown scenario: {other}"),+ }+}++/// Build the tokio runtime. When `OPENHUMAN_PROFILE_WORKER_THREADS` is set the+/// multi-thread runtime is built manually with that worker count (set to `2` to+/// simulate the 2 vCPU box); otherwise the standard multi-thread default runs.+fn build_runtime() -> Result<tokio::runtime::Runtime> {+ let mut builder = tokio::runtime::Builder::new_multi_thread();+ builder.enable_all();+ if let Some(workers) = std::env::var("OPENHUMAN_PROFILE_WORKER_THREADS")+ .ok()+ .and_then(|value| value.parse::<usize>().ok())+ .filter(|n| *n > 0)+ {+ eprintln!("[library-profile] tokio worker_threads={workers}");+ builder.worker_threads(workers);+ }+ builder.build().context("build tokio runtime")+}++fn main() -> Result<()> {+ // Parse args BEFORE building the runtime so `OPENHUMAN_PROFILE_WORKER_THREADS`+ // can size the worker pool (the `fleet` scenario simulates the 2 vCPU box).+ let scenario = std::env::args().nth(1).context(+ "usage: library-profile \+ <memory-ingest|agent-turn|long-agent|workflow|cold-phases|fleet|\+ skill-run|subagent-storm>",+ )?;++ // Profiler must outlive the whole run + the JSON print so its Drop writes+ // the complete heap profile last.+ #[cfg(feature = "rss-bench-dhat")]+ let _dhat = start_dhat(&scenario)?;++ eprintln!(+ "[library-profile] pid={} scenario={scenario} start",+ std::process::id()+ );++ let runtime = build_runtime()?;+ runtime.block_on(async move {+ #[cfg_attr(not(feature = "rss-bench-dhat"), allow(unused_mut))]+ let mut result = dispatch(&scenario).await?;++ #[cfg(feature = "rss-bench-dhat")]+ {+ result.dhat = Some(true);+ }++ println!("{}", serde_json::to_string_pretty(&result)?);++ if let Some(seconds) = std::env::var("OPENHUMAN_PROFILE_HOLD_SECS")+ .ok()+ .and_then(|value| value.parse::<u64>().ok())+ .filter(|seconds| *seconds > 0)+ {+ eprintln!(+ "[library-profile] pid={} holding for {seconds}s",+ std::process::id()+ );+ tokio::time::sleep(Duration::from_secs(seconds)).await;+ }+ Ok(())+ })+}diff --git a/src/bin/library_profile/mock.rs b/src/bin/library_profile/mock.rsnew file mode 100644index 0000000000..9e7c3fbef2--- /dev/null+++ b/src/bin/library_profile/mock.rs@@ -0,0 +1,498 @@+//! Deterministic offline `ChatModel` mocks installed via+//! `test_provider_override` (honoured only under the `rss-bench` feature).++use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++use async_trait::async_trait;+use openhuman_core::openhuman::inference::provider::types::{ChatResponse, ToolCall};+use tinyinference::message::{AssistantMessage, ContentBlock, Message};+use tinyinference::model::{ChatModel, ModelRequest, ModelResponse};+use tinyinference::tool::ToolCall as TinyAgentsToolCall;++/// A plain `ChatResponse` carrying only text (no tool calls).+pub fn response(text: &str) -> ChatResponse {+ ChatResponse {+ text: Some(text.into()),+ tool_calls: Vec::new(),+ usage: None,+ reasoning_content: None,+ }+}++fn joined_request(request: &ModelRequest) -> String {+ request+ .messages+ .iter()+ .map(|message| {+ let role = match message {+ Message::System(_) => "system",+ Message::User(_) => "user",+ Message::Assistant(_) => "assistant",+ Message::Tool(_) => "tool",+ };+ format!("{role}: {}", message.text())+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn model_response(response: ChatResponse) -> ModelResponse {+ let content = response+ .text+ .filter(|text| !text.is_empty())+ .map(|text| vec![ContentBlock::Text(text)])+ .unwrap_or_default();+ let tool_calls = response+ .tool_calls+ .into_iter()+ .map(|call| {+ TinyAgentsToolCall::new(+ call.id,+ call.name,+ serde_json::from_str(&call.arguments).unwrap_or(serde_json::Value::Null),+ )+ })+ .collect::<Vec<_>>();+ ModelResponse {+ finish_reason: (!tool_calls.is_empty()).then(|| "tool_calls".to_string()),+ message: AssistantMessage {+ id: None,+ content,+ tool_calls,+ usage: None,+ },+ usage: None,+ raw: None,+ resolved_model: None,+ continue_turn: None,+ served_from_cache: false,+ }+}++/// Records every prompt it sees so scenarios can assert what ran.+fn record(prompts: &Mutex<Vec<String>>, joined: &str) {+ prompts+ .lock()+ .expect("mock prompt lock")+ .push(joined.into());+}++/// Read `key` as a `u64`, falling back to `default` when unset/unparsable.+fn env_u64(key: &str, default: u64) -> u64 {+ std::env::var(key)+ .ok()+ .and_then(|value| value.parse::<u64>().ok())+ .unwrap_or(default)+}++/// Stable per-researcher marker embedded in a delegated subagent's prompt.+/// Zero-padded so `..._001` is never a substring of `..._011` — the storm mock+/// routes by exact marker containment across K up to 32.+pub fn subagent_marker(index: usize) -> String {+ format!("LIB_PROFILE_SUBAGENT_{index:03}")+}++/// The finding text a delegated researcher returns for `index`. The merge turn+/// is detected by all K of these being present in the conversation.+pub fn finding_text(index: usize) -> String {+ format!("Finding {index:03}: researcher {index} reports healthy.")+}++/// Text the orchestrator returns once it has merged every researcher finding;+/// its arrival in the parent (subconscious) conversation ends the storm turn.+pub const MERGE_SENTINEL: &str = "STORM_MERGE_COMPLETE";++/// Shared, dependency-free latency sampler driven by the standard env knobs+/// (`OPENHUMAN_PROFILE_MOCK_LATENCY_MS` mean, `OPENHUMAN_PROFILE_MOCK_JITTER_MS`+/// jitter, default `mean / 4`). Reused by both [`LatencyMock`] and+/// [`SubagentMock`] so a delegated subagent turn can carry realistic latency.+pub struct LatencyKnobs {+ mean_ms: u64,+ jitter_ms: u64,+ counter: AtomicU64,+}++impl LatencyKnobs {+ pub fn from_env() -> Self {+ let mean_ms = env_u64("OPENHUMAN_PROFILE_MOCK_LATENCY_MS", 0);+ let jitter_ms = env_u64("OPENHUMAN_PROFILE_MOCK_JITTER_MS", mean_ms / 4);+ eprintln!("[library-profile] LatencyKnobs mean_ms={mean_ms} jitter_ms={jitter_ms}");+ Self {+ mean_ms,+ jitter_ms,+ counter: AtomicU64::new(0),+ }+ }++ /// Sample `mean ± jitter` (clamped at zero) via a seeded xorshift step. The+ /// seed advances per call so successive turns get distinct latencies.+ pub fn sample_ms(&self) -> u64 {+ if self.mean_ms == 0 && self.jitter_ms == 0 {+ return 0;+ }+ let seed = self.counter.fetch_add(1, Ordering::Relaxed).wrapping_add(1);+ // xorshift64 — deterministic, dependency-free pseudo-randomness.+ let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15);+ x ^= x >> 12;+ x ^= x << 25;+ x ^= x >> 27;+ let span = self.jitter_ms.saturating_mul(2).saturating_add(1);+ let delta = (x % span) as i64 - self.jitter_ms as i64;+ (self.mean_ms as i64 + delta).max(0) as u64+ }++ /// Sleep a sampled latency and return the ms slept (0 when disabled).+ pub async fn sleep_sampled(&self) -> u64 {+ let ms = self.sample_ms();+ if ms > 0 {+ tokio::time::sleep(Duration::from_millis(ms)).await;+ }+ ms+ }+}++/// Orchestration mock: the first (orchestrator) turn emits a+/// `spawn_parallel_agents` tool call fanning out to **K** researchers; each+/// researcher turn returns its finding; the final merge turn returns plain+/// text once all K findings are present.+///+/// `width` = K parallel researchers. `new()` keeps the original two-researcher+/// shape (K = 2, no injected latency, driven from the subconscious which has no+/// `spawn_parallel_agents` — the tool call is rejected and its markers echo+/// back, which is all the `subagents` scenario asserts). `with_width(k)` drives+/// the **orchestrator directly** and scripts the full delegation chain, so it+/// must first hand off via `delegate_orchestrator`-free direct fan-out — this is+/// the `subagent-storm` fuzz-width path.+pub struct SubagentMock {+ pub prompts: Mutex<Vec<String>>,+ /// Actual wall-time (ms) of each *researcher* chat call, for percentiles.+ pub researcher_latencies_ms: Mutex<Vec<u128>>,+ width: usize,+ latency: LatencyKnobs,+ /// `true` for `with_width` (orchestrator-driven storm): route the full+ /// agent-aware chain. `false` for `new` (subconscious-driven `subagents`):+ /// the original simple routing that emits the fan-out directly.+ orchestrator_driven: bool,+ /// Increments per fan-out so successive `spawn_parallel_agents` calls carry+ /// distinct task prompts.+ spawn_nonce: AtomicU64,+}++impl SubagentMock {+ /// K researchers with per-researcher latency drawn from the env knobs, driven+ /// directly against the orchestrator agent (full agent-aware chain).+ pub fn with_width(width: usize) -> Arc<Self> {+ Arc::new(Self {+ prompts: Mutex::new(Vec::new()),+ researcher_latencies_ms: Mutex::new(Vec::new()),+ width: width.max(1),+ latency: LatencyKnobs::from_env(),+ orchestrator_driven: true,+ spawn_nonce: AtomicU64::new(0),+ })+ }++ /// Which researcher (1-based) this prompt is for, if any. A researcher+ /// prompt embeds exactly one `subagent_marker`.+ fn researcher_index(&self, joined: &str) -> Option<usize> {+ (1..=self.width).find(|&i| joined.contains(&subagent_marker(i)))+ }++ /// True once every researcher's finding is present — the merge turn.+ fn is_merge(&self, joined: &str) -> bool {+ (1..=self.width).all(|i| joined.contains(&finding_text(i)))+ }++ /// True when this call is a real researcher worker turn: exactly one task+ /// marker is present and the executing agent is neither the orchestrator nor+ /// the subconscious (their Tool Policy Boundary headers name them, and their+ /// merge/echo turns also carry every marker). The researcher agent's system+ /// prompt names it `Researcher`, so it matches neither header string.+ fn is_researcher_turn(&self, joined: &str) -> bool {+ self.researcher_index(joined).is_some()+ && !joined.contains("Agent: orchestrator")+ && !joined.contains("Agent: subconscious")+ }++ /// Build the fan-out tool call delegating to K parallel researchers. Only+ /// valid on an **orchestrator** turn — the subconscious has no+ /// `spawn_parallel_agents` tool, so we `delegate_orchestrator` there first.+ fn spawn_call(&self) -> ChatResponse {+ let nonce = self.spawn_nonce.fetch_add(1, Ordering::Relaxed);+ let tasks: Vec<serde_json::Value> = (1..=self.width)+ .map(|i| {+ serde_json::json!({+ "agent_id": "researcher",+ // The nonce keeps each fan-out's tasks byte-distinct so the+ // parallel-graph result cache can't short-circuit a re-spawn.+ "prompt": format!("{} [spawn {nonce}]: inspect subsystem {i}", subagent_marker(i)),+ "ownership": format!("scope: subsystem-{i}-spawn-{nonce}")+ })+ })+ .collect();+ ChatResponse {+ text: Some(format!("Delegating to {} researchers.", self.width)),+ tool_calls: vec![ToolCall {+ id: "profile-parallel-call".into(),+ name: "spawn_parallel_agents".into(),+ arguments: serde_json::json!({ "tasks": tasks }).to_string(),+ extra_content: None,+ }],+ usage: None,+ reasoning_content: None,+ }+ }++ /// The subconscious's first turn: hand the task to the orchestrator (which+ /// owns `spawn_parallel_agents` and allows the `researcher` subagent).+ fn delegate_orchestrator_call(&self) -> ChatResponse {+ ChatResponse {+ text: Some("Delegating to the orchestrator for a parallel research fan-out.".into()),+ tool_calls: vec![ToolCall {+ id: "profile-delegate-orchestrator".into(),+ name: "delegate_orchestrator".into(),+ arguments: serde_json::json!({+ "prompt": "Research every subsystem in parallel and merge the findings."+ })+ .to_string(),+ extra_content: None,+ }],+ usage: None,+ reasoning_content: None,+ }+ }++ /// Classify the turn by the *executing agent* (from the Tool Policy Boundary+ /// header) and script the real delegation chain:+ /// subconscious → `delegate_orchestrator` → orchestrator →+ /// `spawn_parallel_agents(K)` → K researchers → orchestrator merge →+ /// subconscious final. No latency/recording here — the async `chat` wrappers+ /// handle sleeping + latency capture around this.+ fn reply(&self, joined: &str) -> ChatResponse {+ if self.orchestrator_driven {+ return self.reply_orchestrator_driven(joined);+ }+ // Original `subagents` routing (subconscious-driven): merge once both+ // findings are present, answer a researcher's marker with its finding,+ // else emit the fan-out directly. The subconscious rejects the unknown+ // `spawn_parallel_agents`, echoing the markers back — which is all the+ // `subagents` scenario asserts.+ if self.is_merge(joined) {+ return response("Merged all researcher findings.");+ }+ if let Some(i) = self.researcher_index(joined) {+ return response(&finding_text(i));+ }+ self.spawn_call()+ }++ /// Agent-aware routing for the orchestrator-driven storm.+ fn reply_orchestrator_driven(&self, joined: &str) -> ChatResponse {+ // Researcher worker: return its finding.+ if self.is_researcher_turn(joined) {+ let i = self+ .researcher_index(joined)+ .expect("researcher turn has a marker");+ return response(&finding_text(i));+ }+ // Orchestrator: fan out, then merge once every finding is back.+ if joined.contains("Agent: orchestrator") {+ if self.is_merge(joined) {+ return response(MERGE_SENTINEL);+ }+ return self.spawn_call();+ }+ // Parent (subconscious / any other): finish once the orchestrator's+ // merged result has flowed back; otherwise delegate to the orchestrator.+ if joined.contains(MERGE_SENTINEL) {+ return response("Storm complete: merged every researcher's finding.");+ }+ self.delegate_orchestrator_call()+ }+}++#[async_trait]+impl ChatModel<()> for SubagentMock {+ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> Result<ModelResponse, tinyinference::Error> {+ Ok(model_response(+ self.dispatch(&joined_request(&request)).await,+ ))+ }+}++impl SubagentMock {+ /// Record the prompt, sleep a sampled latency for *researcher* calls (and+ /// capture their wall time), then return the classified response.+ async fn dispatch(&self, joined: &str) -> ChatResponse {+ record(&self.prompts, joined);+ let is_researcher = self.is_researcher_turn(joined);+ let started = std::time::Instant::now();+ if is_researcher {+ self.latency.sleep_sampled().await;+ }+ let resp = self.reply(joined);+ if is_researcher {+ self.researcher_latencies_ms+ .lock()+ .expect("mock latency lock")+ .push(started.elapsed().as_millis());+ }+ resp+ }+}++/// Latency-configurable text-only mock used by the `fleet` scenario. Before+/// returning its fixed answer it sleeps a sampled latency: a mean from+/// `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` (default `0` = no sleep) with jitter+/// `± OPENHUMAN_PROFILE_MOCK_JITTER_MS` (default `mean / 4`). Per-call jitter is+/// derived from a seeded xorshift counter — deterministic and dependency-free+/// (no `rand` crate).+pub struct LatencyMock {+ text: String,+ latency: LatencyKnobs,+ pub prompts: Mutex<Vec<String>>,+}++impl LatencyMock {+ /// Build from the standard env knobs.+ pub fn from_env(text: impl Into<String>) -> Arc<Self> {+ Arc::new(Self {+ text: text.into(),+ latency: LatencyKnobs::from_env(),+ prompts: Mutex::new(Vec::new()),+ })+ }+}++#[async_trait]+impl ChatModel<()> for LatencyMock {+ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> Result<ModelResponse, tinyinference::Error> {+ self.latency.sleep_sampled().await;+ let joined = joined_request(&request);+ record(&self.prompts, &joined);+ Ok(model_response(response(&self.text)))+ }+}++/// Text-only mock: always returns a fixed direct answer, never a tool call.+/// Used by the single-turn / workflow scenarios that must NOT delegate.+pub struct PlainTextMock {+ text: String,+ pub prompts: Mutex<Vec<String>>,+}++impl PlainTextMock {+ pub fn new(text: impl Into<String>) -> Arc<Self> {+ Arc::new(Self {+ text: text.into(),+ prompts: Mutex::new(Vec::new()),+ })+ }+}++#[async_trait]+impl ChatModel<()> for PlainTextMock {+ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> Result<ModelResponse, tinyinference::Error> {+ let joined = joined_request(&request);+ record(&self.prompts, &joined);+ Ok(model_response(response(&self.text)))+ }+}++/// The stdout marker the profiling `node` step prints. Its presence in the run+/// conversation proves the real interpreter child executed (not merely that a+/// tool call was emitted).+pub const NODE_MARKER: &str = "PROFILE_NODE_RESULT";++/// Skill-run mock: the first turn emits a `node_exec` tool call running a short,+/// real JavaScript computation (which spawns a genuine `node` child process);+/// once its printed JSON (carrying [`NODE_MARKER`]) rides back into the+/// conversation, the mock returns a plain final answer so the agent turn+/// completes. This scripts exactly the tool call the code-executor specialist+/// needs to spawn the language runtime whose cost we measure.+pub struct SkillRunMock {+ code: String,+ node_call_emitted: AtomicU64,+ node_output_seen: AtomicU64,+ pub prompts: Mutex<Vec<String>>,+}++impl SkillRunMock {+ pub fn new() -> Arc<Self> {+ // A real computation, a live allocation, and a ~1.2s busy-wait so the+ // child stays resident long enough for the tree sampler (15 ms poll) to+ // catch it. The JSON it prints carries NODE_MARKER.+ let code = format!(+ "const start = Date.now();\n\+ const buf = [];\n\+ let sum = 0;\n\+ for (let i = 0; i < 500000; i++) {{ buf.push(i % 97); sum += i; }}\n\+ while (Date.now() - start < 1200) {{ sum += buf.length; }}\n\+ console.log(JSON.stringify({{ marker: '{NODE_MARKER}', sum, kept: buf.length }}));\n"+ );+ Arc::new(Self {+ code,+ node_call_emitted: AtomicU64::new(0),+ node_output_seen: AtomicU64::new(0),+ prompts: Mutex::new(Vec::new()),+ })+ }++ /// True once the `node_exec` tool call has been emitted.+ pub fn node_call_emitted(&self) -> bool {+ self.node_call_emitted.load(Ordering::Relaxed) > 0+ }++ /// True once the node child's printed output flowed back into the turn —+ /// i.e. the interpreter child actually ran and printed.+ pub fn node_output_seen(&self) -> bool {+ self.node_output_seen.load(Ordering::Relaxed) > 0+ }++ fn reply(&self, joined: &str) -> ChatResponse {+ record(&self.prompts, joined);+ if joined.contains(NODE_MARKER) {+ self.node_output_seen.store(1, Ordering::Relaxed);+ return response(+ "Skill complete: the Node.js step computed the value and it checks out.",+ );+ }+ self.node_call_emitted.store(1, Ordering::Relaxed);+ ChatResponse {+ text: Some("Running the JavaScript computation step.".into()),+ tool_calls: vec![ToolCall {+ id: "profile-node-call".into(),+ name: "node_exec".into(),+ arguments: serde_json::json!({ "inline_code": self.code }).to_string(),+ extra_content: None,+ }],+ usage: None,+ reasoning_content: None,+ }+ }+}++#[async_trait]+impl ChatModel<()> for SkillRunMock {+ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> Result<ModelResponse, tinyinference::Error> {+ Ok(model_response(self.reply(&joined_request(&request))))+ }+}diff --git a/src/bin/library_profile/scenarios/agent_turn.rs b/src/bin/library_profile/scenarios/agent_turn.rsnew file mode 100644index 0000000000..ff565c8d3f--- /dev/null+++ b/src/bin/library_profile/scenarios/agent_turn.rs@@ -0,0 +1,31 @@+//! `agent-turn`: the minimal "embed OpenHuman as a library" unit — a single+//! cold agent turn built directly from config, with a plain-text mock provider+//! (no tool calls, no delegation).++use anyhow::Result;+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;++use crate::harness::{fixture, measure, ProfileResult};+use crate::mock::PlainTextMock;++pub async fn run() -> Result<ProfileResult> {+ let fixture = fixture()?;+ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();+ let mock = PlainTextMock::new("The Phoenix migration is healthy and on track.");+ let _provider = test_provider_override::install_model(mock.clone());+ eprintln!("[library-profile] agent-turn: registries ready, mock installed");++ measure("agent-turn", 1, None, |_rec| async {+ let mut agent = Agent::from_config_for_agent(&fixture.config, "subconscious")?;+ let reply = agent+ .run_single("Give me a one-line status on the Phoenix migration.")+ .await?;+ anyhow::ensure!(!reply.trim().is_empty(), "empty agent reply");+ Ok(())+ })+ .await+}diff --git a/src/bin/library_profile/scenarios/fleet.rs b/src/bin/library_profile/scenarios/fleet.rsnew file mode 100644index 0000000000..bd6dc86780--- /dev/null+++ b/src/bin/library_profile/scenarios/fleet.rs@@ -0,0 +1,297 @@+//! `fleet`: can OpenHuman host 100–1000 live agents on a 2 GB / 2 vCPU box?+//!+//! Answers four questions in one process: (1) marginal RSS per live agent+//! (`baseline → constructed`), (2) idle CPU of parked agents (CPU delta over a+//! 10 s do-nothing window), (3) thread + fd growth vs N (rides along in+//! `ProcSample`), and (4) turn latency percentiles under overlapping load.+//!+//! Env knobs:+//! - `OPENHUMAN_PROFILE_AGENTS` (default 100) — live agents to construct.+//! - `OPENHUMAN_PROFILE_TURNS` (default 3) — turns per agent under load.+//! - `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` / `_JITTER_MS` — mock reply latency.+//! - `OPENHUMAN_PROFILE_TARGET_AGENTS` (default 1000) — budget projection target.+//! - `OPENHUMAN_PROFILE_RAM_BUDGET_MIB` (default 2048) — budget ceiling.+//!+//! `OPENHUMAN_PROFILE_WORKER_THREADS` is honoured in `main` (runtime built+//! manually) rather than here.++use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use anyhow::Result;+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;+use openhuman_core::openhuman::platform::proc_metrics;++use crate::harness::{fixture, measure, FleetBudget, ProfileResult, Recorder, TurnLatency};+use crate::mock::LatencyMock;++const DEFAULT_AGENTS: usize = 100;+const DEFAULT_TURNS: usize = 3;+const DEFAULT_TARGET_AGENTS: u64 = 1000;+const DEFAULT_RAM_BUDGET_MIB: u64 = 2048;+const IDLE_WINDOW: Duration = Duration::from_secs(10);++fn env_usize(key: &str, default: usize) -> usize {+ std::env::var(key)+ .ok()+ .and_then(|v| v.parse::<usize>().ok())+ .filter(|n| *n > 0)+ .unwrap_or(default)+}++fn env_u64(key: &str, default: u64) -> u64 {+ std::env::var(key)+ .ok()+ .and_then(|v| v.parse::<u64>().ok())+ .filter(|n| *n > 0)+ .unwrap_or(default)+}++/// Raise `RLIMIT_NOFILE` toward its hard cap so N agents (each opening SQLite+/// etc.) don't exhaust the default macOS 256 soft limit. Logs old/new to stderr.+fn raise_fd_limit() {+ use std::mem::MaybeUninit;+ let mut lim = MaybeUninit::<libc::rlimit>::uninit();+ // SAFETY: `getrlimit` initialises `lim` on success.+ if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, lim.as_mut_ptr()) } != 0 {+ eprintln!("[library-profile] fleet: getrlimit(RLIMIT_NOFILE) failed");+ return;+ }+ // SAFETY: initialised by the successful `getrlimit`.+ let mut lim = unsafe { lim.assume_init() };+ let old_soft = lim.rlim_cur;+ lim.rlim_cur = lim.rlim_max;+ // SAFETY: raising the soft limit to the existing hard limit is always valid.+ let rc = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &lim) };+ eprintln!(+ "[library-profile] fleet: RLIMIT_NOFILE soft {old_soft} -> {} (hard {}) setrlimit_rc={rc}",+ lim.rlim_cur, lim.rlim_max+ );+}++/// Shared metrics captured inside the measured closure and read back after.+#[derive(Default)]+struct FleetMetrics {+ agents_built: usize,+ baseline_rss_kib: u64,+ constructed_rss_kib: u64,+ idle_cpu_ms: u64,+ latency_ms: Vec<u128>,+}++/// Percentile (nearest-rank) of an already-sorted slice. `p` in `[0,100]`.+fn percentile(sorted: &[u128], p: u128) -> u128 {+ if sorted.is_empty() {+ return 0;+ }+ let rank = ((p * sorted.len() as u128) + 99) / 100; // ceil(p% * n)+ let idx = rank.saturating_sub(1).min(sorted.len() as u128 - 1) as usize;+ sorted[idx]+}++fn latency_summary(mut samples: Vec<u128>) -> Option<TurnLatency> {+ if samples.is_empty() {+ return None;+ }+ samples.sort_unstable();+ Some(TurnLatency {+ p50: percentile(&samples, 50),+ p95: percentile(&samples, 95),+ p99: percentile(&samples, 99),+ max: *samples.last().unwrap(),+ })+}++/// Build agents sequentially, checkpointing the marginal-RSS curve. On a+/// mid-construction failure, records `construction-failed-<count>` and returns+/// what was built rather than crashing.+fn build_agents(+ config: &openhuman_core::openhuman::config::Config,+ n: usize,+ rec: &Recorder,+) -> Result<Vec<Agent>> {+ let stride = (n / 10).max(1);+ let mut agents = Vec::with_capacity(n);+ for i in 0..n {+ match Agent::from_config_for_agent(config, "subconscious") {+ Ok(agent) => agents.push(agent),+ Err(err) => {+ eprintln!(+ "[library-profile] fleet: construction failed at agent {} — {err}",+ i + 1+ );+ rec.checkpoint(format!("construction-failed-{}", agents.len()))?;+ break;+ }+ }+ let built = i + 1;+ if built % stride == 0 || built == n {+ rec.checkpoint(format!("built-{built}"))?;+ }+ }+ Ok(agents)+}++pub async fn run() -> Result<ProfileResult> {+ let agents_requested = env_usize("OPENHUMAN_PROFILE_AGENTS", DEFAULT_AGENTS);+ let turns = env_usize("OPENHUMAN_PROFILE_TURNS", DEFAULT_TURNS);+ let target_agents = env_u64("OPENHUMAN_PROFILE_TARGET_AGENTS", DEFAULT_TARGET_AGENTS);+ let ram_budget_mib = env_u64("OPENHUMAN_PROFILE_RAM_BUDGET_MIB", DEFAULT_RAM_BUDGET_MIB);++ raise_fd_limit();++ let fixture = fixture()?;+ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();+ let mock = LatencyMock::from_env("Fleet agent: nothing needs your attention.");+ let _provider = test_provider_override::install_model(mock.clone());+ eprintln!(+ "[library-profile] fleet: agents={agents_requested} turns={turns} \+ target={target_agents} budget_mib={ram_budget_mib}"+ );++ let metrics = Arc::new(Mutex::new(FleetMetrics::default()));+ let config = fixture.config.clone();+ let metrics_for_workload = Arc::clone(&metrics);++ let mut result = measure(+ "fleet",+ agents_requested,+ Some(turns),+ move |rec| async move {+ rec.checkpoint("baseline")?;+ let baseline_rss = proc_metrics::sample_self()?.rss_kib;++ // (b) construct N agents sequentially, curve visible via checkpoints.+ let mut agents = build_agents(&config, agents_requested, &rec)?;+ let agents_built = agents.len();+ rec.checkpoint("constructed")?;+ let constructed_rss = proc_metrics::sample_self()?.rss_kib;++ {+ let mut m = metrics_for_workload.lock().expect("metrics lock");+ m.agents_built = agents_built;+ m.baseline_rss_kib = baseline_rss;+ m.constructed_rss_kib = constructed_rss;+ }+ eprintln!(+ "[library-profile] fleet: built {agents_built}/{agents_requested} agents; \+ baseline_rss={baseline_rss} constructed_rss={constructed_rss}"+ );++ // (d) idle phase — park all agents, measure CPU drift over 10 s.+ rec.checkpoint("idle-start")?;+ let idle_start = proc_metrics::sample_self()?;+ tokio::time::sleep(IDLE_WINDOW).await;+ rec.checkpoint("idle-end")?;+ let idle_end = proc_metrics::sample_self()?;+ let idle_cpu_ms = (idle_end.cpu_user_ms + idle_end.cpu_system_ms)+ .saturating_sub(idle_start.cpu_user_ms + idle_start.cpu_system_ms);+ metrics_for_workload+ .lock()+ .expect("metrics lock")+ .idle_cpu_ms = idle_cpu_ms;+ eprintln!("[library-profile] fleet: idle CPU over 10s = {idle_cpu_ms} ms");++ // (e) load phase — TURNS turns per agent, one task each, staggered.+ let mut handles = Vec::with_capacity(agents.len());+ for (idx, mut agent) in agents.drain(..).enumerate() {+ let stagger = Duration::from_millis(((idx as u64) * 10).min(2000));+ handles.push(tokio::spawn(async move {+ tokio::time::sleep(stagger).await;+ let mut latencies = Vec::with_capacity(turns);+ for _ in 0..turns {+ let started = Instant::now();+ let reply = agent.run_single("Give me a one-line status update.").await;+ let elapsed = started.elapsed().as_millis();+ match reply {+ Ok(text) if !text.trim().is_empty() => latencies.push(elapsed),+ Ok(_) => eprintln!("[library-profile] fleet: empty reply agent={idx}"),+ Err(err) => {+ eprintln!("[library-profile] fleet: turn error agent={idx} — {err}")+ }+ }+ }+ latencies+ }));+ }++ let mut all_latencies = Vec::new();+ for handle in handles {+ match handle.await {+ Ok(mut latencies) => all_latencies.append(&mut latencies),+ Err(err) => eprintln!("[library-profile] fleet: task join error — {err}"),+ }+ }+ metrics_for_workload+ .lock()+ .expect("metrics lock")+ .latency_ms = all_latencies;+ rec.checkpoint("load-done")?;+ Ok(())+ },+ )+ .await?;++ // Fold fleet-specific metrics into the pinned result.+ let metrics = Arc::try_unwrap(metrics)+ .map(|m| m.into_inner().expect("metrics lock"))+ .unwrap_or_default();++ let agents_built = metrics.agents_built;+ let marginal = if agents_built > 0 {+ Some(+ (metrics.constructed_rss_kib as f64 - metrics.baseline_rss_kib as f64)+ / agents_built as f64,+ )+ } else {+ None+ };++ // (4) budget projection: settled base + marginal * target.+ let base_mib = metrics.baseline_rss_kib as f64 / 1024.0;+ let marginal_mib = marginal.unwrap_or(0.0) / 1024.0;+ let projected = base_mib + marginal_mib * target_agents as f64;+ let budget = FleetBudget {+ target_agents,+ ram_budget_mib,+ projected_rss_mib_at_target: projected,+ fits: projected <= ram_budget_mib as f64,+ };++ result.agents = Some(agents_requested);+ result.agents_built = Some(agents_built);+ result.marginal_rss_kib_per_agent = marginal;+ result.idle_cpu_ms = Some(metrics.idle_cpu_ms);+ result.turn_latency_ms = latency_summary(metrics.latency_ms);+ result.budget = Some(budget);+ Ok(result)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn percentiles_nearest_rank() {+ let mut v: Vec<u128> = (1..=100).collect();+ v.sort_unstable();+ assert_eq!(percentile(&v, 50), 50);+ assert_eq!(percentile(&v, 95), 95);+ assert_eq!(percentile(&v, 99), 99);+ assert_eq!(percentile(&v, 100), 100);+ assert_eq!(percentile(&[], 50), 0);+ assert_eq!(percentile(&[7], 99), 7);+ }++ #[test]+ fn latency_summary_none_when_empty() {+ assert!(latency_summary(Vec::new()).is_none());+ let s = latency_summary(vec![10, 20, 30]).unwrap();+ assert_eq!(s.max, 30);+ assert_eq!(s.p50, 20);+ }+}diff --git a/src/bin/library_profile/scenarios/long_agent.rs b/src/bin/library_profile/scenarios/long_agent.rsnew file mode 100644index 0000000000..7f7c88e202--- /dev/null+++ b/src/bin/library_profile/scenarios/long_agent.rs@@ -0,0 +1,53 @@+//! `long-agent`: steady-state many-turn loop on ONE warmed agent — models a+//! long-running opencompany agent. Builds the agent and runs one warm-up turn+//! BEFORE the measured region, then runs N sequential turns inside it, pushing+//! a per-turn checkpoint so the plateau/leak curve is visible.++use anyhow::Result;+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;++use crate::harness::{fixture, measure, ProfileResult};+use crate::mock::PlainTextMock;++const DEFAULT_TURNS: usize = 25;++const PROMPTS: &[&str] = &[+ "Summarise today's Phoenix migration standup in one line.",+ "What is the current staging p99 latency and error rate?",+ "Who owns the rollback runbook and on-call coordination?",+ "When does the phoenix_v2_enabled flag ramp, and what gates it?",+ "Draft a one-sentence status update for the billing-ledger team.",+];++pub async fn run() -> Result<ProfileResult> {+ let turns = std::env::var("OPENHUMAN_PROFILE_TURNS")+ .ok()+ .and_then(|value| value.parse::<usize>().ok())+ .filter(|n| *n > 0)+ .unwrap_or(DEFAULT_TURNS);++ let fixture = fixture()?;+ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();+ let mock = PlainTextMock::new("Phoenix migration is healthy; no action needed.");+ let _provider = test_provider_override::install_model(mock.clone());++ let mut agent = Agent::from_config_for_agent(&fixture.config, "subconscious")?;+ eprintln!("[library-profile] long-agent: warming agent with one pre-measure turn");+ let warm = agent.run_single("Warm-up: confirm you are ready.").await?;+ anyhow::ensure!(!warm.trim().is_empty(), "empty warm-up reply");++ measure("long-agent", turns, Some(turns), move |rec| async move {+ for i in 0..turns {+ let prompt = PROMPTS[i % PROMPTS.len()];+ let reply = agent.run_single(prompt).await?;+ anyhow::ensure!(!reply.trim().is_empty(), "empty reply on turn {i}");+ rec.checkpoint(format!("turn-{i}"))?;+ }+ Ok(())+ })+ .await+}diff --git a/src/bin/library_profile/scenarios/mod.rs b/src/bin/library_profile/scenarios/mod.rsnew file mode 100644index 0000000000..2c612d6800--- /dev/null+++ b/src/bin/library_profile/scenarios/mod.rs@@ -0,0 +1,11 @@+//! One module per profiling scenario. Each exposes a single+//! `run() -> Result<ProfileResult>` entry point dispatched from `main`.++pub mod agent_turn;+pub mod cold_phases;+pub mod fleet;+pub mod long_agent;+pub mod memory_ingest;+pub mod skill_run;+pub mod subagent_storm;+pub mod workflow;diff --git a/src/bin/library_profile/scenarios/skill_run.rs b/src/bin/library_profile/scenarios/skill_run.rsnew file mode 100644index 0000000000..87efa05279--- /dev/null+++ b/src/bin/library_profile/scenarios/skill_run.rs@@ -0,0 +1,241 @@+//! `skill-run`: the true, process-*tree* cost of a skill step that executes on+//! a real language runtime — the interpreter child process included — and the+//! regression instrument for the shared runtime pool (issue #5106).+//!+//! ## What it actually runs+//!+//! A skill run's orchestrator (`spawn_workflow_run_background` → the+//! `orchestrator` agent) deliberately owns **no** `node_exec` tool: the+//! chat-tier orchestrator never executes code itself, it delegates every code+//! step to the `code_executor` specialist (the only builtin whose allow-list+//! carries `node_exec` / `npm_exec`). So the agent that genuinely spawns the+//! language runtime *is* `code_executor`. This scenario drives that specialist+//! directly — one turn, one scripted `node_exec` call — which is the real+//! node-executing path, not a bare `std::process` spawn.+//!+//! ## Concurrency knob (K parallel skill runs)+//!+//! `OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY=K` (default 1) drives **K**+//! `code_executor` turns in parallel, each emitting its own `node_exec` call.+//! The point of #5106: with the runtime pool **on**, K concurrent skill runs+//! share a small bounded set of warm `node` workers, so the process tree grows+//! by ~one pooled worker — **not** K interpreters. This scenario asserts that+//! (`tree.child_count <= max_workers`) whenever pooling is on and K > 1, so a+//! regression that reintroduces per-run forking fails the profiling suite.+//!+//! Toggle for an A/B baseline:+//!+//! * `OPENHUMAN_PROFILE_SKILL_RUN_POOL=off` — disable the pool (legacy per-call+//! spawn); the tree then shows ~K resident `node` children at peak.+//! * `OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS=W` — pool size (default 1, for a+//! tight, deterministic bound).+//!+//! ## No interpreter download+//!+//! `node.prefer_system = true` (the default) means a host `node` whose **major**+//! matches the configured target is reused rather than downloaded. This+//! scenario **requires** a system `node` and bails with a clear stderr error ++//! nonzero exit if none is on `PATH` — it must never pull a runtime.+//!+//! The measured cost lands in `result.tree` (`tree_rss_kib`, `child_count`,+//! per-child RSS), captured at the workload peak.++use anyhow::{Context, Result};+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::config::Config;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;+use openhuman_core::openhuman::security::AutonomyLevel;++use crate::harness::{fixture, measure_with_tree, EnvGuard, ProfileResult};+use crate::mock::SkillRunMock;++/// The specialist agent that owns `node_exec` and spawns the runtime child.+const CODE_AGENT: &str = "code_executor";++/// Probe for a usable system `node`. Returns its version on success; on failure+/// prints a clear `[library-profile]` stderr error and returns `Err` (which+/// propagates to a nonzero process exit). We must NOT download an interpreter.+fn require_system_node() -> Result<String> {+ match std::process::Command::new("node").arg("--version").output() {+ Ok(output) if output.status.success() => {+ let version = String::from_utf8_lossy(&output.stdout).trim().to_string();+ eprintln!("[library-profile] skill-run: using system node {version}");+ Ok(version)+ }+ Ok(output) => {+ let stderr = String::from_utf8_lossy(&output.stderr);+ eprintln!(+ "[library-profile] skill-run: `node --version` failed (status {:?}): {stderr}",+ output.status.code()+ );+ anyhow::bail!("skill-run requires a working system `node`, but `node --version` failed")+ }+ Err(err) => {+ eprintln!(+ "[library-profile] skill-run: `node` not found on PATH: {err}. Install Node.js — \+ the profiler will NOT download an interpreter."+ );+ anyhow::bail!("skill-run requires a system `node` on PATH; none found")+ }+ }+}++/// Read a `>= 1` usize from the environment. Absent ⇒ `default`; present but not+/// a positive integer ⇒ a hard error (silently coercing a bad `0`/garbage value+/// would change the workload and bypass the `K > 1` pool gate).+fn env_usize(key: &str, default: usize) -> Result<usize> {+ match std::env::var(key) {+ Err(_) => Ok(default),+ Ok(raw) => {+ let n: usize = raw+ .trim()+ .parse()+ .with_context(|| format!("{key}={raw:?} is not a valid integer"))?;+ anyhow::ensure!(n >= 1, "{key}={raw:?} must be >= 1");+ Ok(n)+ }+ }+}++/// Apply the `[runtime_pool]` settings to the in-memory fixture config. The exec+/// tools snapshot `config.runtime_pool` at construction (the pool config is+/// injected, never re-read from disk on the hot path), so mutating the config+/// the agent is built from is what toggles pooling for the scenario.+fn apply_pool_config(config: &mut Config, pool_enabled: bool, workers: usize) {+ config.runtime_pool.enabled = pool_enabled;+ config.runtime_pool.node.max_workers = workers;+ config.runtime_pool.node.idle_ttl_secs = 300;+ config.runtime_pool.node.recycle_after_jobs = 0;+}++pub async fn run() -> Result<ProfileResult> {+ // Hard requirement: a system node must be present (no download).+ require_system_node()?;++ let concurrency = env_usize("OPENHUMAN_PROFILE_SKILL_RUN_CONCURRENCY", 1)?;+ let pool_enabled = std::env::var("OPENHUMAN_PROFILE_SKILL_RUN_POOL")+ .map(|v| !v.trim().eq_ignore_ascii_case("off"))+ .unwrap_or(true);+ let pool_workers = env_usize("OPENHUMAN_PROFILE_SKILL_RUN_POOL_WORKERS", 1)?;++ // `node_exec` is a Write-class acting tool. Full autonomy keeps the gate+ // from parking the turn on approval; the gate is also opted out explicitly.+ let mut fixture = fixture()?;+ fixture.config.autonomy.level = AutonomyLevel::Full;+ apply_pool_config(&mut fixture.config, pool_enabled, pool_workers);+ let _approval_env = EnvGuard::set("OPENHUMAN_APPROVAL_GATE", "0");++ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();++ let mock = SkillRunMock::new();+ let _provider = test_provider_override::install_model(mock.clone());+ eprintln!(+ "[library-profile] skill-run: registries ready, node_exec mock installed \+ (agent={CODE_AGENT}, concurrency={concurrency}, pool={}, pool_workers={pool_workers})",+ if pool_enabled { "on" } else { "off" }+ );++ let mock_for_workload = mock.clone();+ let config = fixture.config.clone();+ let mut result = measure_with_tree("skill-run", concurrency, None, move |rec| async move {+ rec.checkpoint("turn-start")?;+ // Drive K code_executor turns concurrently. `join_all` gives real+ // process-level parallelism (each node_exec awaits its own child /+ // pooled job) without requiring the agent future to be `Send`.+ let futures = (0..concurrency).map(|idx| {+ let config = config.clone();+ async move {+ let mut agent = Agent::from_config_for_agent(&config, CODE_AGENT)+ .with_context(|| format!("building code_executor agent #{idx}"))?;+ let reply = agent+ .run_single(+ "Run a short JavaScript computation with node_exec and report the JSON it prints.",+ )+ .await+ .with_context(|| format!("code_executor turn #{idx}"))?;+ anyhow::ensure!(!reply.trim().is_empty(), "empty code_executor reply #{idx}");+ Ok::<(), anyhow::Error>(())+ }+ });+ let outcomes = futures::future::join_all(futures).await;+ for outcome in outcomes {+ outcome?;+ }+ rec.checkpoint("turn-done")?;+ anyhow::ensure!(+ mock_for_workload.node_call_emitted(),+ "the node_exec tool call was never emitted"+ );+ anyhow::ensure!(+ mock_for_workload.node_output_seen(),+ "the node child's output never flowed back — the interpreter child did not run/print"+ );+ Ok(())+ })+ .await?;++ match result.tree.as_ref() {+ Some(tree) if tree.child_count >= 1 => {+ eprintln!(+ "[library-profile] skill-run: captured tree_rss_kib={} child_count={} \+ concurrency={concurrency} pool={} children={:?}",+ tree.tree_rss_kib,+ tree.child_count,+ if pool_enabled { "on" } else { "off" },+ tree.children+ );+ }+ Some(tree) => {+ eprintln!(+ "[library-profile] skill-run: tree captured but no child resident at peak \+ (tree_rss_kib={}). With the pool on this is expected between jobs; with the \+ pool off the node child may have been too short-lived.",+ tree.tree_rss_kib+ );+ }+ None => {+ eprintln!("[library-profile] skill-run: WARNING no process-tree sample captured");+ }+ }++ // DoD gate (#5106): with pooling on, K concurrent skill runs must not fork K+ // interpreters — the tree grows by ~one pooled worker. A regression that+ // reintroduces per-run forking makes child_count scale with K and fails here.+ if pool_enabled && concurrency > 1 {+ // Require a real measurement: a missing tree or zero children would let+ // the gate "pass" without ever observing an interpreter. With the+ // scenario's 300 s idle TTL the pooled worker is resident at sample time,+ // so this must hold.+ let tree = result.tree.as_ref().ok_or_else(|| {+ anyhow::anyhow!(+ "pool gate: no process-tree sample captured for K={concurrency}; cannot verify \+ the pooled worker (tree sampling is required for this gate)"+ )+ })?;+ anyhow::ensure!(+ tree.child_count >= 1,+ "pool gate: process tree captured zero interpreter children at K={concurrency}; \+ the pooled worker was not observed"+ );+ anyhow::ensure!(+ tree.child_count <= pool_workers,+ "runtime pool failed to bound interpreters: child_count={} exceeds max_workers={} \+ at concurrency K={} — expected warm-worker reuse, not K forked children",+ tree.child_count,+ pool_workers,+ concurrency+ );+ eprintln!(+ "[library-profile] skill-run: POOL OK — {} node worker(s) served {concurrency} \+ concurrent skill runs (would be ~{concurrency} interpreters unpooled)",+ tree.child_count+ );+ }++ // Fold in scenario-visible fields (schema stays additive).+ result.workload_units = concurrency;+ Ok(result)+}diff --git a/src/bin/library_profile/scenarios/subagent_storm.rs b/src/bin/library_profile/scenarios/subagent_storm.rsnew file mode 100644index 0000000000..32fcbe80ac--- /dev/null+++ b/src/bin/library_profile/scenarios/subagent_storm.rs@@ -0,0 +1,186 @@+//! `subagent-storm`: fuzz the *width* of delegation inside ONE core instance.+//!+//! One orchestrator turn fans out to **K** parallel researcher subagents (all+//! in-process tokio tasks, not child processes) via `spawn_parallel_agents`.+//! K comes from `OPENHUMAN_PROFILE_SUBAGENTS` (default 8; tested up to 32), and+//! each researcher carries per-subagent mock latency drawn from the shared+//! `OPENHUMAN_PROFILE_MOCK_LATENCY_MS` / `_JITTER_MS` knobs.+//!+//! ## Measurement shape (and a hard constraint we hit)+//!+//! The intended shape was: prewarm one width-K fan-out, then measure a second on+//! the same warm process so the delta is attributable to the K children rather+//! than cold bootstrap. That is **not achievable** here: the parallel-spawn+//! machinery is effectively one-shot per process. Once a fan-out's run ledger is+//! finalized, a second `spawn_parallel_agents` returns an empty result and the+//! orchestrator just re-calls the tool without re-running the workers. Worse,+//! merely *constructing* an orchestrator/researcher agent beforehand perturbs+//! the fan-out the same way. The only shape that reliably executes all K real+//! researcher subagents is a single fan-out as the process's first agent+//! activity.+//!+//! So this scenario measures exactly that: one cold width-K fan-out. `retained_delta_kib`+//! therefore includes the shared per-process bootstrap (~20–30 MiB every+//! scenario pays once) amortized across K, so a single run's+//! `marginal_rss_kib_per_agent = retained_delta_kib / K` is an **upper bound**,+//! not the true marginal. Read the true marginal by comparing runs: the fixed+//! bootstrap amortizes, so `(retained(K₂) - retained(K₁)) / (K₂ - K₁)` across+//! two widths (e.g. K=8 vs K=32) isolates the genuine per-additional-subagent+//! cost. `peak_delta_kib` additionally captures the K-concurrent peak.+//!+//! Reported fields: `subagents = K`, `marginal_rss_kib_per_agent` (retained/K,+//! upper bound), `checkpoints` (baseline → storm-turn-done), and+//! `turn_latency_ms` (percentiles across the K researcher child executions).+//! The workload asserts all K researcher subagents actually executed.++use anyhow::Result;+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;++use crate::harness::{fixture, measure, ProfileResult, TurnLatency};+use crate::mock::{subagent_marker, SubagentMock};++const DEFAULT_SUBAGENTS: usize = 8;++/// The orchestrator's top-level task. The mock ignores the wording and always+/// fans out to K researchers.+const STORM_PROMPT: &str = "Research every subsystem in parallel and merge the findings.";++/// Positive identity anchor for a researcher *worker* turn — its own system+/// prompt names it. Distinguishes a real worker from the orchestrator turns that+/// also echo every task marker in the fan-out tool call / result.+const RESEARCHER_IDENTITY: &str = "You are the **Researcher** agent";++fn env_usize(key: &str, default: usize) -> usize {+ std::env::var(key)+ .ok()+ .and_then(|value| value.parse::<usize>().ok())+ .filter(|n| *n > 0)+ .unwrap_or(default)+}++/// Nearest-rank percentile of an already-sorted slice. `p` in `[0, 100]`.+fn percentile(sorted: &[u128], p: u128) -> u128 {+ if sorted.is_empty() {+ return 0;+ }+ let rank = ((p * sorted.len() as u128) + 99) / 100; // ceil(p% * n)+ let idx = rank.saturating_sub(1).min(sorted.len() as u128 - 1) as usize;+ sorted[idx]+}++fn latency_summary(mut samples: Vec<u128>) -> Option<TurnLatency> {+ if samples.is_empty() {+ return None;+ }+ samples.sort_unstable();+ Some(TurnLatency {+ p50: percentile(&samples, 50),+ p95: percentile(&samples, 95),+ p99: percentile(&samples, 99),+ max: *samples.last().unwrap(),+ })+}++pub async fn run() -> Result<ProfileResult> {+ let width = env_usize("OPENHUMAN_PROFILE_SUBAGENTS", DEFAULT_SUBAGENTS);++ let mut fixture = fixture()?;+ // `spawn_parallel_agents` rejects a fan-out wider than the orchestrator's+ // `max_parallel_tools` (default 4). Raise it to K so the full width actually+ // spawns instead of erroring back to a re-spawn loop.+ fixture.config.agent.max_parallel_tools = width.max(4);+ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();++ let mock = SubagentMock::with_width(width);+ let _provider = test_provider_override::install_model(mock.clone());+ eprintln!("[library-profile] subagent-storm: width={width} — single cold width-K fan-out");++ // We drive the `orchestrator` agent directly: it owns `spawn_parallel_agents`+ // and allows the `researcher` subagent (the chat-tier subconscious has+ // neither, and would reject the fan-out). One orchestrator turn fans out to+ // K real researcher subagents via the parallel graph. This fan-out MUST be+ // the process's first agent activity — see the module docs for why prewarming+ // is not possible here.+ let config = fixture.config.clone();+ let mock_for_workload = mock.clone();+ let mut result = measure("subagent-storm", width, None, move |rec| async move {+ rec.checkpoint("baseline")?;+ let mut agent = Agent::from_config_for_agent(&config, "orchestrator")?;+ let reply = agent.run_single(STORM_PROMPT).await?;+ rec.checkpoint("storm-turn-done")?;+ anyhow::ensure!(!reply.trim().is_empty(), "empty storm-turn response");+ // Every one of the K researcher subagents must have actually executed as+ // its own worker turn: for each i there must be a prompt that carries the+ // researcher identity anchor AND that researcher's task marker — not+ // merely an orchestrator turn echoing every marker in the fan-out call.+ let prompts = mock_for_workload.prompts.lock().expect("mock prompt lock");+ for i in 1..=width {+ anyhow::ensure!(+ prompts+ .iter()+ .any(|p| p.contains(RESEARCHER_IDENTITY) && p.contains(&subagent_marker(i))),+ "researcher subagent {i}/{width} never executed as its own worker turn"+ );+ }+ Ok(())+ })+ .await?;++ // Marginal per subagent = retained / K. An UPPER BOUND: `retained_delta_kib`+ // still carries the one-time per-process bootstrap (see module docs), so the+ // true marginal is the cross-width delta `(retained(K₂)-retained(K₁))/(K₂-K₁)`.+ let marginal = if width > 0 {+ Some(result.retained_delta_kib as f64 / width as f64)+ } else {+ None+ };+ let latencies = mock+ .researcher_latencies_ms+ .lock()+ .expect("mock latency lock")+ .clone();+ eprintln!(+ "[library-profile] subagent-storm: width={width} retained_delta_kib={} \+ marginal_rss_kib_per_agent={:?} researcher_executions={}",+ result.retained_delta_kib,+ marginal,+ latencies.len()+ );++ result.subagents = Some(width);+ result.marginal_rss_kib_per_agent = marginal;+ result.turn_latency_ms = latency_summary(latencies);+ Ok(result)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn percentiles_nearest_rank() {+ let v: Vec<u128> = (1..=100).collect();+ assert_eq!(percentile(&v, 50), 50);+ assert_eq!(percentile(&v, 95), 95);+ assert_eq!(percentile(&v, 99), 99);+ assert_eq!(percentile(&v, 100), 100);+ assert_eq!(percentile(&[], 50), 0);+ }++ #[test]+ fn latency_summary_none_when_empty() {+ assert!(latency_summary(Vec::new()).is_none());+ let s = latency_summary(vec![10, 20, 30]).unwrap();+ assert_eq!(s.max, 30);+ assert_eq!(s.p50, 20);+ }++ #[test]+ fn env_usize_falls_back_on_zero_or_unset() {+ assert_eq!(env_usize("OPENHUMAN_PROFILE_STORM_UNSET_XYZ", 8), 8);+ }+}diff --git a/src/bin/library_profile/scenarios/workflow.rs b/src/bin/library_profile/scenarios/workflow.rsnew file mode 100644index 0000000000..2ae42e6fb7--- /dev/null+++ b/src/bin/library_profile/scenarios/workflow.rs@@ -0,0 +1,71 @@+//! `workflow`: run a real flows-domain workflow end to end. A+//! trigger -> transform -> agent graph is created OUTSIDE the measured region+//! (recorded as a checkpoint), then `flows_run` is measured as the workload.+//! The agent node's LLM routes through the plain-text mock provider.++use anyhow::Result;+use openhuman_core::openhuman::agent::harness::AgentDefinitionRegistry;+use openhuman_core::openhuman::flows::ops::{flows_create, flows_run};+use openhuman_core::openhuman::flows::FlowRunTrigger;+use openhuman_core::openhuman::inference::provider::factory::test_provider_override;+use serde_json::json;++use crate::harness::{fixture, measure, ProfileResult};+use crate::mock::PlainTextMock;++pub async fn run() -> Result<ProfileResult> {+ let fixture = fixture()?;+ openhuman_core::core::bus::init().await.expect("bus init");+ openhuman_core::openhuman::agent::bus::register_agent_handlers();+ let _ = AgentDefinitionRegistry::init_global_builtins();+ let mock = PlainTextMock::new("Phoenix migration status: healthy, ramp on Friday.");+ let _provider = test_provider_override::install_model(mock.clone());++ let graph = json!({+ "name": "profile-workflow",+ "nodes": [+ { "id": "t", "kind": "trigger", "name": "Trigger" },+ { "id": "prep", "kind": "transform", "name": "Prep",+ "config": { "set": { "topic": "Phoenix migration" } } },+ { "id": "summarize", "kind": "agent", "name": "Summarize",+ "config": { "agent_ref": "researcher",+ "prompt": "Summarise the Phoenix migration status in one line." } }+ ],+ "edges": [+ { "from_node": "t", "to_node": "prep" },+ { "from_node": "prep", "to_node": "summarize" }+ ]+ });++ eprintln!("[library-profile] workflow: creating flow (outside measured region)");+ let flow = flows_create(&fixture.config, "profile-workflow".into(), graph, false)+ .await+ .map_err(anyhow::Error::msg)?+ .value;+ let flow_id = flow.id.clone();++ measure("workflow", 1, None, move |_rec| async move {+ let outcome = flows_run(+ &fixture.config,+ &flow_id,+ json!({ "topic": "Phoenix migration" }),+ serde_json::Map::new(),+ FlowRunTrigger::Rpc,+ )+ .await+ .map_err(anyhow::Error::msg)?;+ let output = outcome.value.get("output");+ anyhow::ensure!(+ output.is_some() && !output.unwrap().is_null(),+ "workflow run produced no output: {}",+ outcome.value+ );+ anyhow::ensure!(+ outcome.value.get("note").is_none(),+ "workflow with an actionable agent node unexpectedly reported nothing-to-run: {}",+ outcome.value+ );+ Ok(())+ })+ .await+}diff --git a/src/bin/rss_bench.rs b/src/bin/rss_bench.rsnew file mode 100644index 0000000000..70d2d3b51c--- /dev/null+++ b/src/bin/rss_bench.rs@@ -0,0 +1,424 @@+//! `rss-bench` — steady-state RSS benchmark for an embedded `openhuman_core`+//! agent roster (#5046).+//!+//! Mirrors the OpenCompany embedding contract: a bare [`Agent`] built directly+//! via [`Agent::builder`] (no `CoreBuilder`, no RPC, no background services)+//! with an injected mock model, an in-process `"none"` memory backend, and a+//! per-agent temp workspace. Builds a 1-agent and an 8-agent roster, runs one+//! deterministic warm-up turn per agent to fault in lazy allocations, settles,+//! then samples `/proc/self/{status,smaps_rollup}`.+//!+//! Two modes:+//! * `--child --roster N` builds one roster in a **fresh process**, warms up,+//! settles, and prints one [`ProcSample`] JSON line. This is the isolated+//! measured workload.+//! * default (parent) re-execs itself `--repeat` times per roster size to get+//! independent cold samples, aggregates, writes the raw JSON report+//! (`--out`), and prints a human summary.+//!+//! Gated behind the default-OFF `rss-bench` feature so no benchmark code enters+//! the shipped desktop/library build. Build & run:+//! `cargo build --release --features rss-bench --bin rss-bench`.+//!+//! The pure sampling/aggregation logic lives in+//! [`openhuman_core::openhuman::platform::proc_metrics`]; this binary is the fixture ++//! process driver.++use anyhow::{Context, Result};+use async_trait::async_trait;+use openhuman_core::openhuman::agent::dispatcher::NativeToolDispatcher;+use openhuman_core::openhuman::agent::Agent;+use openhuman_core::openhuman::memory::{+ Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts,+};+use openhuman_core::openhuman::platform::proc_metrics::{+ self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,+ RSS_HARD_CAP_KIB,+};+use openhuman_core::openhuman::tools::{Tool, ToolResult};+use std::path::PathBuf;+use std::process::Stdio;+use std::sync::Arc;+use std::time::Duration;+use tempfile::TempDir;+use tinyinference::model::{ChatModel, ModelRequest, ModelResponse};++/// Roster sizes measured by default: the 1-agent baseline and the+/// representative 8-agent company roster from #5046.+const DEFAULT_ROSTER_SIZES: &[usize] = &[1, 8];+/// Fresh processes sampled per roster size (≥ 5 per the issue).+const DEFAULT_REPEAT: usize = 5;+/// Per-child wall-clock budget. A child does bounded work (build a roster, one+/// warm-up turn, a ≤2 s settle), so anything beyond this is a stall — kill it and+/// fail the run rather than letting one bad child block the whole benchmark until+/// the outer CI job timeout.+const CHILD_TIMEOUT: Duration = Duration::from_secs(120);++/// Model that never touches the network: returns a fixed assistant message+/// with a `stop` shape (no tool calls) so a turn completes in one round-trip.+struct MockModel;++#[async_trait]+impl ChatModel<()> for MockModel {+ async fn invoke(+ &self,+ _state: &(),+ _request: ModelRequest,+ ) -> tinyinference::Result<ModelResponse> {+ Ok(ModelResponse::assistant("ok"))+ }+}++/// Trivial host-supplied tool so the roster mirrors a real embedding (the host+/// injects its own tools). Never invoked — the model returns no tool calls.+struct EchoTool;++#[async_trait]+impl Tool for EchoTool {+ fn name(&self) -> &str {+ "echo"+ }++ fn description(&self) -> &str {+ "echo"+ }++ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({ "type": "object" })+ }++ async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {+ Ok(ToolResult::success("echo"))+ }+}++/// Zero-allocation no-op `Memory` for the fixture.+///+/// The benchmark measures a bare agent under the OpenCompany embedding contract+/// (host supplies its own `Memory` over its context store), *not* a memory+/// store. `create_memory(MemoryConfig{ backend: "none", .. })` does **not**+/// select a no-op backend — it always builds a `UnifiedMemory` (SQLite + the+/// default cloud embedder), which would inflate the measured RSS with+/// memory-store setup. Injecting a real no-op keeps the reading on the agent+/// harness itself.+struct NoopMemory;++#[async_trait]+impl Memory for NoopMemory {+ fn name(&self) -> &str {+ "noop"+ }+ async fn store(+ &self,+ _namespace: &str,+ _key: &str,+ _content: &str,+ _category: MemoryCategory,+ _session_id: Option<&str>,+ ) -> Result<()> {+ Ok(())+ }+ async fn recall(+ &self,+ _query: &str,+ _limit: usize,+ _opts: RecallOpts<'_>,+ ) -> Result<Vec<MemoryEntry>> {+ Ok(Vec::new())+ }+ async fn get(&self, _namespace: &str, _key: &str) -> Result<Option<MemoryEntry>> {+ Ok(None)+ }+ async fn list(+ &self,+ _namespace: Option<&str>,+ _category: Option<&MemoryCategory>,+ _session_id: Option<&str>,+ ) -> Result<Vec<MemoryEntry>> {+ Ok(Vec::new())+ }+ async fn forget(&self, _namespace: &str, _key: &str) -> Result<bool> {+ Ok(false)+ }+ async fn namespace_summaries(&self) -> Result<Vec<NamespaceSummary>> {+ Ok(Vec::new())+ }+ async fn count(&self) -> Result<usize> {+ Ok(0)+ }+ async fn health_check(&self) -> bool {+ true+ }+}++/// A built roster plus the temp workspaces that must outlive it — dropping the+/// `TempDir`s would delete the agents' workspaces mid-measurement.+struct Roster {+ agents: Vec<Agent>,+ _workspaces: Vec<TempDir>,+}++/// Build `n` bare agents, each with its own temp workspace, mock model,+/// `"none"` memory backend, and a single host-supplied tool.+fn build_roster(n: usize) -> Result<Roster> {+ let mut agents = Vec::with_capacity(n);+ let mut workspaces = Vec::with_capacity(n);+ for i in 0..n {+ let workspace = TempDir::new().context("create temp workspace")?;+ let path = workspace.path().to_path_buf();++ let memory: Arc<dyn Memory> = Arc::new(NoopMemory);++ let agent = Agent::builder()+ .chat_model(Arc::new(MockModel))+ .tools(vec![Box::new(EchoTool)])+ .memory(memory)+ .tool_dispatcher(Box::new(NativeToolDispatcher))+ .model_name("bench-mock".into())+ .agent_definition_name(format!("bench-{i}"))+ .workspace_dir(path.clone())+ .action_dir(path)+ .auto_save(false)+ .build()+ .context("build bench agent")?;+ agents.push(agent);+ workspaces.push(workspace);+ }+ Ok(Roster {+ agents,+ _workspaces: workspaces,+ })+}++/// One deterministic warm-up turn per agent, forcing first-touch allocations+/// (prompt build, tokenizer, model seam) to fault in before measuring.+async fn warm_up(roster: &mut Roster) -> Result<()> {+ for agent in &mut roster.agents {+ let _ = agent.turn("warmup").await.context("warm-up turn")?;+ }+ Ok(())+}++/// Poll RSS until it stops climbing (Δ < 256 KiB between reads ~200 ms apart)+/// or a 2 s cap, draining async task-allocation jitter. No-op off Linux.+async fn settle() {+ let deadline = tokio::time::Instant::now() + Duration::from_secs(2);+ let mut last = proc_metrics::sample_self().map(|s| s.rss_kib).unwrap_or(0);+ loop {+ tokio::time::sleep(Duration::from_millis(200)).await;+ let now = proc_metrics::sample_self()+ .map(|s| s.rss_kib)+ .unwrap_or(last);+ if now.abs_diff(last) < 256 || tokio::time::Instant::now() >= deadline {+ break;+ }+ last = now;+ }+}++/// Child mode: build one roster in this fresh process, warm up, settle, sample,+/// and print the sample as a single JSON line on stdout.+async fn run_child(roster_size: usize) -> Result<()> {+ // Diagnostics go to stderr so they never corrupt the single JSON line the+ // parent parses from stdout.+ eprintln!("[rss-bench] child: building {roster_size}-agent roster");+ let mut roster = build_roster(roster_size)?;+ eprintln!("[rss-bench] child: warming up {roster_size} agent(s)");+ warm_up(&mut roster).await?;+ eprintln!("[rss-bench] child: settling");+ settle().await;+ let sample = proc_metrics::sample_self()?;+ eprintln!(+ "[rss-bench] child: sampled rss={}KiB threads={}",+ sample.rss_kib, sample.threads+ );+ println!("{}", serde_json::to_string(&sample)?);+ drop(roster); // keep the roster alive until after the sample is taken+ Ok(())+}++/// Parent mode: re-exec the child `repeat` times per roster size, aggregate, and+/// write the report.+async fn run_parent(out: Option<PathBuf>, repeat: usize, roster_sizes: &[usize]) -> Result<()> {+ let exe = std::env::current_exe().context("resolve current exe")?;+ let mut rosters = Vec::with_capacity(roster_sizes.len());+ for &size in roster_sizes {+ let mut samples = Vec::with_capacity(repeat);+ for run in 0..repeat {+ eprintln!("[rss-bench] spawn child roster={size} run={run}");+ // `kill_on_drop` + a `timeout` around `wait_with_output` gives a+ // robust kill-and-reap: on timeout the cancelled future drops the+ // child, `kill_on_drop` sends SIGKILL, and the tokio runtime reaps it.+ let child = tokio::process::Command::new(&exe)+ .arg("--child")+ .arg("--roster")+ .arg(size.to_string())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true)+ .spawn()+ .with_context(|| format!("spawn child roster={size} run={run}"))?;+ let output = match tokio::time::timeout(CHILD_TIMEOUT, child.wait_with_output()).await {+ Ok(res) => res.with_context(|| format!("await child roster={size} run={run}"))?,+ Err(_) => {+ eprintln!(+ "[rss-bench] child roster={size} run={run} timed out after {}s; killed",+ CHILD_TIMEOUT.as_secs()+ );+ anyhow::bail!(+ "child roster={size} run={run} timed out after {}s",+ CHILD_TIMEOUT.as_secs()+ );+ }+ };+ if !output.status.success() {+ eprintln!("[rss-bench] child roster={size} run={run} exited non-zero");+ anyhow::bail!(+ "child roster={size} run={run} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ let line = stdout+ .lines()+ .rev()+ .find(|l| !l.trim().is_empty())+ .unwrap_or("")+ .trim();+ let sample: ProcSample = serde_json::from_str(line)+ .with_context(|| format!("parse child sample (roster={size}): {line:?}"))?;+ eprintln!(+ "[rss-bench] child roster={size} run={run} ok rss={}KiB",+ sample.rss_kib+ );+ samples.push(sample);+ }+ rosters.push(RosterResult::from_samples(size, samples));+ }++ let report = BenchReport {+ schema_version: REPORT_SCHEMA_VERSION,+ git_sha: git_sha(),+ kernel: kernel(),+ rss_budget_kib: RSS_BUDGET_KIB,+ rss_hard_cap_kib: RSS_HARD_CAP_KIB,+ rosters,+ };++ if let Some(path) = out {+ std::fs::write(&path, serde_json::to_string_pretty(&report)?)+ .with_context(|| format!("write report to {}", path.display()))?;+ }+ println!("{}", proc_metrics::human_summary(&report));+ Ok(())+}++/// Best-effort commit id for the report header (`GITHUB_SHA` in CI).+fn git_sha() -> String {+ std::env::var("GITHUB_SHA").unwrap_or_else(|_| "unknown".into())+}++/// Best-effort kernel version for the report header.+fn kernel() -> String {+ std::fs::read_to_string("/proc/sys/kernel/osrelease")+ .map(|s| s.trim().to_string())+ .unwrap_or_else(|_| std::env::consts::OS.to_string())+}++/// Minimal flag parse — avoids a clap dependency for four flags.+struct Args {+ child: bool,+ roster: usize,+ repeat: usize,+ out: Option<PathBuf>,+}++fn parse_args() -> Result<Args> {+ let mut child = false;+ let mut roster = 1usize;+ let mut repeat = DEFAULT_REPEAT;+ let mut out = None;+ let mut it = std::env::args().skip(1);+ while let Some(arg) = it.next() {+ match arg.as_str() {+ "--child" => child = true,+ "--roster" => {+ roster = it+ .next()+ .context("--roster needs a value")?+ .parse()+ .context("--roster value")?;+ }+ "--repeat" => {+ repeat = it+ .next()+ .context("--repeat needs a value")?+ .parse()+ .context("--repeat value")?;+ }+ "--out" => out = Some(PathBuf::from(it.next().context("--out needs a path")?)),+ other => anyhow::bail!("unknown argument: {other}"),+ }+ }+ Ok(Args {+ child,+ roster,+ repeat,+ out,+ })+}++#[tokio::main]+async fn main() -> Result<()> {+ let args = parse_args()?;+ if args.child {+ run_child(args.roster).await+ } else {+ run_parent(args.out, args.repeat, DEFAULT_ROSTER_SIZES).await+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn build_roster_constructs_bare_agents_with_isolated_workspaces() {+ let roster = build_roster(8).expect("8-agent roster builds");+ assert_eq!(roster.agents.len(), 8);+ assert_eq!(roster._workspaces.len(), 8);+ // Each agent got a distinct workspace directory.+ let mut dirs: Vec<_> = roster+ ._workspaces+ .iter()+ .map(|w| w.path().to_path_buf())+ .collect();+ dirs.sort();+ dirs.dedup();+ assert_eq!(dirs.len(), 8, "workspaces must be isolated per agent");+ }++ #[test]+ fn warm_up_turn_completes_without_network() {+ // The agent-turn future is large in debug builds. Run it on a worker+ // with explicit stack headroom instead of libtest's smaller default.+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .thread_stack_size(8 * 1024 * 1024)+ .build()+ .expect("test runtime builds");+ runtime+ .block_on(runtime.spawn(async {+ let mut roster = build_roster(1).expect("1-agent roster builds");+ warm_up(&mut roster).await.expect("warm-up turn completes");+ // The mock provider reports usage, so last_turn_usage is populated —+ // proving the embedding cost-metering contract works on the bare Agent.+ assert!(+ roster.agents[0].last_turn_usage().is_some(),+ "usage should be readable after a turn"+ );+ }))+ .expect("warm-up task joins");+ }+}diff --git a/src/openhuman/inference/provider/factory.rs b/src/openhuman/inference/provider/factory.rsindex 85915a224c..4496155609 100644--- a/src/openhuman/inference/provider/factory.rs+++ b/src/openhuman/inference/provider/factory.rs@@ -32,7 +32,7 @@/// and clear it via the returned guard. Inert in production: the check below/// is gated on `cfg(test)` or an off-by-default test/profiling feature,/// so the override is never consulted in shipped builds.-#[cfg(any(test, feature = "e2e-test-support"))]+#[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]#[path = "factory_test_provider_override_tests.rs"]pub mod test_provider_override;diff --git a/src/openhuman/inference/provider/factory_part_02.rs b/src/openhuman/inference/provider/factory_part_02.rsindex 9e54b05e7a..e3756781b1 100644--- a/src/openhuman/inference/provider/factory_part_02.rs+++ b/src/openhuman/inference/provider/factory_part_02.rs@@ -3,7 +3,7 @@ fn create_chat_model_with_model_id_inner(role: &str,config: &Config,) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]if let Some(model) = test_provider_override::current() {return Ok((model, "mock-model".to_string()));}@@ -14,11 +14,11 @@ fn create_chat_model_with_model_id_inner(// override is installed. The public wrapper supplies the construction-time// default while preserving an explicit per-call `ModelRequest` temperature.let test_override_active = {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]{test_provider_override::current().is_some()}- #[cfg(not(any(test, feature = "e2e-test-support")))]+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]{false}@@ -91,7 +91,7 @@ fn resolves_to_managed_backend(role: &str, config: &Config) -> bool {/// `resolves_to_managed_backend` is a pure config read that would otherwise/// still call this "managed" in a test with a bare default `Config`.pub async fn probe_inference_readiness(role: &str, config: &Config) -> Result<(), String> {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]if test_provider_override::current().is_some() {log::debug!("[flows][inference-probe] role={role} test model override active — skipping probe"@@ -161,16 +161,16 @@ fn create_chat_model_from_string_with_model_id_inner(provider: &str,config: &Config,) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]if let Some(model) = test_provider_override::current() {return Ok((model, "mock-model".to_string()));}let test_override_active = {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]{test_provider_override::current().is_some()}- #[cfg(not(any(test, feature = "e2e-test-support")))]+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]{false}diff --git a/src/openhuman/inference/provider/factory_part_03.rs b/src/openhuman/inference/provider/factory_part_03.rsindex c9a9db424b..6cd974f4b1 100644--- a/src/openhuman/inference/provider/factory_part_03.rs+++ b/src/openhuman/inference/provider/factory_part_03.rs@@ -5,7 +5,7 @@ fn create_turn_chat_model_with_native_tools_and_route_inner(model: &str,native_tool_calling: bool,) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]if let Some(chat) = test_provider_override::current() {let provider = chat.profile()@@ -14,11 +14,11 @@ fn create_turn_chat_model_with_native_tools_and_route_inner(return Ok((chat, provider, model.to_string()));}let test_override_active = {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]{test_provider_override::current().is_some()}- #[cfg(not(any(test, feature = "e2e-test-support")))]+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]{false}@@ -258,7 +258,7 @@ pub(crate) fn create_turn_chat_model_from_string_with_native_tools_and_route(temperature: f64,native_tool_calling: bool,) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]if let Some(chat) = test_provider_override::current() {let provider = chat.profile()@@ -271,11 +271,11 @@ pub(crate) fn create_turn_chat_model_from_string_with_native_tools_and_route());}let test_override_active = {- #[cfg(any(test, feature = "e2e-test-support"))]+ #[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]{test_provider_override::current().is_some()}- #[cfg(not(any(test, feature = "e2e-test-support")))]+ #[cfg(not(any(test, feature = "e2e-test-support", feature = "rss-bench")))]{false}diff --git a/src/openhuman/memory/README.md b/src/openhuman/memory/README.mdindex be7dd9b6f8..8232c445b8 100644--- a/src/openhuman/memory/README.md+++ b/src/openhuman/memory/README.md@@ -26,22 +26,33 @@ What stays here, per that split:- **Driver binding** — [`driver/`](driver/), which provider backs aworkspace.- **Ops** — [`ops/`](ops/), RPC handlers that delegate into the core.-- **Seam impls** — [`host.rs`](host.rs) /- [`host_impls.rs`](host_impls.rs) — `install_memory_event_sink` and- `MemoryHostConfig for Config`.+- **Seam impls** — [`host.rs`](host.rs) — `install_memory_event_sink` and+ `MemoryHostConfig for Config`. Its sibling `host_impls.rs` held the half that+ only an in-process engine could use, and went with the engine when the test+ build stopped linking one (openhuman#6161).-Everything else in this module is a **re-export** of the extracted crate-(`pub use tinymemory_core::{chat, global, ingest_pipeline, ingestion,+This module used to be mostly a **re-export** of the engine crate — a wall of+`pub use tinymemory_core::{chat, global, ingest_pipeline, ingestion,preferences, remember, rpc_models, store, sync_events, traits, util, …}` in-[`mod.rs`](mod.rs)), so the ~550 `crate::openhuman::memory::…` paths-elsewhere in this crate keep resolving unchanged. Prefer-`tinymemory_core::…` in new code.+[`mod.rs`](mod.rs), so the ~550 `crate::openhuman::memory::…` paths elsewhere+in this crate kept resolving after the extraction. Those re-exports are gone+with the engine: `tinymemory-core` left the product build in openhuman#5560 and+the test build in openhuman#6161, and it is now in neither this crate's normal+nor its dev dependency graph.++**Prefer `tinymemory_api::…` in new code, never `tinymemory_core::…`.** The+contract crate is what both this host and the loaded TinyMemory module compile+against; the engine crate is what the module carries and this binary does not+link. `memory::api` is the re-export of the contract, and its own module docs+explain which parts of `tinymemory-api` are the *bus* surface and which are the+host's own use of the crate — they are not the same set.## Domains that kept their RPC surface here-Mostly extracted, but each is a thin wrapper (`pub use-tinymemory_core::<domain>::*;` plus the handler/schema modules that name-`RpcOutcome` and `ControllerSchema`):+Each is the RPC surface for a family the *driver* serves: the handler and+schema modules that name `RpcOutcome` and `ControllerSchema`, resolving through+the bound provider rather than through a linked engine. Before the engine left,+each was a thin wrapper over `pub use tinymemory_core::<domain>::*;` as well.| Module | Role || -------------------------------- | --------------------------------------------------------- |@@ -66,11 +77,14 @@ owned by TinyCortex and used at ingest time.## Layer rules-- **No storage in this module.** All persistence goes through- `tinymemory_core::store::*`. If you're tempted to open a SQLite- connection here, the connection helper belongs one layer down, in the- extracted crate.-- **RPC + tools + seam wiring live here.** Domain logic belongs in- `tinymemory-core`; this module surfaces it over `/rpc` and to agents.+- **No storage in this module.** All persistence goes through the bound+ driver — `memory::binding::for_config(..)` and the `MemoryProvider`+ capability families behind it. If you are tempted to open a SQLite+ connection here, it belongs on the other side of that contract, in whatever+ engine the driver fronts. This crate does not link one.+- **RPC + tools + guard live here.** Domain logic belongs behind the contract;+ this module surfaces it over `/rpc` and to agents, and owns the policy that+ is genuinely the host's — the taint/scope/budget guard, the approval gate,+ and the workspace a binding is keyed on.- **Surface high-level tool calls** that route to the right submodule;don't expose internals at the call site.