Skip to content

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

feat(cli): add library profile harness and benchmark binaries

Steven Enamakel64684615397d
diff --git a/crates/openhuman-cli/src/bin/library_profile/harness.rs b/crates/openhuman-cli/src/bin/library_profile/harness.rs
deleted file mode 100644
index 08cd8c1c4c..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/harness.rs
+++ /dev/null
@@ -1,489 +0,0 @@
-//! 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::config::Config;
-use openhuman_core::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 `vision_agent` 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 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
-"#
- .to_string();
- if std::env::var_os("OPENHUMAN_PROFILE_DISABLE_MEMORY_WRITES").is_some() {
- config_toml.push_str(
- r#"
-[memory.conversations]
-enabled = false
-
-[memory.recall]
-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;
-
- 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/crates/openhuman-cli/src/bin/library_profile/main.rs b/crates/openhuman-cli/src/bin/library_profile/main.rs
deleted file mode 100644
index edc37ab526..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/main.rs
+++ /dev/null
@@ -1,126 +0,0 @@
-//! 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>`):
-//! - `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.
-//! - `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 `agent_memory` subagents in one instance: marginal RSS per subagent.
-//!
-//! `memory-ingest` and `cold-phases` were removed with the in-process memory
-//! engine (openhuman#6161); see `scenarios/mod.rs`.
-//!
-//! 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 {
- "agent-turn" => scenarios::agent_turn::run().await,
- "long-agent" => scenarios::long_agent::run().await,
- "workflow" => scenarios::workflow::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 \
- <agent-turn|long-agent|workflow|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/crates/openhuman-cli/src/bin/library_profile/mock.rs b/crates/openhuman-cli/src/bin/library_profile/mock.rs
deleted file mode 100644
index ba097d46c2..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/mock.rs
+++ /dev/null
@@ -1,470 +0,0 @@
-//! 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::inference::provider::types::ChatResponse;
-use tinyinference_llm::message::{AssistantMessage, ContentBlock, Message};
-use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
-use tinyinference_llm::tool::ToolCall as TinyAgentsToolCall;
-use tinytools_agent::dialect::NativeToolCall as ToolCall;
-
-/// 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",
- Message::Custom(_) => "custom",
- };
- 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,
- origin: None,
- },
- usage: None,
- raw: None,
- resolved_model: None,
- continue_turn: None,
- served_from_cache: false,
- correlation: None,
- resolved_route: None,
- }
-}
-
-/// 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-worker 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 worker 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}: worker {index} reports healthy.")
-}
-
-/// Text the orchestrator returns once it has merged every worker finding;
-/// its arrival in the 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** `vision_agent` workers;
-/// each worker turn returns its finding; the final merge turn returns plain
-/// text once all K findings are present.
-///
-/// `width` = K parallel workers. [`Self::with_width`] drives the
-/// **orchestrator directly** and scripts the full delegation chain as a direct
-/// fan-out — the `subagent-storm` fuzz-width path.
-pub struct SubagentMock {
- pub prompts: Mutex<Vec<String>>,
- /// Actual wall-time (ms) of each *worker* chat call, for percentiles.
- pub worker_latencies_ms: Mutex<Vec<u128>>,
- width: usize,
- latency: LatencyKnobs,
- /// Increments per fan-out so successive `spawn_parallel_agents` calls carry
- /// distinct task prompts.
- spawn_nonce: AtomicU64,
-}
-
-impl SubagentMock {
- /// K workers with per-worker 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()),
- worker_latencies_ms: Mutex::new(Vec::new()),
- width: width.max(1),
- latency: LatencyKnobs::from_env(),
- spawn_nonce: AtomicU64::new(0),
- })
- }
-
- /// Which worker (1-based) this prompt is for, if any. A worker
- /// prompt embeds exactly one `subagent_marker`.
- fn worker_index(&self, joined: &str) -> Option<usize> {
- (1..=self.width).find(|&i| joined.contains(&subagent_marker(i)))
- }
-
- /// True once every worker'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 `vision_agent` worker turn: exactly one task
- /// marker is present and the executing agent is not the orchestrator (its
- /// Tool Policy Boundary header names it, and its merge turn also carries
- /// every marker). The memory agent's system
- /// prompt names it a memory retrieval specialist, so it matches neither header.
- fn is_worker_turn(&self, joined: &str) -> bool {
- self.worker_index(joined).is_some() && !joined.contains("Agent: orchestrator")
- }
-
- /// Build the fan-out tool call delegating to K parallel `vision_agent` workers. Only
- /// valid on an **orchestrator** turn — other agents have no
- /// `spawn_parallel_agents` tool, so they `delegate_orchestrator` 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": "vision_agent",
- // 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 {} workers.", 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,
- }
- }
-
- /// A non-orchestrator parent's first turn: hand the task to the orchestrator (which
- /// owns `spawn_parallel_agents` and allows the `vision_agent` 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 delegation chain: orchestrator →
- /// `spawn_parallel_agents(K)` → K vision_agent workers → orchestrator merge.
- /// No latency/recording here — the async `chat` wrappers handle sleeping +
- /// latency capture around this.
- fn reply(&self, joined: &str) -> ChatResponse {
- // vision_agent worker: return its finding.
- if self.is_worker_turn(joined) {
- let i = self.worker_index(joined).expect("worker 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();
- }
- // Any other parent: 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 worker's finding.");
- }
- self.delegate_orchestrator_call()
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for SubagentMock {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> Result<ModelResponse, tinyinference_llm::Error> {
- Ok(model_response(
- self.dispatch(&joined_request(&request)).await,
- ))
- }
-}
-
-impl SubagentMock {
- /// Record the prompt, sleep a sampled latency for *worker* calls (and
- /// capture their wall time), then return the classified response.
- async fn dispatch(&self, joined: &str) -> ChatResponse {
- record(&self.prompts, joined);
- let is_worker = self.is_worker_turn(joined);
- let started = std::time::Instant::now();
- if is_worker {
- self.latency.sleep_sampled().await;
- }
- let resp = self.reply(joined);
- if is_worker {
- self.worker_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_llm::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_llm::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_llm::Error> {
- Ok(model_response(self.reply(&joined_request(&request))))
- }
-}
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs
deleted file mode 100644
index f60607df0b..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/agent_turn.rs
+++ /dev/null
@@ -1,32 +0,0 @@
-//! `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::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::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::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 =
- OpenHumanSessionHost::from_config_for_agent(&fixture.config, "orchestrator")?;
- 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/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs
deleted file mode 100644
index 63ed475285..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet.rs
+++ /dev/null
@@ -1,277 +0,0 @@
-//! `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::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::inference::provider::factory::test_provider_override;
-use openhuman_core::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);
-const FLEET_AGENT_ID: &str = "orchestrator";
-
-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).div_ceil(100);
- 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::config::Config,
- n: usize,
- rec: &Recorder,
-) -> Result<Vec<OpenHumanSessionHost>> {
- let stride = (n / 10).max(1);
- let mut agents = Vec::with_capacity(n);
- for i in 0..n {
- match OpenHumanSessionHost::from_config_for_agent(config, FLEET_AGENT_ID) {
- 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::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)]
-#[path = "fleet_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs
deleted file mode 100644
index bac2989769..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/fleet_tests.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-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 fleet_agent_is_a_shipped_definition() {
- assert!(
- AgentDefinitionRegistry::builtins_only()
- .get(FLEET_AGENT_ID)
- .is_some(),
- "fleet benchmark must construct a current shipped agent"
- );
-}
-
-#[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/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs
deleted file mode 100644
index 389a149966..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/long_agent.rs
+++ /dev/null
@@ -1,53 +0,0 @@
-//! `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::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::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::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 = OpenHumanSessionHost::from_config_for_agent(&fixture.config, "orchestrator")?;
- 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/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs
deleted file mode 100644
index 922f15e061..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/mod.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-//! One module per profiling scenario. Each exposes a single
-//! `run() -> Result<ProfileResult>` entry point dispatched from `main`.
-//!
-//! `memory-ingest` and `cold-phases` are absent. Both measured the memory
-//! engine embedded in this process — `memory_ingest` drained its queue,
-//! `cold_phases` checkpointed its bootstrap through
-//! `tinymemory_core::store::MemoryClient` — and this binary no longer links
-//! one (openhuman#6161). Re-adding them means measuring the memory *module*
-//! over the bus, which is a different scenario and wants a fresh design
-//! rather than a revived file.
-
-pub mod agent_turn;
-pub mod fleet;
-pub mod long_agent;
-pub mod skill_run;
-pub mod subagent_storm;
-pub mod workflow;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs
deleted file mode 100644
index 071d34a07d..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/skill_run.rs
+++ /dev/null
@@ -1,240 +0,0 @@
-//! `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
-//!
-//! The orchestrator carries `node_exec` as a `Deferred` tool: off the wire,
-//! found through `tool_search` (or skill `coding`), and callable by name once
-//! found. There is no separate code-executing specialist any more, so the
-//! agent that genuinely spawns the language runtime *is* the orchestrator. This
-//! scenario drives it 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**
-//! orchestrator 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::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::config::Config;
-use openhuman_core::inference::provider::factory::test_provider_override;
-use openhuman_core::security::AutonomyLevel;
-
-use crate::harness::{fixture, measure_with_tree, EnvGuard, ProfileResult};
-use crate::mock::SkillRunMock;
-
-/// The agent that reaches `node_exec` (a `Deferred` tool) and spawns the
-/// runtime child.
-const CODE_AGENT: &str = "orchestrator";
-
-/// 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::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 orchestrator 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 = OpenHumanSessionHost::from_config_for_agent(&config, CODE_AGENT)
- .with_context(|| format!("building {CODE_AGENT} 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_AGENT} turn #{idx}"))?;
- anyhow::ensure!(!reply.trim().is_empty(), "empty {CODE_AGENT} 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/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs
deleted file mode 100644
index e26e7eb5b7..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-//! `subagent-storm`: fuzz the *width* of delegation inside ONE core instance.
-//!
-//! One orchestrator turn fans out to **K** parallel `vision_agent` 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 worker 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/vision_agent agent beforehand perturbs
-//! the fan-out the same way. The only shape that reliably executes all K real
-//! vision_agent 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 vision_agent child executions).
-//! The workload asserts all K vision_agent subagents actually executed.
-//!
-//! The worker is `vision_agent`: a read-only worker-tier agent with a small
-//! memory tool surface, no spawn tools, and in the orchestrator's `[subagents] allowlist` —
-//! the closest surviving fit for the retired `researcher` archetype this
-//! scenario used to fan out to.
-
-use anyhow::Result;
-use openhuman_core::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::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 vision_agent workers.
-const STORM_PROMPT: &str = "Research every subsystem in parallel and merge the findings.";
-
-/// Positive identity anchor for an vision_agent *worker* turn — its own
-/// system prompt (`memory/agent/agent/prompt.md`) names it. Distinguishes a real worker
-/// from the orchestrator turns that also echo every task marker in the fan-out
-/// tool call / result.
-const WORKER_IDENTITY: &str = "You are a memory retrieval specialist.";
-
-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).div_ceil(100);
- 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::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 `vision_agent` subagent. One orchestrator turn fans out to
- // K real vision_agent 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 = OpenHumanSessionHost::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 vision_agent subagents must have actually executed as
- // its own worker turn: for each i there must be a prompt that carries the
- // vision_agent identity anchor AND that worker'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(WORKER_IDENTITY) && p.contains(&subagent_marker(i))),
- "vision_agent 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
- .worker_latencies_ms
- .lock()
- .expect("mock latency lock")
- .clone();
- eprintln!(
- "[library-profile] subagent-storm: width={width} retained_delta_kib={} \
- marginal_rss_kib_per_agent={:?} worker_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)]
-#[path = "subagent_storm_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs
deleted file mode 100644
index 78ceef8a25..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/subagent_storm_tests.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-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/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs b/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs
deleted file mode 100644
index da37f86366..0000000000
--- a/crates/openhuman-cli/src/bin/library_profile/scenarios/workflow.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-//! `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::agent::harness::AgentDefinitionRegistry;
-use openhuman_core::flows::ops::{flows_create, flows_run};
-use openhuman_core::flows::FlowRunTrigger;
-use openhuman_core::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::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": "agent_memory",
- "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/crates/openhuman-cli/src/bin/rss_bench.rs b/crates/openhuman-cli/src/bin/rss_bench.rs
deleted file mode 100644
index 735de31562..0000000000
--- a/crates/openhuman-cli/src/bin/rss_bench.rs
+++ /dev/null
@@ -1,325 +0,0 @@
-//! `rss-bench` — steady-state RSS benchmark for an embedded `openhuman_core`
-//! agent roster (#5046).
-//!
-//! Mirrors the OpenCompany embedding contract: a bare [`OpenHumanSessionHost`] built directly
-//! via [`OpenHumanSessionHost::builder`] (no `CoreBuilder`, no RPC, no background services)
-//! with an injected mock model 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::platform::proc_metrics`]; this binary is the fixture +
-//! process driver.
-
-use anyhow::{Context, Result};
-use async_trait::async_trait;
-use openhuman_core::agent::OpenHumanSessionHost;
-use openhuman_core::platform::proc_metrics::{
- self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,
- RSS_HARD_CAP_KIB,
-};
-use tinytools::{Tool, ToolResult};
-use tinytools_agent::dialect::NativeDialect;
-
-use std::path::PathBuf;
-use std::process::Stdio;
-use std::sync::Arc;
-use std::time::Duration;
-use tempfile::TempDir;
-use tinyinference_llm::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_llm::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"))
- }
-}
-
-/// 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<OpenHumanSessionHost>,
- _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> {
- // Root turns now go through the hosted TinyAgents path, which requires a
- // definition registry to supply durable host authority. This fixture has
- // no workspace-specific definitions, so the built-in catalogue is the
- // smallest representative setup.
- openhuman_core::agent::harness::AgentDefinitionRegistry::init_global_builtins()?;
-
- let mut agents = Vec::with_capacity(n);
- let mut workspaces = Vec::with_capacity(n);
- for _ in 0..n {
- let workspace = TempDir::new().context("create temp workspace")?;
- let path = workspace.path().to_path_buf();
-
- let agent = OpenHumanSessionHost::builder()
- .chat_model(Arc::new(MockModel))
- .tools(vec![Box::new(EchoTool)])
- .tool_dispatcher(Box::new(NativeDialect))
- .model_name("bench-mock".into())
- // Use a real built-in id because the hosted invocation resolves
- // root authority through the definition registry.
- .agent_definition_name("orchestrator")
- .workspace_dir(path.clone())
- .action_dir(path)
- .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)]
-#[path = "rss_bench_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-cli/src/bin/rss_bench_tests.rs b/crates/openhuman-cli/src/bin/rss_bench_tests.rs
deleted file mode 100644
index 74eef62e6e..0000000000
--- a/crates/openhuman-cli/src/bin/rss_bench_tests.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-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/crates/openhuman-cli/src/bin/tool_dialect_bench.rs b/crates/openhuman-cli/src/bin/tool_dialect_bench.rs
deleted file mode 100644
index 8fa7a9e0b2..0000000000
--- a/crates/openhuman-cli/src/bin/tool_dialect_bench.rs
+++ /dev/null
@@ -1,709 +0,0 @@
-//! `tool-dialect-bench` — how well a local model calls tools under each text
-//! dialect, and what each dialect costs in prompt tokens.
-//!
-//! The experiment behind `agent.tool_dispatcher = "python" | "typescript"`:
-//! render the tool catalogue as function signatures instead of JSON schemas
-//! or P-Format slots, and see whether a small code-trained model (an 8B
-//! Ollama model) calls tools more reliably for fewer tokens.
-//!
-//! For every `dialect × model × task` the bench composes the system prompt
-//! exactly as OpenHuman's `ToolsSection` + the dialect's protocol block would
-//! (catalogue, then protocol), sends one user turn with **no** schemas on the
-//! wire, reads the answer back through `tinytools_agent::parse_text` with the
-//! same registry the harness builds, and records:
-//!
-//! * `usage.input_tokens` / `output_tokens` as the provider reports them
-//! (Ollama fills them from `prompt_eval_count` / `eval_count`);
-//! * system-prompt bytes;
-//! * whether a call was recovered at all, whether it named the expected tool,
-//! and whether its arguments matched (exactly, and as a superset);
-//! * latency and the `CallSource` the call came through.
-//!
-//! Manual, network-touching, never run by CI:
-//!
-//! ```text
-//! ollama pull qwen3:8b
-//! cargo run -p openhuman-cli --bin tool-dialect-bench -- \
-//! --model qwen3:8b --dialects xml,pformat,python,typescript --trials 3
-//! ```
-//!
-//! `OLLAMA_HOST` / `OPENHUMAN_LOCAL_INFERENCE_URL` pick the server, as for
-//! the product.
-
-use std::collections::BTreeMap;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use anyhow::{Context, Result};
-use serde::Serialize;
-use serde_json::{json, Value};
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{ChatModel, ModelRequest};
-use tinytools::ToolSpec;
-use tinytools_agent::dialect::{CodeDialect, CodeStyle, PFormatDialect, ToolDialect, XmlDialect};
-use tinytools_agent::render::{render_code_catalogue, render_pformat_catalogue};
-use tinytools_agent::{build_registry, parse_text, CallSource, PFormatRegistry, ParseOptions};
-
-/// The role line every prompt starts with, so the dialect block is the only
-/// thing that differs between runs.
-const BASE_SYSTEM_PROMPT: &str = "You are a helpful assistant with tools. When the user's request \
- needs a tool, call it; do not describe what you would do instead of doing it. \
- Do not ask clarifying questions for these tasks.";
-
-/// Default per-call ceiling: the answer is one call, but a thinking model
-/// (qwen3) spends most of its budget in the reasoning channel first, and a
-/// runaway 8B model can otherwise generate for minutes. `--max-output-tokens`
-/// overrides it.
-const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 1500;
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
-enum Dialect {
- Xml,
- Pformat,
- Python,
- Typescript,
-}
-
-impl Dialect {
- fn parse(raw: &str) -> Result<Self> {
- match raw.trim().to_ascii_lowercase().as_str() {
- "xml" => Ok(Self::Xml),
- "pformat" => Ok(Self::Pformat),
- "python" => Ok(Self::Python),
- "typescript" => Ok(Self::Typescript),
- other => anyhow::bail!("unknown dialect {other:?} (xml|pformat|python|typescript)"),
- }
- }
-
- fn as_str(self) -> &'static str {
- match self {
- Self::Xml => "xml",
- Self::Pformat => "pformat",
- Self::Python => "python",
- Self::Typescript => "typescript",
- }
- }
-
- /// The tool section as OpenHuman renders it: catalogue first, then the
- /// dialect's protocol block. The XML dialect embeds its own catalogue in
- /// the block, so it gets no separate one.
- fn tool_section(self, specs: &[ToolSpec], registry: &PFormatRegistry) -> String {
- match self {
- Self::Xml => XmlDialect.prompt_instructions(specs),
- Self::Pformat => {
- let mut out = render_pformat_catalogue(specs);
- out.push('\n');
- out.push_str(&PFormatDialect::new(registry.clone()).prompt_instructions(specs));
- out
- }
- Self::Python | Self::Typescript => {
- let style = self.code_style();
- let mut out = render_code_catalogue(specs, style);
- out.push('\n');
- out.push_str(&CodeDialect::instructions(style));
- out
- }
- }
- }
-
- fn code_style(self) -> CodeStyle {
- match self {
- Self::Typescript => CodeStyle::TypeScript,
- _ => CodeStyle::Python,
- }
- }
-}
-
-/// One thing we ask the model to do, and the call that would do it.
-struct Task {
- prompt: &'static str,
- tool: &'static str,
- args: Value,
-}
-
-fn tool(name: &str, description: &str, parameters: Value) -> ToolSpec {
- ToolSpec {
- name: name.to_string(),
- description: description.to_string(),
- parameters,
- }
-}
-
-/// Ten tools with the shapes real OpenHuman tools have: required and optional
-/// parameters, integers, booleans, enums, lists, and one nested object.
-fn fixture_tools() -> Vec<ToolSpec> {
- vec![
- tool(
- "read_file",
- "Read a text file from the workspace.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string", "description": "Path relative to the workspace root"},
- "limit": {"type": "integer", "description": "Maximum number of lines to return"}
- },
- "required": ["path"]
- }),
- ),
- tool(
- "write_file",
- "Create or overwrite a text file in the workspace.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string"},
- "content": {"type": "string"}
- },
- "required": ["path", "content"]
- }),
- ),
- tool(
- "list_dir",
- "List the entries of a directory.",
- json!({
- "type": "object",
- "properties": {
- "path": {"type": "string", "description": "Directory to list; defaults to the workspace root"}
- }
- }),
- ),
- tool(
- "search_files",
- "Search file contents for a string.",
- json!({
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "glob": {"type": "string", "description": "Restrict to files matching this glob"},
- "max_results": {"type": "integer"}
- },
- "required": ["query"]
- }),
- ),
- tool(
- "shell",
- "Run a shell command and return its output.",
- json!({
- "type": "object",
- "properties": {
- "command": {"type": "string"},
- "background": {"type": "boolean", "description": "Run detached and return immediately"},
- "timeout_secs": {"type": "number"}
- },
- "required": ["command"]
- }),
- ),
- tool(
- "get_weather",
- "Get the current weather for a location.",
- json!({
- "type": "object",
- "properties": {
- "location": {"type": "string", "description": "City name"},
- "unit": {"type": "string", "enum": ["metric", "imperial"]}
- },
- "required": ["location"]
- }),
- ),
- tool(
- "send_email",
- "Send an email.",
- json!({
- "type": "object",
- "properties": {
- "to": {"type": "string"},
- "subject": {"type": "string"},
- "body": {"type": "string"},
- "cc": {"type": "array", "items": {"type": "string"}}
- },
- "required": ["to", "subject", "body"]
- }),
- ),
- tool(
- "calendar_create",
- "Create a calendar event.",
- json!({
- "type": "object",
- "properties": {
- "title": {"type": "string"},
- "start": {"type": "string", "description": "ISO 8601 start time"},
- "duration_minutes": {"type": "integer"},
- "attendees": {"type": "array", "items": {"type": "string"}}
- },
- "required": ["title", "start"]
- }),
- ),
- tool(
- "memory_recall",
- "Search long-term memory for relevant notes.",
- json!({
- "type": "object",
- "properties": {
- "query": {"type": "string"},
- "limit": {"type": "integer"}
- },
- "required": ["query"]
- }),
- ),
- tool(
- "http_fetch",
- "Fetch a URL.",
- json!({
- "type": "object",
- "properties": {
- "url": {"type": "string"},
- "method": {"type": "string", "enum": ["GET", "POST"]},
- "headers": {"type": "object", "description": "Extra request headers"}
- },
- "required": ["url"]
- }),
- ),
- ]
-}
-
-/// Twenty requests, each answerable by exactly one call. Optional
-/// arguments are only expected when the prompt names their value.
-fn fixture_tasks() -> Vec<Task> {
- vec![
- Task { prompt: "Show me the file README.md.", tool: "read_file", args: json!({"path": "README.md"}) },
- Task { prompt: "Read the first 20 lines of src/main.rs.", tool: "read_file", args: json!({"path": "src/main.rs", "limit": 20}) },
- Task { prompt: "Create a file called notes.txt containing exactly: hello world", tool: "write_file", args: json!({"path": "notes.txt", "content": "hello world"}) },
- Task { prompt: "What files are in the workspace root?", tool: "list_dir", args: json!({}) },
- Task { prompt: "List the contents of the docs directory.", tool: "list_dir", args: json!({"path": "docs"}) },
- Task { prompt: "Find every occurrence of the word TODO in the code.", tool: "search_files", args: json!({"query": "TODO"}) },
- Task { prompt: "Search for the string 'unwrap()' but only in Rust files (*.rs), at most 5 results.", tool: "search_files", args: json!({"query": "unwrap()", "glob": "*.rs", "max_results": 5}) },
- Task { prompt: "Run the command `cargo test`.", tool: "shell", args: json!({"command": "cargo test"}) },
- Task { prompt: "Start the dev server with `npm run dev` in the background.", tool: "shell", args: json!({"command": "npm run dev", "background": true}) },
- Task { prompt: "What's the weather in London?", tool: "get_weather", args: json!({"location": "London"}) },
- Task { prompt: "What's the weather in Chicago, in imperial units?", tool: "get_weather", args: json!({"location": "Chicago", "unit": "imperial"}) },
- Task { prompt: "Email [email protected] with the subject 'Lunch' and the body 'Are you free at noon?'", tool: "send_email", args: json!({"to": "[email protected]", "subject": "Lunch", "body": "Are you free at noon?"}) },
- Task { prompt: "Send an email to [email protected], subject 'Report', body 'Attached is the report.', and cc [email protected].", tool: "send_email", args: json!({"to": "[email protected]", "subject": "Report", "body": "Attached is the report.", "cc": ["[email protected]"]}) },
- Task { prompt: "Put a 'Standup' meeting on my calendar starting 2026-10-01T09:00:00.", tool: "calendar_create", args: json!({"title": "Standup", "start": "2026-10-01T09:00:00"}) },
- Task { prompt: "Schedule 'Design review' at 2026-10-02T14:00:00 for 45 minutes with [email protected] and [email protected].", tool: "calendar_create", args: json!({"title": "Design review", "start": "2026-10-02T14:00:00", "duration_minutes": 45, "attendees": ["[email protected]", "[email protected]"]}) },
- Task { prompt: "What do you remember about my dog's vet?", tool: "memory_recall", args: json!({"query": "dog's vet"}) },
- Task { prompt: "Recall up to 3 notes about the Berlin trip.", tool: "memory_recall", args: json!({"query": "Berlin trip", "limit": 3}) },
- Task { prompt: "Fetch https://example.com/status", tool: "http_fetch", args: json!({"url": "https://example.com/status"}) },
- Task { prompt: "POST to https://api.example.com/ping", tool: "http_fetch", args: json!({"url": "https://api.example.com/ping", "method": "POST"}) },
- Task { prompt: "Read config.toml, but only the first 5 lines.", tool: "read_file", args: json!({"path": "config.toml", "limit": 5}) },
- ]
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct Row {
- model: String,
- dialect: &'static str,
- trial: usize,
- task: usize,
- expected_tool: &'static str,
- system_prompt_bytes: usize,
- input_tokens: Option<u64>,
- output_tokens: Option<u64>,
- latency_ms: u128,
- recovered: bool,
- name_ok: bool,
- args_exact: bool,
- args_superset: bool,
- source: Option<String>,
- parsed_tool: Option<String>,
- parsed_args: Option<Value>,
- raw_text: String,
- error: Option<String>,
-}
-
-#[derive(Debug, Default)]
-struct Summary {
- n: usize,
- input_tokens: u64,
- input_samples: u64,
- output_tokens: u64,
- output_samples: u64,
- system_prompt_bytes: usize,
- latency_ms: u128,
- recovered: usize,
- name_ok: usize,
- args_exact: usize,
- args_superset: usize,
- errors: usize,
- sources: BTreeMap<String, usize>,
-}
-
-impl Summary {
- fn add(&mut self, row: &Row) {
- self.n += 1;
- if let Some(tokens) = row.input_tokens {
- self.input_tokens += tokens;
- self.input_samples += 1;
- }
- if let Some(tokens) = row.output_tokens {
- self.output_tokens += tokens;
- self.output_samples += 1;
- }
- self.system_prompt_bytes = row.system_prompt_bytes;
- self.latency_ms += row.latency_ms;
- self.recovered += usize::from(row.recovered);
- self.name_ok += usize::from(row.name_ok);
- self.args_exact += usize::from(row.args_exact);
- self.args_superset += usize::from(row.args_superset);
- self.errors += usize::from(row.error.is_some());
- if let Some(source) = &row.source {
- *self.sources.entry(source.clone()).or_default() += 1;
- }
- }
-
- fn pct(&self, count: usize) -> String {
- if self.n == 0 {
- return "-".into();
- }
- format!("{:.0}%", 100.0 * count as f64 / self.n as f64)
- }
-
- fn avg(total: u64, samples: u64) -> String {
- if samples == 0 {
- return "-".into();
- }
- format!("{}", total / samples)
- }
-}
-
-struct Args {
- models: Vec<String>,
- dialects: Vec<Dialect>,
- trials: usize,
- json: bool,
- verbose: bool,
- tasks: Option<Vec<usize>>,
- max_output_tokens: u32,
-}
-
-fn parse_args() -> Result<Args> {
- let mut models = vec!["qwen3:8b".to_string()];
- let mut dialects = vec![
- Dialect::Xml,
- Dialect::Pformat,
- Dialect::Python,
- Dialect::Typescript,
- ];
- let mut trials = 1usize;
- let mut json = false;
- let mut verbose = false;
- let mut tasks = None;
- let mut max_output_tokens = DEFAULT_MAX_OUTPUT_TOKENS;
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- match arg.as_str() {
- "--model" | "--models" => {
- models = it
- .next()
- .context("--model needs a value")?
- .split(',')
- .map(|m| m.trim().to_string())
- .filter(|m| !m.is_empty())
- .collect();
- }
- "--dialects" => {
- dialects = it
- .next()
- .context("--dialects needs a value")?
- .split(',')
- .map(Dialect::parse)
- .collect::<Result<Vec<_>>>()?;
- }
- "--trials" => {
- trials = it
- .next()
- .context("--trials needs a value")?
- .parse()
- .context("--trials value")?;
- }
- "--tasks" => {
- tasks = Some(
- it.next()
- .context("--tasks needs a value")?
- .split(',')
- .map(|t| t.trim().parse::<usize>().context("--tasks index"))
- .collect::<Result<Vec<_>>>()?,
- );
- }
- "--max-output-tokens" => {
- max_output_tokens = it
- .next()
- .context("--max-output-tokens needs a value")?
- .parse()
- .context("--max-output-tokens value")?;
- }
- "--json" => json = true,
- "--verbose" | "-v" => verbose = true,
- "--help" | "-h" => {
- eprintln!(
- "tool-dialect-bench [--model m1,m2] [--dialects xml,pformat,python,typescript] \
- [--trials N] [--tasks 0,3,5] [--max-output-tokens N] [--json] [--verbose]"
- );
- std::process::exit(0);
- }
- other => anyhow::bail!("unknown argument: {other}"),
- }
- }
- Ok(Args {
- models,
- dialects,
- trials,
- json,
- verbose,
- tasks,
- max_output_tokens,
- })
-}
-
-/// `expected ⊆ parsed`, comparing values after light normalisation (a
-/// number the model quoted still counts).
-fn is_superset(parsed: &Value, expected: &Value) -> bool {
- let (Some(parsed), Some(expected)) = (parsed.as_object(), expected.as_object()) else {
- return false;
- };
- expected
- .iter()
- .all(|(key, want)| parsed.get(key).is_some_and(|got| loosely_equal(got, want)))
-}
-
-fn loosely_equal(got: &Value, want: &Value) -> bool {
- if got == want {
- return true;
- }
- match (got, want) {
- (Value::String(g), Value::Number(w)) => g.trim() == w.to_string(),
- (Value::Number(g), Value::String(w)) => g.to_string() == w.trim(),
- (Value::String(g), Value::Bool(w)) => g.trim().eq_ignore_ascii_case(&w.to_string()),
- (Value::String(g), Value::String(w)) => g.trim() == w.trim(),
- _ => false,
- }
-}
-
-fn is_exact(parsed: &Value, expected: &Value) -> bool {
- let (Some(parsed), Some(expected)) = (parsed.as_object(), expected.as_object()) else {
- return false;
- };
- parsed.len() == expected.len()
- && is_superset(
- &Value::Object(parsed.clone()),
- &Value::Object(expected.clone()),
- )
-}
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let _ = env_logger::try_init();
- let args = parse_args()?;
- let specs = fixture_tools();
- let all_tasks = fixture_tasks();
- let tasks: Vec<(usize, &Task)> = match &args.tasks {
- Some(indices) => indices
- .iter()
- .map(|&i| {
- all_tasks
- .get(i)
- .map(|t| (i, t))
- .context("task index out of range")
- })
- .collect::<Result<Vec<_>>>()?,
- None => all_tasks.iter().enumerate().collect(),
- };
- let registry = build_registry(
- specs
- .iter()
- .map(|spec| (spec.name.clone(), spec.parameters.clone())),
- );
- let known: Vec<String> = specs.iter().map(|spec| spec.name.clone()).collect();
- let config = openhuman_core::config::Config::default();
-
- let mut rows: Vec<Row> = Vec::new();
- let mut summaries: BTreeMap<(String, Dialect), Summary> = BTreeMap::new();
-
- for model_name in &args.models {
- let provider = format!("ollama:{model_name}");
- let (model, model_id): (Arc<dyn ChatModel<()>>, String) =
- openhuman_core::inference::provider::create_chat_model_from_string_with_model_id(
- "chat", &provider, &config, 0.0,
- )
- .with_context(|| format!("building model {provider}"))?;
- eprintln!("== model {model_id} ({provider})");
-
- for &dialect in &args.dialects {
- let section = dialect.tool_section(&specs, &registry);
- let system = format!("{BASE_SYSTEM_PROMPT}\n\n{section}");
- eprintln!(
- "-- dialect {} (system prompt {} bytes, ~{} tokens at 4 chars/token)",
- dialect.as_str(),
- system.len(),
- system.len() / 4
- );
- if args.verbose {
- eprintln!("{system}\n");
- }
- for trial in 0..args.trials {
- for &(task_index, task) in &tasks {
- let request = ModelRequest::new(vec![
- Message::system(system.clone()),
- Message::user(task.prompt),
- ])
- .with_model(model_id.clone())
- .with_temperature(0.0)
- .with_max_tokens(args.max_output_tokens);
- let started = Instant::now();
- let outcome =
- tokio::time::timeout(Duration::from_secs(180), model.invoke(&(), request))
- .await;
- let latency_ms = started.elapsed().as_millis();
- let mut row = Row {
- model: model_id.clone(),
- dialect: dialect.as_str(),
- trial,
- task: task_index,
- expected_tool: task.tool,
- system_prompt_bytes: system.len(),
- input_tokens: None,
- output_tokens: None,
- latency_ms,
- recovered: false,
- name_ok: false,
- args_exact: false,
- args_superset: false,
- source: None,
- parsed_tool: None,
- parsed_args: None,
- raw_text: String::new(),
- error: None,
- };
- match outcome {
- Err(_) => row.error = Some("timeout".into()),
- // An empty answer that used the whole budget is the
- // model thinking past the cap, not a dialect failure.
- Ok(Ok(response))
- if response.text().trim().is_empty()
- && response.usage.is_some_and(|u| {
- u.output_tokens >= u64::from(args.max_output_tokens)
- }) =>
- {
- row.input_tokens = response.usage.map(|u| u.input_tokens);
- row.output_tokens = response.usage.map(|u| u.output_tokens);
- row.error = Some("output cap reached with no visible text".into());
- }
- Ok(Err(error)) => row.error = Some(error.to_string()),
- Ok(Ok(response)) => {
- row.input_tokens = response.usage.map(|u| u.input_tokens);
- row.output_tokens = response.usage.map(|u| u.output_tokens);
- let text = response.text();
- row.raw_text = text.clone();
- // The same recovery the harness runs: known tools
- // for name repair, the registry for positional
- // and code-style bodies.
- let options = ParseOptions::new()
- .with_known_tools(&known)
- .with_registry(&registry);
- let (_narrative, calls) = parse_text(&text, &options).into_parts();
- if let Some(call) = calls.first() {
- row.recovered = true;
- row.name_ok = call.name == task.tool;
- row.args_exact =
- row.name_ok && is_exact(&call.arguments, &task.args);
- row.args_superset =
- row.name_ok && is_superset(&call.arguments, &task.args);
- row.source = Some(source_name(call.source).to_string());
- row.parsed_tool = Some(call.name.clone());
- row.parsed_args = Some(call.arguments.clone());
- }
- }
- }
- let mark = if row.args_exact {
- "ok "
- } else if row.args_superset {
- "sup"
- } else if row.name_ok {
- "arg"
- } else if row.recovered {
- "tool"
- } else if row.error.is_some() {
- "ERR"
- } else {
- "none"
- };
- eprintln!(
- " [{mark:>4}] task {task_index:>2} {:<16} in={:<5} out={:<4} {}ms{}",
- task.tool,
- row.input_tokens.map_or("-".to_string(), |t| t.to_string()),
- row.output_tokens.map_or("-".to_string(), |t| t.to_string()),
- row.latency_ms,
- if args.verbose || !row.args_superset {
- format!("\n raw: {}", one_line(&row.raw_text))
- } else {
- String::new()
- }
- );
- summaries
- .entry((model_id.clone(), dialect))
- .or_default()
- .add(&row);
- rows.push(row);
- }
- }
- }
- }
-
- println!();
- println!(
- "| model | dialect | n | sys bytes | in tok | out tok | recovered | tool | args ⊇ | args = | avg ms | errors | sources |"
- );
- println!("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
- for ((model, dialect), s) in &summaries {
- let sources: Vec<String> = s.sources.iter().map(|(k, v)| format!("{k}:{v}")).collect();
- println!(
- "| {model} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
- dialect.as_str(),
- s.n,
- s.system_prompt_bytes,
- Summary::avg(s.input_tokens, s.input_samples),
- Summary::avg(s.output_tokens, s.output_samples),
- s.pct(s.recovered),
- s.pct(s.name_ok),
- s.pct(s.args_superset),
- s.pct(s.args_exact),
- if s.n == 0 {
- 0
- } else {
- s.latency_ms / s.n as u128
- },
- s.errors,
- sources.join(" ")
- );
- }
- if args.json {
- println!();
- println!("{}", serde_json::to_string_pretty(&rows)?);
- }
- Ok(())
-}
-
-fn source_name(source: CallSource) -> &'static str {
- match source {
- CallSource::Native => "native",
- CallSource::TaggedJson => "tagged_json",
- CallSource::InvokeXml => "invoke_xml",
- CallSource::Sentinel => "sentinel",
- CallSource::Harmony => "harmony",
- CallSource::Mistral => "mistral",
- CallSource::Glm => "glm",
- CallSource::BareJson => "bare_json",
- CallSource::PFormat => "pformat",
- CallSource::Code => "code",
- _ => "other",
- }
-}
-
-fn one_line(text: &str) -> String {
- let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
- if flat.chars().count() > 240 {
- let clipped: String = flat.chars().take(240).collect();
- format!("{clipped}…")
- } else {
- flat
- }
-}
diff --git a/crates/openhuman-cli/src/bin/tool_search_bench.rs b/crates/openhuman-cli/src/bin/tool_search_bench.rs
deleted file mode 100644
index 578d8ce026..0000000000
--- a/crates/openhuman-cli/src/bin/tool_search_bench.rs
+++ /dev/null
@@ -1,678 +0,0 @@
-//! `tool-search-bench` — how well does each `tool_search` ranker pick the
-//! right tool for an intent?
-//!
-//! The catalogue is the real thing: every tool the orchestrator session
-//! registers (built exactly as a session builds it, with a temp workspace),
-//! plus the recorded Composio catalogues under `tests/fixtures/composio_*.json`
-//! (≈1,000 actions across nine toolkits) as the deferred per-action tools a
-//! signed-in workspace would synthesise. The intents are
-//! `tests/fixtures/tool_search/intents.jsonl`: hand-written requests, each
-//! labelled with the tool it should reach (or `none` for a request no tool
-//! should answer).
-//!
-//! Three rankers are measured on the same rows:
-//!
-//! - `bm25` — `tinytools::Bm25Ranker`, what the harness answers with when
-//! nothing else is installed.
-//! - `overlap` — `tinyagents_harness::tool::select::rank_tools_by_prompt`,
-//! the verb-gated token overlap the Composio sub-agent narrows with today.
-//! - `jev` — `tinytools_jev::JevRanker`: BM25 retrieves the top 20, one Jev
-//! `Choice` decides. Needs a key: `OPENHUMAN_BACKEND_API_KEY` (through the
-//! TinyHumans proxy, `BACKEND_URL` to override the base) or
-//! `TYPESAFE_API_KEY` (TypeSafe directly). Skipped without one.
-//!
-//! Reported per ranker: top-1 and top-3 accuracy over the labelled rows,
-//! recall@20 of the BM25 retriever (the ceiling Jev can reach), the needless
-//! rate (a `none` row answered with a hit), p50/p95 latency, input tokens and
-//! USD from the provider's `usage`, and a per-family confusion table.
-//!
-//! ```text
-//! cargo run -p openhuman-cli --bin tool-search-bench -- --ranker all
-//! cargo run -p openhuman-cli --bin tool-search-bench -- --dump-catalogue
-//! ```
-
-use std::collections::BTreeMap;
-use std::path::PathBuf;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use anyhow::{Context, Result};
-use serde::{Deserialize, Serialize};
-use tinytools::{Bm25Ranker, RankCandidate, RankContext, ToolRanker};
-
-/// jev-1.13 list price for input tokens, USD per million; output is free.
-const JEV_USD_PER_MILLION_INPUT: f64 = 0.042;
-/// Toolkits with a recorded catalogue under `tests/fixtures/`.
-const FIXTURE_TOOLKITS: &[&str] = &[
- "gmail",
- "slack",
- "github",
- "notion",
- "googledrive",
- "googlesheets",
- "reddit",
- "facebook",
- "instagram",
-];
-
-#[derive(Debug, Clone, Deserialize)]
-struct IntentRow {
- intent: String,
- /// The tool that should answer, or `"none"`.
- expected: String,
- #[serde(default)]
- family: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct CatalogueEntry {
- name: String,
- family: Option<String>,
- description: String,
- #[serde(skip)]
- parameters: serde_json::Value,
-}
-
-impl CatalogueEntry {
- fn candidate(&self) -> RankCandidate {
- let mut summary = String::with_capacity(self.description.len() + 64);
- summary.push_str(&self.name);
- summary.push(' ');
- summary.push_str(&self.name.replace('_', " "));
- summary.push(' ');
- summary.push_str(&self.description);
- if let Some(props) = self
- .parameters
- .get("properties")
- .and_then(|v| v.as_object())
- {
- for key in props.keys() {
- summary.push(' ');
- summary.push_str(key);
- }
- }
- RankCandidate {
- key: self.name.clone(),
- family: self.family.clone(),
- summary,
- }
- }
-}
-
-#[derive(Debug, Default, Serialize)]
-struct RankerReport {
- ranker: String,
- rows: usize,
- labelled: usize,
- top1: usize,
- top3: usize,
- /// Labelled rows whose expected tool BM25 retrieved in its top 20.
- recall_at_20: usize,
- none_rows: usize,
- needless: usize,
- errors: usize,
- latency_ms: Vec<u64>,
- input_tokens: u64,
- usd: f64,
- /// `expected family -> top-1 family -> count`, labelled rows only.
- confusion: BTreeMap<String, BTreeMap<String, usize>>,
- /// `source -> (labelled, top1, top3, recall@k)` where source is `composio`
- /// or `core`; the connector catalogue is the heavy one, so it is read on
- /// its own.
- by_source: BTreeMap<String, (usize, usize, usize, usize)>,
- misses: Vec<Miss>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-struct Miss {
- intent: String,
- expected: String,
- got: Vec<String>,
-}
-
-impl RankerReport {
- fn percentile(&self, p: f64) -> u64 {
- if self.latency_ms.is_empty() {
- return 0;
- }
- let mut sorted = self.latency_ms.clone();
- sorted.sort_unstable();
- let idx = ((sorted.len() as f64 - 1.0) * p).round() as usize;
- sorted[idx.min(sorted.len() - 1)]
- }
-}
-
-struct Args {
- ranker: String,
- intents: PathBuf,
- dump_catalogue: bool,
- json_out: Option<PathBuf>,
- top_k: usize,
- retrieval_k: usize,
- misses: bool,
- family: bool,
- embedding: bool,
-}
-
-fn parse_args() -> Args {
- let mut args = Args {
- ranker: "all".to_string(),
- intents: repo_root().join("tests/fixtures/tool_search/intents.jsonl"),
- dump_catalogue: false,
- json_out: None,
- top_k: 3,
- retrieval_k: 20,
- misses: false,
- family: false,
- embedding: false,
- };
- let mut it = std::env::args().skip(1);
- while let Some(arg) = it.next() {
- match arg.as_str() {
- "--ranker" => args.ranker = it.next().unwrap_or_default(),
- "--intents" => args.intents = PathBuf::from(it.next().unwrap_or_default()),
- "--dump-catalogue" => args.dump_catalogue = true,
- "--json" => args.json_out = Some(PathBuf::from(it.next().unwrap_or_default())),
- "--top-k" => args.top_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(3),
- "--retrieval-k" => {
- args.retrieval_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(20)
- }
- "--misses" => args.misses = true,
- "--family" => args.family = true,
- "--embedding" => args.embedding = true,
- "-h" | "--help" => {
- eprintln!(
- "usage: tool-search-bench [--ranker all|bm25|overlap|embedding|jev] [--intents FILE] \
- [--dump-catalogue] [--json OUT] [--top-k N] [--retrieval-k N] [--misses] [--family] [--embedding]"
- );
- std::process::exit(0);
- }
- other => {
- eprintln!("unknown argument {other}");
- std::process::exit(2);
- }
- }
- }
- args
-}
-
-fn repo_root() -> PathBuf {
- PathBuf::from(env!("OPENHUMAN_REPOSITORY_ROOT"))
-}
-
-/// The orchestrator's registered tools, built the way a session builds them.
-fn core_catalogue() -> Result<Vec<CatalogueEntry>> {
- use openhuman_core::agent::harness::AgentDefinitionRegistry;
- use openhuman_core::agent::OpenHumanSessionHost;
-
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let tmp = tempfile::TempDir::new()?;
- let config = openhuman_core::config::Config {
- workspace_dir: tmp.path().join("workspace"),
- action_dir: tmp.path().join("workspace"),
- config_path: tmp.path().join("config.toml"),
- ..openhuman_core::config::Config::default()
- };
- std::fs::create_dir_all(&config.workspace_dir)?;
- let host = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")
- .context("build orchestrator session")?;
- let mut out = Vec::new();
- for spec in host.tool_specs() {
- // Pack members carry their pack as the family; everything else is a
- // core tool with no family, like the registry sees it.
- let family = openhuman_core::tools::toolpacks::pack_for_tool(&spec.name)
- .map(|pack| pack.id.to_string());
- out.push(CatalogueEntry {
- name: spec.name.clone(),
- family,
- description: spec.description.clone(),
- parameters: spec.parameters.clone(),
- });
- }
- Ok(out)
-}
-
-/// The recorded Composio catalogues, one deferred action per entry.
-fn composio_catalogue() -> Result<Vec<CatalogueEntry>> {
- let mut out = Vec::new();
- for toolkit in FIXTURE_TOOLKITS {
- let path = repo_root().join(format!("tests/fixtures/composio_{toolkit}.json"));
- let raw = std::fs::read_to_string(&path).with_context(|| format!("read {path:?}"))?;
- let parsed: serde_json::Value = serde_json::from_str(&raw)?;
- let tools = parsed
- .pointer("/result/result/tools")
- .and_then(|t| t.as_array())
- .with_context(|| format!("missing /result/result/tools in {path:?}"))?;
- for tool in tools {
- let name = tool
- .pointer("/function/name")
- .and_then(|n| n.as_str())
- .unwrap_or_default()
- .to_string();
- if name.is_empty() {
- continue;
- }
- out.push(CatalogueEntry {
- name,
- family: Some((*toolkit).to_string()),
- description: tool
- .pointer("/function/description")
- .and_then(|d| d.as_str())
- .unwrap_or_default()
- .to_string(),
- parameters: tool
- .pointer("/function/parameters")
- .cloned()
- .unwrap_or_else(|| serde_json::json!({"type": "object"})),
- });
- }
- }
- Ok(out)
-}
-
-fn load_intents(path: &PathBuf) -> Result<Vec<IntentRow>> {
- let raw = std::fs::read_to_string(path).with_context(|| format!("read {path:?}"))?;
- let mut rows = Vec::new();
- for (i, line) in raw.lines().enumerate() {
- let line = line.trim();
- if line.is_empty() || line.starts_with('#') {
- continue;
- }
- let row: IntentRow =
- serde_json::from_str(line).with_context(|| format!("{path:?}:{} bad row", i + 1))?;
- rows.push(row);
- }
- Ok(rows)
-}
-
-use openhuman_core::agent::tinyagents::discovery::OverlapRanker;
-
-#[cfg(feature = "jev")]
-fn jev_ranker(
- retrieval_k: usize,
- family: bool,
- embedding: bool,
-) -> Option<(Arc<dyn ToolRanker>, Arc<tinytools_jev::JevRanker>)> {
- use openhuman_tinyhumans::jev::TinyJevEvaluator;
- use tinyjevclient::{Client, ClientConfig};
- use tinytools_jev::JevRanker;
- let client = if let Ok(key) = std::env::var("OPENHUMAN_BACKEND_API_KEY") {
- let mut client = ClientConfig::tinyhumans_openrouter(key);
- if let Ok(base) = std::env::var("BACKEND_URL") {
- if !base.trim().is_empty() {
- client.base_url = base.trim().trim_end_matches('/').to_string();
- }
- }
- client
- } else if let Ok(key) = std::env::var("TYPESAFE_API_KEY") {
- ClientConfig::new(key)
- } else {
- // No key in the environment: rank exactly as the product does, with
- // the process's signed-in TinyHumans session resolved per search.
- eprintln!("jev: no key in the environment; using the signed-in TinyHumans session");
- return None;
- };
- let client = Client::new(client).ok()?;
- let evaluator = Arc::new(TinyJevEvaluator::new(client).with_deadline(Duration::from_secs(20)));
- let ranker = Arc::new(JevRanker::new(
- evaluator,
- jev_config(retrieval_k, family, embedding),
- ));
- Some((ranker.clone() as Arc<dyn ToolRanker>, ranker))
-}
-
-#[cfg(feature = "jev")]
-fn jev_config(retrieval_k: usize, family: bool, embedding: bool) -> tinytools_jev::JevRankerConfig {
- use tinytools_jev::{JevRankerConfig, JevStrategy};
- let mut config = JevRankerConfig::new().with_retrieval_k(retrieval_k);
- if family {
- config = config.with_strategy(JevStrategy::FamilyThenDecide);
- }
- if embedding {
- config = config.with_retriever(embedding_retriever());
- }
- config
-}
-
-#[cfg(not(feature = "jev"))]
-fn jev_ranker(
- _retrieval_k: usize,
- _family: bool,
- _embedding: bool,
-) -> Option<(Arc<dyn ToolRanker>, Arc<()>)> {
- None
-}
-
-/// The process's configured embedding provider as a `ToolRanker`, with its
-/// catalogue cache in the scratch workspace so repeated runs embed only the
-/// intents.
-fn embedding_retriever() -> Arc<dyn ToolRanker> {
- use openhuman_core::agent::tinyagents::discovery::{
- embedding_provider_is_usable, embedding_tool_ranker,
- };
- let config = tokio::task::block_in_place(|| {
- tokio::runtime::Handle::current().block_on(openhuman_core::config::Config::load_or_init())
- })
- .expect("load config for the embedding provider");
- let provider =
- openhuman_core::inference::embedding_host::default_embedding_provider_with_config(&config);
- if !embedding_provider_is_usable(provider.as_ref()) {
- eprintln!(
- "embedding: provider `{}` cannot embed; the bench retriever stays bm25",
- provider.name()
- );
- return Arc::new(Bm25Ranker);
- }
- eprintln!("embedding: {} / {}", provider.name(), provider.model_id());
- Arc::new(
- embedding_tool_ranker(provider).with_disk_cache(
- repo_root()
- .join("target")
- .join("tool_search_bench_embeddings.json"),
- ),
- )
-}
-
-fn family_of<'a>(catalogue: &'a [CatalogueEntry], name: &str) -> &'a str {
- catalogue
- .iter()
- .find(|e| e.name == name)
- .and_then(|e| e.family.as_deref())
- .unwrap_or("core")
-}
-
-#[tokio::main]
-async fn main() -> Result<()> {
- let args = parse_args();
- let mut catalogue = core_catalogue()?;
- let core_count = catalogue.len();
- catalogue.extend(composio_catalogue()?);
- eprintln!(
- "catalogue: {} tools ({} core, {} composio actions)",
- catalogue.len(),
- core_count,
- catalogue.len() - core_count
- );
- if args.dump_catalogue {
- for entry in &catalogue {
- println!(
- "{}\t{}\t{}",
- entry.name,
- entry.family.as_deref().unwrap_or("-"),
- entry.description.chars().take(100).collect::<String>()
- );
- }
- return Ok(());
- }
- let names: std::collections::HashSet<&str> =
- catalogue.iter().map(|e| e.name.as_str()).collect();
- let rows = load_intents(&args.intents)?;
- for row in &rows {
- if row.expected != "none" && !names.contains(row.expected.as_str()) {
- anyhow::bail!(
- "intent {:?} expects `{}`, which is not in the catalogue",
- row.intent,
- row.expected
- );
- }
- }
- let candidates: Vec<RankCandidate> = catalogue.iter().map(CatalogueEntry::candidate).collect();
-
- let mut rankers: Vec<(String, Arc<dyn ToolRanker>)> = Vec::new();
- let want = |k: &str| args.ranker == "all" || args.ranker == k;
- if want("bm25") {
- rankers.push(("bm25".into(), Arc::new(Bm25Ranker)));
- }
- if want("overlap") {
- rankers.push(("overlap".into(), Arc::new(OverlapRanker)));
- }
- if want("embedding") && args.embedding {
- rankers.push(("embedding".into(), embedding_retriever()));
- }
- if want("jev") {
- match jev_ranker(args.retrieval_k, args.family, args.embedding) {
- Some((ranker, _)) => rankers.push(("jev".into(), ranker)),
- None => {
- #[cfg(feature = "jev")]
- {
- let ranker = openhuman_tinyhumans::jev::TinyHumansJevRanker::with_config(
- jev_config(args.retrieval_k, args.family, args.embedding),
- )
- .with_deadline(Duration::from_secs(20));
- rankers.push(("jev".into(), Arc::new(ranker)));
- }
- #[cfg(not(feature = "jev"))]
- eprintln!("jev: skipped (build with the `jev` feature)");
- }
- }
- }
-
- let mut reports = Vec::new();
- for (kind, ranker) in &rankers {
- let mut report = RankerReport {
- ranker: if kind == "jev" {
- format!(
- "jev({}{})",
- if args.family { "family" } else { "retrieve" },
- if args.embedding {
- "+embedding"
- } else {
- "+bm25"
- }
- )
- } else {
- kind.clone()
- },
- rows: rows.len(),
- ..RankerReport::default()
- };
- for row in &rows {
- let started = Instant::now();
- let result = ranker
- .rank(&row.intent, &RankContext::empty(), &candidates, args.top_k)
- .await;
- report
- .latency_ms
- .push(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));
- let hits = match result {
- Ok(hits) => hits,
- Err(error) => {
- report.errors += 1;
- eprintln!("{kind}: {:?} -> {error}", row.intent);
- Vec::new()
- }
- };
- let got: Vec<String> = hits.iter().map(|h| h.key.clone()).collect();
- if row.expected == "none" {
- report.none_rows += 1;
- if !got.is_empty() {
- report.needless += 1;
- }
- continue;
- }
- report.labelled += 1;
- let source = if catalogue.iter().any(|e| {
- e.name == row.expected
- && e.family
- .as_deref()
- .is_some_and(|f| FIXTURE_TOOLKITS.contains(&f))
- }) {
- "composio"
- } else {
- "core"
- };
- let bucket = report.by_source.entry(source.to_string()).or_default();
- bucket.0 += 1;
- let hit1 = got.first().map(String::as_str) == Some(row.expected.as_str());
- let hit3 = got.iter().any(|g| g == &row.expected);
- if hit1 {
- report.top1 += 1;
- bucket.1 += 1;
- }
- if hit3 {
- report.top3 += 1;
- bucket.2 += 1;
- } else if args.misses {
- report.misses.push(Miss {
- intent: row.intent.clone(),
- expected: row.expected.clone(),
- got: got.clone(),
- });
- }
- // Recall of the retriever Jev sits on: the embedding index when
- // `--embedding`, BM25 otherwise. For the standalone rankers it is
- // their own recall at `retrieval_k`.
- let retrieved: Vec<String> = if kind == "jev" && !args.embedding || kind == "bm25" {
- Bm25Ranker::rank_sync(&candidates, &row.intent, args.retrieval_k)
- .into_iter()
- .map(|h| h.key)
- .collect()
- } else {
- let retriever: Arc<dyn ToolRanker> = if kind == "jev" {
- embedding_retriever()
- } else {
- ranker.clone()
- };
- retriever
- .rank(
- &row.intent,
- &RankContext::empty(),
- &candidates,
- args.retrieval_k,
- )
- .await
- .map(|hits| hits.into_iter().map(|h| h.key).collect())
- .unwrap_or_default()
- };
- if retrieved.iter().any(|h| h == &row.expected) {
- report.recall_at_20 += 1;
- if let Some(bucket) = report.by_source.get_mut(source) {
- bucket.3 += 1;
- }
- }
- let expected_family = row
- .family
- .clone()
- .unwrap_or_else(|| family_of(&catalogue, &row.expected).to_string());
- let got_family = got
- .first()
- .map(|g| family_of(&catalogue, g).to_string())
- .unwrap_or_else(|| "(none)".to_string());
- *report
- .confusion
- .entry(expected_family)
- .or_default()
- .entry(got_family)
- .or_default() += 1;
- }
- reports.push(report);
- }
-
- #[cfg(feature = "jev")]
- if let Some(report) = reports.iter_mut().find(|r| r.ranker == "jev") {
- // Tokens and cost: one detailed pass over the labelled rows so the
- // number is the provider's own `usage`, not an estimate.
- if let Some((_, detailed)) = jev_ranker(args.retrieval_k, args.family, args.embedding) {
- let mut tokens = 0_u64;
- let mut counted = 0_u64;
- for row in rows.iter().take(25) {
- if let Ok(ranking) = detailed
- .rank_detailed(&row.intent, &RankContext::empty(), &candidates, args.top_k)
- .await
- {
- if let Some(t) = ranking.input_tokens {
- tokens += t;
- counted += 1;
- }
- }
- }
- if counted > 0 {
- let per_search = tokens as f64 / counted as f64;
- report.input_tokens = per_search.round() as u64;
- report.usd = per_search * JEV_USD_PER_MILLION_INPUT / 1_000_000.0;
- }
- }
- }
-
- println!("| ranker | rows | top-1 | top-3 | retriever recall@{} | needless (of {}) | errors | p50 ms | p95 ms | tokens/search | USD/search |",
- args.retrieval_k,
- reports.first().map_or(0, |r| r.none_rows));
- println!("|---|---|---|---|---|---|---|---|---|---|---|");
- for r in &reports {
- let pct = |n: usize, d: usize| {
- if d == 0 {
- "n/a".to_string()
- } else {
- format!("{:.1}%", 100.0 * n as f64 / d as f64)
- }
- };
- println!(
- "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
- r.ranker,
- r.rows,
- pct(r.top1, r.labelled),
- pct(r.top3, r.labelled),
- pct(r.recall_at_20, r.labelled),
- r.needless,
- r.errors,
- r.percentile(0.5),
- r.percentile(0.95),
- if r.input_tokens == 0 {
- "-".to_string()
- } else {
- r.input_tokens.to_string()
- },
- if r.usd == 0.0 {
- "-".to_string()
- } else {
- format!("${:.5}", r.usd)
- },
- );
- }
- println!(
- "\n| ranker | source | labelled | top-1 | top-3 | recall@{} |",
- args.retrieval_k
- );
- println!("|---|---|---|---|---|---|");
- for r in &reports {
- for (source, (n, t1, t3, rk)) in &r.by_source {
- let pct = |x: usize| {
- if *n == 0 {
- "n/a".to_string()
- } else {
- format!("{:.1}%", 100.0 * x as f64 / *n as f64)
- }
- };
- println!(
- "| {} | {} | {} | {} | {} | {} |",
- r.ranker,
- source,
- n,
- pct(*t1),
- pct(*t3),
- pct(*rk)
- );
- }
- }
- for r in &reports {
- println!(
- "\n### {} — top-1 family confusion (expected → got)",
- r.ranker
- );
- for (expected, gots) in &r.confusion {
- let line: Vec<String> = gots.iter().map(|(g, n)| format!("{g}:{n}")).collect();
- println!("- {expected}: {}", line.join(", "));
- }
- if args.misses && !r.misses.is_empty() {
- println!("\n### {} — misses", r.ranker);
- for m in &r.misses {
- println!("- {:?} expected `{}` got {:?}", m.intent, m.expected, m.got);
- }
- }
- }
- if let Some(out) = &args.json_out {
- std::fs::write(out, serde_json::to_string_pretty(&reports)?)?;
- eprintln!("wrote {out:?}");
- }
- Ok(())
-}