The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat: scale embedded library agent concurrency
Steven Enamakelc3f61aadc90f
diff --git a/docs/specs/2026-09-10-library-agent-host.md b/docs/specs/2026-09-10-library-agent-host.mdnew file mode 100644index 0000000000..51b852f587--- /dev/null+++ b/docs/specs/2026-09-10-library-agent-host.md@@ -0,0 +1,343 @@+# OpenHuman library host: one core, many agents++**Status:** in progress — library identity and JSONL lock sharding implemented;+the typed per-agent resource API and RSS gate remain proposed.++## Objective++OpenHuman must be usable as an in-process execution library by products such as+OpenCompany. One host starts one core and then creates many independently+configured agent handles over it. The first capacity target is 100 live agent+handles and 100 concurrent turns in one process, without an OpenHuman account or+login flow and without duplicating core-wide services per agent.++The host supplies all product policy and resources programmatically:++- provider id, OpenAI-compatible URL, credential, model and model capabilities;+- agent definition and system prompt;+- skills and MCP servers, including per-agent allowlists;+- workspace/action root, tool policy, access policy and persistence policy;+- optional memory, transcript and event sinks.++Library mode must never discover an operator's OpenHuman login, configuration,+skills, MCP servers or workspace as an implicit fallback.++## Current state++The existing embedding surface already provides two important pieces:++- `CoreBuilder` can start an in-process `CoreRuntime` without HTTP or background+ services.+- `embed::Core::agent()` can run concurrent routed turns against that runtime.++It does not yet provide the required ownership model:++1. `HarnessBuilder` owns and builds a core. `HARNESS_LIVE` consequently permits+ one harness per process. Removing the atomic is unsafe because several core+ resources are still process-scoped.+2. Resolved: `HostKind::Library` bypasses the desktop registration check for a+ routed caller-supplied provider. The default harness no longer writes a fake+ `Session::local` auth state.+3. `TurnRequest` can select a route and model but not an agent definition.+ `inference::local::ops::agent_chat` always builds the orchestrator.+4. Agent definitions come from the process-global `AgentDefinitionRegistry`;+ skills are copied into a workspace; MCP servers are installed into the+ core-wide static registry. Those are discovery/configuration mechanisms, not+ per-agent dependency injection.+5. Every turn constructs a full `Agent`, including its tool objects, prompt+ machinery, provider selection and session adapters.+6. Resolved for independent transcripts: OpenHuman's JSONL conversation store+ now uses a per-root lifecycle lock, per-root metadata lock and per-thread+ message locks. Shared `threads.jsonl` metadata fsyncs remain serialized+ within one root.++The desired model is therefore **not** 100 `Harness` or `CoreRuntime` values.+It is one library host with 100 cheap agent handles.++## Public API++Names below describe ownership and are not required to preserve the current+`Harness` naming.++```rust+let host = LibraryHost::builder()+ .workspace(host_workspace)+ .persistence(Persistence::Sqlite)+ .limits(HostLimits {+ max_concurrent_turns: 100,+ max_blocking_tasks: 16,+ ..Default::default()+ })+ .build()+ .await?;++let analyst = host.agent(+ AgentSpec::new("company-analyst")+ .prompt(analyst_prompt)+ .provider(+ ProviderSpec::openai_compatible(+ "opencompany-primary",+ provider_url,+ provider_credential,+ )+ .model("gpt-5"),+ )+ .skills(analyst_skills)+ .mcp_servers(company_mcp_servers)+ .tool_policy(analyst_tool_policy)+ .memory(MemoryPolicy::SharedNamespace("company".into())),+)?;++let session = analyst.session(SessionSpec::new("customer-42:analysis-7"))?;+let result = session.turn("Review this company").send().await?;+```++### Ownership++- `LibraryHost` owns the single `CoreRuntime`, shared provider transports,+ module runtimes, registries, stores, resource limits and shutdown.+- `AgentHandle` is an `Arc`-backed immutable compiled `AgentSpec`. Cloning it is+ cheap and does not open stores, spawn tasks or build a new HTTP client.+- `AgentSession` binds an agent to a conversation and mutable turn state. It+ serializes turns for its own session only. Different sessions run in+ parallel.+- `Turn` owns per-call overrides and cancellation. Dropping a handle never+ shuts down the host.++`LibraryHost`, `AgentHandle` and `AgentSession` must be `Send + Sync`.++### Provider input++`ProviderSpec` requires a stable provider id, endpoint, credential and model.+The provider id is not inferred from the URL and is used for pooling,+rate-limit state, metrics and redacted diagnostics. Credentials are stored in a+redacting secret type and are never written to `Config`, auth profiles or the+workspace.++A provider instance/cache is keyed by the fields that affect transport and+model behavior. Agents sharing a provider reuse its HTTP connection pool,+retry/rate-limit state and model profile.++### Definitions, skills and MCP++The host accepts values, not only filesystem locations:++- `AgentSpec` owns an `AgentDefinition` value. It never needs insertion into the+ process-global definition registry for a root turn.+- `SkillSource` supports an already parsed skill bundle and an explicitly named+ directory. Directory loading occurs once during agent compilation. Skills are+ immutable after the handle is returned.+- `McpServerSpec` is supplied as data. The host owns one connection per distinct+ server identity and agents hold allowlisted views over its tool catalog.++Sub-agent definitions form an immutable registry owned by the compiled agent+graph. The existing global registry remains a compatibility path for the+desktop, but library turns do not read it.++## Authentication and host policy++Add an explicit library host policy to `CoreContext`; do not identify library+mode by the absence of a token or by a magic local session.++```rust+pub enum HostKind {+ TauriShell,+ Cli,+ Docker,+ Library,+}+```++For `HostKind::Library`:++- routed providers do not call `verify_session_active`;+- no auth session is created, read, refreshed or cleared;+- managed OpenHuman inference and login-gated hosted APIs are unavailable+ unless the embedder explicitly installs a backend-auth port;+- provider credentials grant access only to their declared provider;+- tool authorization still comes from the supplied access/tool policy. Library+ mode is not an automatic `full` autonomy grant.++The bypass must consult the ambient `CoreContext` installed by dispatch. The+desktop, CLI and Docker paths retain their current registration gate exactly.++## Runtime composition++Introduce a minimal `DomainSet::library()` and `ServiceSet::library()` rather+than using `DomainSet::embedded()`, which currently includes Medulla, flows,+channels, integrations and automation for a different embedding use case.++The default library set includes only the kernel needed for agent turns:++- agent, config, security and inference;+- threads and memory only when the selected persistence/memory policy needs+ them;+- skills, MCP and runtimes only when at least one agent declares them;+- no desktop, hosted, Medulla, channels, cron, heartbeat, update, Socket.IO or+ HTTP server.++Core-wide services are initialized once. Agent construction must not start a+background service.++## Concurrency rules++The API distinguishes **live handles** from **in-flight turns**. One hundred+live handles should add only their compiled prompts, tool views and small+session metadata. In-flight turns additionally consume model context, tool+state and response buffers.++- A per-session async mutex prevents two turns from racing the same transcript+ and conversation state.+- No mutex spans provider I/O or tool execution across different sessions.+- A host semaphore provides configurable global backpressure. Reaching the+ limit waits or returns a typed overload error; it never creates unbounded+ queues.+- Per-provider semaphores support upstream rate limits without blocking other+ providers.+- Cancellation propagates through provider calls, tool execution and queued+ persistence work.++The default limit should be conservative and configurable. Supporting 100+concurrent turns means the implementation remains correct at 100; it does not+mean every machine should default to 100 simultaneous provider streams.++## Persistence++The JSONL conversation store no longer has a process-wide mutex: lifecycle is+coordinated per root, shared metadata per root, and transcript IO per thread.+Every message append still fsyncs shared `threads.jsonl` metadata, so SQLite WAL+remains the preferred durable path for sustained high write throughput.++The library path should use a store contract with two initial implementations:++- `InMemory`, for ephemeral agents and tests;+- SQLite in WAL mode, for durable sessions.++SQLite uses a small bounded connection pool, transactional message + thread+metadata writes, indexed thread reads and busy timeouts. WAL allows concurrent+readers while one short write transaction commits. Pool size is a host limit,+not proportional to the number of agents.++The desktop JSONL implementation may remain during migration, but the store+must be selected through the existing session-history/store seams rather than+by `HostKind` checks scattered through the turn path. A compatibility importer+can move old JSONL transcripts into SQLite; dual-writing is not part of the hot+path.++The immediate lock fix is implemented and stress-tested with 100 distinct+threads. It also shards message-file IO by thread, beyond merely keying the old+mutex by root. It does not remove the same-workspace metadata serialization+point.++## Memory budget++The implementation is accepted on measured retained memory, not only type+shape. Add a benchmark executable that records RSS at these checkpoints:++1. process start;+2. library host built;+3. 100 distinct `AgentHandle`s built;+4. 100 sessions idle;+5. 100 turns blocked on a mock streaming provider;+6. all turns complete and transient state is dropped.++The benchmark uses a local mock provider and fixed prompts/tool catalogs so it+is deterministic. CI records the measurements; a dedicated performance lane+can enforce thresholds once stable baselines exist.++Initial targets on Linux x86_64 release builds:++- 100 idle agent handles and sessions add no more than 64 MiB over the built+ host;+- provider clients and MCP connections scale by unique provider/server, not by+ agent;+- completed turns return to within 10% of the pre-turn retained-memory level+ after caches have warmed;+- no Tokio runtime uses a 16 MiB stack per agent. Stack allocation is per+ worker thread, and worker count is explicitly configured by the host.++### 2026-09-10 baseline++The repaired `library-profile fleet` scenario constructed 100 shipped+orchestrator `Agent` values in one process, then ran one overlapping mock turn+per agent on four Tokio workers. On this Linux host, the optimized build+measured 19,904 KiB RSS before construction, 290,828 KiB after construction+(2,709.24 KiB marginal RSS per agent), and 477,336 KiB after the load phase.+The 100-turn latency was p50 11 ms, p95 16 ms, p99 19 ms, max 22 ms.++That baseline proves the current full `Agent` is too heavy to serve as the+public live handle: 100 idle instances add about 265 MiB, well above the 64 MiB+target. The proposed `AgentHandle` therefore needs to retain only a compiled+immutable spec and shared resources; constructing and parking 100 current+`Agent` values is not the intended final architecture.++## Delivery sequence++### Milestone 1: correct library identity and selectable agents++- Add `HostKind::Library` and remove the local-session requirement for routed+ library turns only.+- Add `agent_id` to the typed turn request and route it to+ `Agent::from_config_for_agent`.+- Add a cheap `Core::agent_named(id)`/`AgentHandle` facade over the existing+ runtime.+- Prove 100 concurrent mock-provider turns on distinct session ids complete on+ one core with no auth state.++This milestone can initially use the core-wide definition/skill/MCP registries;+it establishes correct lifecycle and concurrency without pretending injection+is finished.++### Milestone 2: injected immutable agent graphs++- Accept `AgentDefinition`, skills, MCP specs and policies as values.+- Compile and cache shared provider/tool/MCP resources at `host.agent(...)`.+- Stop rebuilding immutable tools and provider clients for every turn.+- Keep the desktop registry/config loaders as adapters into the same compiled+ representation.++### Milestone 3: scalable stores and measurement++- Add in-memory and SQLite-WAL session/conversation stores through the existing+ history/store seams.+- Keep measuring the sharded JSONL path and replace the remaining per-root+ metadata serialization with SQLite WAL where sustained throughput needs it.+- Add the RSS/concurrency benchmark and flamegraph allocation checkpoints.++### Milestone 4: API stabilization++- Run OpenCompany on the library API without environment mutation or fake auth.+- Document shutdown, cancellation, overload and secret-handling guarantees.+- Deprecate `HarnessBuilder::session(Session::local(..))` for library-routed+ providers after downstream migration.++## Acceptance tests++The feature is complete when all of the following are automated:++1. A library host runs a routed turn with no auth-profile files and no backend+ calls.+2. Desktop/CLI custom-provider calls still fail without their required app+ session.+3. Two injected agents with different prompts, providers, skills and MCP+ allowlists cannot observe or call each other's resources.+4. One hundred sessions run concurrently against a deterministic mock provider;+ every response and progress stream is correlated to the correct agent and+ session.+5. Concurrent turns in the same session serialize; turns in different sessions+ overlap.+6. Provider HTTP clients and MCP connections are constructed once per unique+ identity.+7. No process-wide conversation mutex is acquired by the scalable store path.+8. The RSS benchmark reports the checkpoints and satisfies the adopted budget.++## Non-goals++- Multiple independent `CoreRuntime`s or workspaces in one process. That is a+ different multi-context problem and is unnecessary for many agents sharing+ one OpenCompany host.+- Treating agents as security boundaries inside one process. Untrusted tenants+ still require OS/container isolation.+- Running local heavyweight inference models once per agent. Local engines, if+ enabled, are core-owned shared resources.+- Making all 100 turns unbounded. Backpressure is part of the contract.diff --git a/examples/run_turn.rs b/examples/run_turn.rsindex 0878c83f7e..cb48c078c9 100644--- a/examples/run_turn.rs+++ b/examples/run_turn.rs@@ -26,7 +26,7 @@use std::path::PathBuf;use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};-use openhuman_core::{Access, Harness, Provider, Session, Workspace};+use openhuman_core::{Access, Harness, Provider, Workspace};fn main() -> anyhow::Result<()> {// Library embedders own logging. `RUST_LOG=debug` shows the `[embed]` and@@ -87,17 +87,13 @@ async fn run() -> anyhow::Result<()> {.workspace(Workspace::Ephemeral).provider(Provider::openai_compatible(base_url, api_key).model(model))// Let the agent's file tools look at the current directory.- .action_dir(std::env::current_dir()?)- // Routing at a custom endpoint is gated on an active app session,- // even though we just supplied the endpoint and its key. A local- // session satisfies that gate and asserts nothing at the backend.- .session(Session::local("run-turn-example"));+ .action_dir(std::env::current_dir()?);// The core still makes non-inference backend calls. Signed out of the// real one, those are rejected — and a rejection publishes- // `SessionExpired`, which fails the *next* turn's provider gate for- // reasons unrelated to the turn. Point them at your own backend if you- // have one.+ // Point them at your own backend if you have one. Authenticated+ // backend features additionally need a real Session::backend value;+ // caller-supplied inference itself does not.if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_BACKEND_URL") {builder = builder.backend_url(url);}diff --git a/src/bin/library_profile/scenarios/fleet.rs b/src/bin/library_profile/scenarios/fleet.rsindex bd6dc86780..00b5d8612c 100644--- a/src/bin/library_profile/scenarios/fleet.rs+++ b/src/bin/library_profile/scenarios/fleet.rs@@ -32,6 +32,7 @@ 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)@@ -115,7 +116,7 @@ fn build_agents(let stride = (n / 10).max(1);let mut agents = Vec::with_capacity(n);for i in 0..n {- match Agent::from_config_for_agent(config, "subconscious") {+ match Agent::from_config_for_agent(config, FLEET_AGENT_ID) {Ok(agent) => agents.push(agent),Err(err) => {eprintln!(@@ -287,6 +288,16 @@ mod tests {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());diff --git a/src/core/jsonrpc.rs b/src/core/jsonrpc.rsindex cc08aeeede..00a010e336 100644--- a/src/core/jsonrpc.rs+++ b/src/core/jsonrpc.rs@@ -2583,6 +2583,7 @@ pub async fn bootstrap_core_runtime(crate::core::types::HostKind::TauriShell => "tauri-shell",crate::core::types::HostKind::Cli => "cli",crate::core::types::HostKind::Docker => "docker",+ crate::core::types::HostKind::Library => "library",},},);diff --git a/src/core/types.rs b/src/core/types.rsindex 3378d117b7..2d1af93416 100644--- a/src/core/types.rs+++ b/src/core/types.rs@@ -157,6 +157,8 @@ pub struct AppState {/// - [`HostKind::Docker`] — containerised deployment. Same env honour-rule as/// CLI; the host shell is not the user's desktop so there is no UI surface/// to route an approval prompt to.+/// - [`HostKind::Library`] — an in-process embedding host that supplies its own+/// provider credentials and does not participate in OpenHuman app login.////// [`HostKind::detect_standalone`] picks `Docker` vs `Cli` for standalone/// invocations using the standard Docker signals (`/.dockerenv` or@@ -168,6 +170,7 @@ pub enum HostKind {TauriShell,Cli,Docker,+ Library,}impl HostKind {@@ -205,6 +208,7 @@ impl HostKind {HostKind::TauriShell => "tauri-shell",HostKind::Cli => "cli",HostKind::Docker => "docker",+ HostKind::Library => "library",}}}@@ -216,7 +220,7 @@ impl HostKind {/// - `override_ignored`: true when an env override was seen but suppressed/// (Tauri shell with override-requested)/// - `gate_disabled_by_override`: true when an env override was honored and-/// the gate is intentionally not installed (CLI / Docker)+/// the gate is intentionally not installed (CLI / Docker / library)////// Extracted as a pure function so the host-aware policy can be exercised/// in isolation without standing up the full `bootstrap_core_runtime` path.@@ -237,7 +241,7 @@ pub fn approval_gate_boot_decision(override_ignored: env_override_requested,gate_disabled_by_override: false,},- HostKind::Cli | HostKind::Docker => ApprovalGateBootDecision {+ HostKind::Cli | HostKind::Docker | HostKind::Library => ApprovalGateBootDecision {install_gate: !env_override_requested,override_ignored: false,gate_disabled_by_override: env_override_requested,@@ -416,6 +420,7 @@ mod tests {assert_eq!(HostKind::TauriShell.tag(), "tauri-shell");assert_eq!(HostKind::Cli.tag(), "cli");assert_eq!(HostKind::Docker.tag(), "docker");+ assert_eq!(HostKind::Library.tag(), "library");}#[test]@@ -423,6 +428,7 @@ mod tests {assert!(HostKind::TauriShell.is_desktop_shell());assert!(!HostKind::Cli.is_desktop_shell());assert!(!HostKind::Docker.is_desktop_shell());+ assert!(!HostKind::Library.is_desktop_shell());}#[test]@@ -476,7 +482,7 @@ mod tests {#[test]fn standalone_with_no_env_override_installs_gate_silently() {- for host in [HostKind::Cli, HostKind::Docker] {+ for host in [HostKind::Cli, HostKind::Docker, HostKind::Library] {let d = approval_gate_boot_decision(host, false);assert!(d.install_gate,diff --git a/src/embed/auth.rs b/src/embed/auth.rsindex a9effe0e88..43c1c9979a 100644--- a/src/embed/auth.rs+++ b/src/embed/auth.rs@@ -1,14 +1,12 @@//! Auth sub-facade — the session a turn runs under.//!-//! # Why an embedder needs this at all+//! # When an embedder needs this//!-//! A custom provider — anything other than the account's managed backend — is-//! gated on an active app-session JWT (`verify_session_active`,-//! `inference/provider/factory.rs`). The gate is there to stop an unregistered-//! desktop user from configuring every workload at a custom endpoint and-//! bypassing registration entirely; it is not aimed at a library host that was-//! handed an endpoint and a key by its own operator. But the check has no way to-//! tell those apart, so an embedder has to present a session like anyone else.+//! [`HostKind::Library`](crate::core::types::HostKind::Library) accepts a+//! caller-supplied provider without an OpenHuman app login. An embedder needs a+//! real session only when it also calls authenticated TinyHumans backend+//! services, or when it deliberately selects a desktop/standalone host mode+//! whose custom-provider policy still requires an active session.//!//! Before this existed, every embedder reached for `Core::raw()` and hand-wrote//! `openhuman.auth_store_session` — which is how an unrelated host ends up@@ -19,10 +17,10 @@//!//! [`Session::backend`] is a real JWT: it is validated against `GET /auth/me`//! before anything is persisted, and a failure means nothing is stored.-//! [`Session::local`] is the offline form — a token ending in `.local`, carrying-//! its own user payload, which the core recognizes and does not try to validate.-//! It authorizes nothing at the backend; it exists so a host with its own-//! credentials can satisfy a gate that was written about a different situation.+//! [`Session::local`] is the compatibility/offline form — a token ending in+//! `.local`, carrying its own user payload, which the core recognizes and does+//! not try to validate. It authorizes nothing at the backend and is not needed+//! by the default library harness.use std::sync::Arc;@@ -55,8 +53,8 @@ impl Session {/// wrong and be told only that validation failed.////// Grants nothing at the backend. Managed inference, billing and team calls- /// all still fail without a real session; what it unblocks is the- /// custom-provider gate.+ /// all still fail without a real session. The default library harness does+ /// not need this to use caller-supplied inference.pub fn local(user_id: impl Into<String>) -> Self {let user_id = user_id.into();Self {diff --git a/src/embed/harness/builder.rs b/src/embed/harness/builder.rsindex 65c5bae79d..b6f50a2c41 100644--- a/src/embed/harness/builder.rs+++ b/src/embed/harness/builder.rs@@ -57,7 +57,7 @@ impl HarnessBuilder {services: None,domains: None,tool_groups: None,- host_kind: HostKind::Cli,+ host_kind: HostKind::Library,config: None,session: None,backend_url: None,@@ -167,8 +167,8 @@ impl HarnessBuilder {self}- /// Identify the host to the core. Defaults to [`HostKind::Cli`], the- /// standalone bootstrap path.+ /// Identify the host to the core. Defaults to [`HostKind::Library`], which+ /// accepts caller-supplied provider credentials without OpenHuman app login.pub fn host_kind(mut self, host_kind: HostKind) -> Self {self.host_kind = host_kind;self@@ -177,13 +177,12 @@ impl HarnessBuilder {/// Point the core's backend calls at `url`.////// Even a harness running entirely on its own inference endpoint still- /// talks to a backend for everything that is not a completion — the session- /// check, integrations, billing, telemetry. Left unset, that is whatever+ /// can talk to a backend for everything that is not a completion —+ /// integrations, billing, telemetry. Left unset, that is whatever/// [`Config`] resolves to, which for a fresh config is the hosted/// TinyHumans backend: a harness with no real account will make live calls- /// there, be rejected, and — because a rejection publishes `SessionExpired`- /// — have its *next* turn fail the custom-provider gate for reasons that- /// have nothing to do with the turn.+ /// there and be rejected. Library-routed inference is independent of those+ /// calls, but the backend features themselves will still fail.////// Set it to a stub (or a self-hosted backend) whenever the harness is not/// signed in to the real one.@@ -194,13 +193,11 @@ impl HarnessBuilder {/// Install a session before the first turn.///- /// Routing a turn at a custom provider is gated on an active app session- /// (`verify_session_active`), so a harness given its own endpoint and key- /// **still needs one** — the gate cannot distinguish a library host from an- /// unregistered desktop user trying to skip registration.- ///- /// [`Session::backend`] for a real JWT; [`Session::local`] for a host that- /// brings its own provider credentials and needs nothing from the backend.+ /// The default [`HostKind::Library`] does not require an OpenHuman app+ /// login when the caller supplies a provider. Use [`Session::backend`] only+ /// when the embedded workload also calls authenticated TinyHumans backend+ /// services. [`Session::local`] remains available for compatibility with+ /// non-library host modes and offline tests.pub fn session(mut self, session: Session) -> Self {self.session = Some(session);self@@ -363,7 +360,7 @@ impl HarnessBuilder {// After the build, because storing a session is an ordinary RPC and// needs a dispatchable core. Before returning, so the harness a caller- // receives is one whose first turn will not fail the provider gate.+ // receives has the requested backend identity before its first turn.if let Some(session) = self.session {core.auth().store(session).await?;}diff --git a/src/embed/harness/builder_tests.rs b/src/embed/harness/builder_tests.rsindex cb4c2de838..39a6d33b19 100644--- a/src/embed/harness/builder_tests.rs+++ b/src/embed/harness/builder_tests.rs@@ -20,6 +20,11 @@ use crate::openhuman::config::Config;/// runtime.static GUARD: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());+#[test]+fn a_harness_identifies_as_a_library_host_by_default() {+ assert_eq!(HarnessBuilder::new().host_kind, HostKind::Library);+}+#[test]fn default_services_start_no_background_writers() {// cron, heartbeat and the memory queue each write to the workspace on theirdiff --git a/src/embed/harness/mod.rs b/src/embed/harness/mod.rsindex 8096a0ef56..f7c8f4ae6f 100644--- a/src/embed/harness/mod.rs+++ b/src/embed/harness/mod.rs@@ -2,16 +2,14 @@//!//! ```no_run//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {-//! use openhuman_core::{Access, Harness, Provider, Session, Workspace};+//! use openhuman_core::{Access, Harness, Provider, Workspace};//!//! let harness = Harness::builder()//! .provider(Provider::openai_compatible("https://api.example/v1", "sk-…").model("gpt-5"))//! .workspace(Workspace::Ephemeral)//! .access(Access::readonly())-//! // Both of these are effectively required when running on your own-//! // endpoint rather than a signed-in account — see "Running on your own-//! // endpoint" below. Omit them and the first turn fails SESSION_EXPIRED.-//! .session(Session::local("my-host"))+//! // Optional: point non-inference backend calls at the embedding+//! // product's backend. Caller-supplied inference needs no app login.//! .backend_url("https://my-backend.example")//! .build()//! .await?;@@ -41,20 +39,16 @@//!//! # Running on your own endpoint//!-//! Supplying a [`Provider`] is not quite the whole story, because two things in-//! the core are about the *account* rather than about where completions go:+//! A harness identifies as [`HostKind::Library`](crate::core::types::HostKind::Library)+//! by default. Supplying a [`Provider`] is therefore enough for inference: the+//! library host is trusted to supply its endpoint and credentials, without an+//! OpenHuman app login.//!-//! - Routing at a custom provider is gated on an active app session. The gate-//! exists to stop an unregistered desktop user configuring every workload at-//! a custom endpoint and skipping registration, and it cannot tell that case-//! apart from a library host holding operator-supplied credentials — so the-//! host presents a session like anyone else. [`Session::local`] satisfies it-//! without asserting anything at the backend.-//! - The core still makes non-inference backend calls (the session check,-//! integrations, telemetry). Left pointing at the hosted backend while signed-//! out, those are rejected — and a rejection publishes `SessionExpired`, which-//! fails the *next* turn's provider gate for reasons that have nothing to do-//! with the turn. [`HarnessBuilder::backend_url`] points them somewhere else.+//! The core can still make non-inference backend calls (integrations,+//! telemetry, managed services). Those need their own real session when the+//! endpoint requires one. [`HarnessBuilder::backend_url`] points them at the+//! embedding product's backend; [`HarnessBuilder::session`] installs a backend+//! identity when required.//!//! Neither applies to [`Provider::inherit`] with [`Workspace::Inherit`], which//! runs exactly as the installed app does, session included.diff --git a/src/embed/mod.rs b/src/embed/mod.rsindex 3b660b9d7e..04274de81b 100644--- a/src/embed/mod.rs+++ b/src/embed/mod.rs@@ -103,9 +103,9 @@ impl Core {/// Typed access to the session store.///- /// Needed more often than it looks: routing a turn at a custom provider is- /// gated on an active session, so a host bringing its own endpoint still- /// has to present one. See [`Session`].+ /// Use this when the embedded workload calls authenticated TinyHumans+ /// backend services. A [`HostKind::Library`](crate::core::types::HostKind::Library)+ /// runtime does not need an app session for caller-supplied inference.pub fn auth(&self) -> Auth<'_> {Auth(&self.rt)}diff --git a/src/lib.rs b/src/lib.rsindex ba4e67d5c4..048007795c 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -40,12 +40,11 @@ pub use embed::McpServer;////// ```no_run/// # async fn demo() -> Result<(), Box<dyn std::error::Error>> {-/// use openhuman_core::{Harness, Provider, Session, Workspace};+/// use openhuman_core::{Harness, Provider, Workspace};////// let harness = Harness::builder()/// .provider(Provider::openai_compatible("https://api.example/v1", "sk-…").model("gpt-5"))/// .workspace(Workspace::Ephemeral)-/// .session(Session::local("my-host"))/// .build()/// .await?;///diff --git a/src/openhuman/inference/provider/factory_part_03.rs b/src/openhuman/inference/provider/factory_part_03.rsindex 6cd974f4b1..9df135e6e6 100644--- a/src/openhuman/inference/provider/factory_part_03.rs+++ b/src/openhuman/inference/provider/factory_part_03.rs@@ -519,6 +519,18 @@ pub(crate) fn create_local_chat_model_from_string(/// construction-time chokepoint can never diverge on what "session active"/// means.pub(crate) fn verify_session_active(config: &Config) -> anyhow::Result<()> {+ // An in-process library host is given its provider URL and credential by+ // its caller. It does not participate in the OpenHuman app's registration+ // or auth-profile lifecycle, so requiring a fabricated local session here+ // would mix desktop product policy into the library contract. The ambient+ // context is installed by the dispatch chokepoint; all other host kinds+ // retain the registration gate below.+ if crate::core::runtime::context::CoreContext::current()+ .is_some_and(|ctx| ctx.host_kind() == crate::core::types::HostKind::Library)+ {+ return Ok(());+ }+// Fast path: the scheduler gate already knows the session is dead.if crate::openhuman::cron::scheduler_gate::is_signed_out() {anyhow::bail!(diff --git a/src/openhuman/memory/conversations/blocking.rs b/src/openhuman/memory/conversations/blocking.rsindex 2af5f8e402..8f18b2e46e 100644--- a/src/openhuman/memory/conversations/blocking.rs+++ b/src/openhuman/memory/conversations/blocking.rs@@ -17,35 +17,35 @@//! error strings and the `[conversations]` log prefix stay byte-identical —//! `web_chat::run_task` and the RPC layer read them.//!-//! Every store entry point is synchronous, and each one takes the-//! process-global `CONVERSATION_STORE_LOCK` — a-//! `parking_lot::Mutex` — and then does fsync'd JSONL file IO while holding it.-//! Calling one directly from an `async fn` therefore parks a tokio **worker**-//! thread for the whole wait, and the wait is not short:+//! Every store entry point is synchronous and does fsync'd JSONL file IO. The+//! store now coordinates lifecycle per conversation root, shared metadata per+//! root, and message files per thread, so unrelated agents no longer queue+//! behind one process-global mutex. Calling it directly from an `async fn`+//! can still park a tokio **worker** thread for disk latency or a contended+//! per-root lock, and the wait is not always short://!//! * `threads.jsonl` is folded from scratch on nearly every operation//! (`thread_index_unlocked`), and it grows by roughly two lines per appended//! message and is never compacted — so the per-call fold cost grows with the//! user's whole history;-//! * `append_message` writes two fsync'd appends under the lock, and-//! `update_message` reads and rewrites a thread's entire message log under it,-//! so a live streaming turn holds the lock repeatedly;+//! * `append_message` writes a message under its per-thread lock and serializes+//! the compact metadata append; `update_message` reads and rewrites an entire+//! thread log under that thread's lock;//! * `search_cross_thread_messages` reads every thread's transcript on a cold//! index.//!-//! Once more concurrent conversation operations than there are worker threads-//! are parked on that mutex, the runtime stops polling **anything** — including-//! the HTTP task that owes the client its response. That is how a create that+//! Historically, once more concurrent conversation operations than there were+//! worker threads parked on the global mutex, the runtime stopped polling+//! **anything** — including the HTTP task that owed the client its response.+//! That is how a create that//! only needs one append blows the frontend's 30 s RPC budget://! `UnhandledRejection: Core RPC openhuman.threads_create_new timed out after//! 30000ms` (Sentry TAURI-REACT-10, #5156).//!-//! Moving each call onto the blocking pool keeps the lock wait off the async-//! workers. The work is just as serialized as before — the store's lock still-//! decides who writes when — but the executor stays live, so the RPC server-//! keeps answering while a slow conversation operation drains, and a queued-//! create completes as soon as the lock frees instead of after the client has-//! given up.+//! Moving each call onto the blocking pool keeps disk and lock waits off the+//! async workers. Sharded store locks additionally let independent agent+//! threads perform their transcript IO concurrently; only their short shared+//! metadata appends remain serialized per conversation root.//!//! Callers pass owned arguments because the closure must be `'static`.diff --git a/src/openhuman/memory/conversations/blocking_tests.rs b/src/openhuman/memory/conversations/blocking_tests.rsindex 239c5be66e..d1f95f6b92 100644--- a/src/openhuman/memory/conversations/blocking_tests.rs+++ b/src/openhuman/memory/conversations/blocking_tests.rs@@ -78,10 +78,10 @@ async fn store_errors_surface_unchanged() {/// The starvation shape from #5156: several conversation operations in flight at/// once on a runtime with a **single** async worker. Each one contends for the-/// store's process-global mutex, so with the calls made inline the single worker-/// is parked in `lock()` and nothing else on the runtime can be polled. Off the-/// blocking pool they all complete, and a plain cooperative task keeps being-/// polled while they do.+/// same store scope, so with the calls made inline the single worker can be+/// parked in blocking disk or lock work and nothing else on the runtime can be+/// polled. Off the blocking pool they all complete, and a plain cooperative+/// task keeps being polled while they do.////// The cooperative ticker alone would not prove that: its 64 yields can all/// retire before any store task even reaches the lock, so it would stay greendiff --git a/src/openhuman/memory/conversations/mod.rs b/src/openhuman/memory/conversations/mod.rsindex e6eb369aff..5b662e2a63 100644--- a/src/openhuman/memory/conversations/mod.rs+++ b/src/openhuman/memory/conversations/mod.rs@@ -12,12 +12,12 @@//!//! Three parts, and the split is about ownership rather than size://!-//! - `store` — the implementation: on-disk format, the process-wide write-//! lock, the warm index cache, CRUD and search. Everything below is+//! - `store` — the implementation: on-disk format, root lifecycle and sharded+//! metadata/message locks, the warm index cache, CRUD and search. Everything below is//! re-exported from here, so callers name//! `crate::openhuman::memory::conversations::{…}` and never the subtree.//! - [`blocking`] — `spawn_blocking` wrappers. Every store entry point is-//! synchronous and takes a `parking_lot` mutex across fsync'd file IO, so an+//! synchronous and can take `parking_lot` locks across fsync'd file IO, so an//! `async fn` that calls one directly parks a tokio **worker** thread for the//! whole wait. Request paths must use these (#5156).//! - `bus` — the `core::bus` subscriber that mirrors inbound and processeddiff --git a/src/openhuman/memory/conversations/store/mod.rs b/src/openhuman/memory/conversations/store/mod.rsindex c775c9a8b6..6e8c8510bf 100644--- a/src/openhuman/memory/conversations/store/mod.rs+++ b/src/openhuman/memory/conversations/store/mod.rs@@ -19,7 +19,8 @@//! - [`tokenize`] — multilingual normalization + character n-gram tokenizer.//! - [`inverted_index`] — in-memory trigram/bigram index over message content.//! - [`store`] — the JSONL [`ConversationStore`] (append/read/update/delete,-//! process-wide write serialization, warm-index cache, cross-thread search).+//! root lifecycle coordination, per-root metadata and per-thread message+//! locks, warm-index cache, cross-thread search).//!//! The channel-persistence subscriber that mirrors inbound/processed channel//! turns into this store is the host's own [`super::bus`], not part of thisdiff --git a/src/openhuman/memory/conversations/store/store.rs b/src/openhuman/memory/conversations/store/store.rsindex 354a5a5bb8..c8ddb2dc89 100644--- a/src/openhuman/memory/conversations/store/store.rs+++ b/src/openhuman/memory/conversations/store/store.rs@@ -4,8 +4,8 @@//! `threads/<hex(thread_id)>.jsonl` so arbitrary provider ids remain//! filesystem-safe.//!-//! All on-disk mutations serialise through a single process-wide mutex so-//! concurrent RPC handlers don't interleave writes.+//! On-disk mutations synchronize at the narrowest safe scope: lifecycle per+//! conversation root, shared metadata per root, and messages per thread.//!//! This file is the store as it came back from the memory engine (#5560),//! unchanged apart from the one constructor described below. The three@@ -57,6 +57,8 @@ mod ops;#[path = "store_index.rs"]mod index;+#[path = "store_locks.rs"]+mod locks;/// Filename of the append-only thread metadata log, relative to the/// `memory/conversations` root.@@ -65,10 +67,6 @@ pub(super) const THREADS_FILENAME: &str = "threads.jsonl";/// per-thread message JSONL files, named `<hex(thread_id)>.jsonl`.pub(super) const THREAD_MESSAGES_DIR: &str = "threads";-/// Serialises every on-disk mutation so concurrent handlers can't interleave-/// writes to `threads.jsonl` or the per-thread message logs.-static CONVERSATION_STORE_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));-/// Per-workspace inverted index cache. Keyed by the workspace's/// `memory/conversations` root so multiple `ConversationStore` clones/// pointing at the same workspace share one index. The cache outlives@@ -80,28 +78,26 @@ static CONVERSATION_STORE_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::ne////// # Lock ordering///-/// When BOTH `CONVERSATION_STORE_LOCK` and `CONVERSATION_INDEX_CACHE`-/// must be held simultaneously, `CONVERSATION_STORE_LOCK` MUST be-/// acquired first. This applies to `append_message` (writes JSONL then-/// updates the warm index) and `with_index` (caller holds the outer-/// lock, then takes the cache lock to run the search closure).+/// Every operation first takes the root lifecycle lock. Message operations+/// then take their per-thread lock and briefly take the metadata lock when+/// they must inspect or append `threads.jsonl`. When metadata and the index+/// cache are both needed, metadata is acquired first. No code may acquire a+/// thread or metadata lock while holding `CONVERSATION_INDEX_CACHE`.////// `prime_index_if_cold` minimises shared locking. It may hold both-/// locks only momentarily, and always in the `CONVERSATION_STORE_LOCK`-/// → `CONVERSATION_INDEX_CACHE` order above: while holding the outer-/// lock to snapshot live thread IDs via `thread_index_unlocked`+/// metadata and index locks only momentarily, and always in the metadata+/// → `CONVERSATION_INDEX_CACHE` order above: while holding metadata+/// to snapshot live thread IDs via `thread_index_unlocked`/// (header-only, no per-thread I/O) it re-checks the cache once. It then-/// releases `CONVERSATION_STORE_LOCK` before reading per-thread JSONL-/// content (no lock held) and finally acquires `CONVERSATION_INDEX_CACHE`-/// alone to insert the built index. It never holds both across the slow-/// JSONL walk, and neither operation calls back into a function that-/// would acquire the other lock.+/// releases metadata before reading each transcript under that thread's own+/// lock and finally acquires `CONVERSATION_INDEX_CACHE` alone to insert the+/// built index. It never holds both across the slow JSONL walk.////// `list_threads_unlocked` MUST NOT be used inside the locked snapshot —/// it calls `measure_messages_unlocked` per legacy thread (no Stats/// history), which reads every per-thread JSONL file and appends a/// `Stats` entry to `threads.jsonl`, reintroducing the multi-second-/// stall under the outer lock that this design was built to avoid.+/// stall under the shared metadata lock that this design was built to avoid.static CONVERSATION_INDEX_CACHE: LazyLock<Mutex<HashMap<PathBuf, InvertedIndex>>> =LazyLock::new(|| Mutex::new(HashMap::new()));@@ -118,6 +114,7 @@ pub struct ConversationPurgeStats {#[derive(Debug, Clone)]pub struct ConversationStore {workspace_dir: PathBuf,+ locks: std::sync::Arc<locks::StoreLocks>,}impl ConversationStore {@@ -128,7 +125,22 @@ impl ConversationStore {/// `root_dir` in `store_index.rs`), so the caller's workspace is the whole/// input and there is nothing for a config type to add.pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }+ let root = workspace_dir.join("memory").join("conversations");+ let locks = locks::for_root(&root);+ Self {+ workspace_dir,+ locks,+ }+ }++ #[cfg(test)]+ pub(super) fn lock_identity_for_test(&self) -> usize {+ std::sync::Arc::as_ptr(&self.locks) as usize+ }++ #[cfg(test)]+ pub(super) fn thread_lock_identity_for_test(&self, thread_id: &str) -> usize {+ std::sync::Arc::as_ptr(&self.locks.thread(thread_id)) as usize}}diff --git a/src/openhuman/memory/conversations/store/store_concurrency_tests.rs b/src/openhuman/memory/conversations/store/store_concurrency_tests.rsnew file mode 100644index 0000000000..22cdc6f36b--- /dev/null+++ b/src/openhuman/memory/conversations/store/store_concurrency_tests.rs@@ -0,0 +1,59 @@+use super::*;++#[test]+fn one_hundred_agent_threads_append_without_loss_or_corruption() {+ use std::sync::{Arc, Barrier};++ let temp = TempDir::new().unwrap();+ let store = ConversationStore::new(temp.path().to_path_buf());+ let created_at = "2026-09-10T00:00:00Z".to_string();++ for index in 0..100 {+ store+ .ensure_thread(CreateConversationThread {+ parent_thread_id: None,+ id: format!("agent-{index}"),+ title: format!("Agent {index}"),+ created_at: created_at.clone(),+ labels: None,+ personality_id: None,+ })+ .unwrap();+ }++ let barrier = Arc::new(Barrier::new(101));+ let mut writers = Vec::with_capacity(100);+ for index in 0..100 {+ let store = store.clone();+ let barrier = Arc::clone(&barrier);+ let created_at = created_at.clone();+ writers.push(std::thread::spawn(move || {+ barrier.wait();+ store.append_message(+ &format!("agent-{index}"),+ ConversationMessage {+ id: format!("message-{index}"),+ content: format!("reply from agent {index}"),+ message_type: "text".to_string(),+ extra_metadata: serde_json::json!({}),+ sender: "assistant".to_string(),+ created_at,+ },+ )+ }));+ }+ barrier.wait();++ for writer in writers {+ writer.join().expect("writer panicked").expect("append");+ }++ let threads = store.list_threads().unwrap();+ assert_eq!(threads.len(), 100);+ assert!(threads.iter().all(|thread| thread.message_count == 1));+ for index in 0..100 {+ let messages = store.get_messages(&format!("agent-{index}")).unwrap();+ assert_eq!(messages.len(), 1);+ assert_eq!(messages[0].id, format!("message-{index}"));+ }+}diff --git a/src/openhuman/memory/conversations/store/store_index.rs b/src/openhuman/memory/conversations/store/store_index.rsindex ce4432201b..75e0747482 100644--- a/src/openhuman/memory/conversations/store/store_index.rs+++ b/src/openhuman/memory/conversations/store/store_index.rs@@ -13,14 +13,14 @@ use super::super::types::{ConversationMessage, ConversationThread};use super::{append_jsonl, hex_encode, infer_labels, normalize_labels, read_jsonl, ConversationPurgeStats,ConversationStore, ThreadIndexEntry, ThreadLogEntry, CONVERSATION_INDEX_CACHE,- CONVERSATION_STORE_LOCK, THREADS_FILENAME, THREAD_MESSAGES_DIR,+ THREADS_FILENAME, THREAD_MESSAGES_DIR,};impl ConversationStore {/// If no index entry exists for this workspace, snapshot the live thread- /// IDs under `CONVERSATION_STORE_LOCK` (fast — reads only `threads.jsonl`,- /// no per-thread I/O), release that lock, read all per-thread JSONL files- /// with no lock held (safe — append-only), then insert the built index+ /// IDs under the root metadata lock (fast — reads only `threads.jsonl`,+ /// no per-thread I/O), release it, read every JSONL file under its+ /// per-thread lock, then insert the built index/// into `CONVERSATION_INDEX_CACHE` using `entry().or_insert()` so a/// concurrent prime that finished first wins and ours is discarded.///@@ -32,9 +32,9 @@ impl ConversationStore {if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {return Ok(());}- // Snapshot live thread IDs while holding the outer lock.+ // Snapshot live thread IDs while holding the metadata lock.// `thread_index_unlocked` reads only `threads.jsonl` (header-only,- // O(threads), no per-thread file I/O) — the lock is released+ // O(threads), no per-thread file I/O) — metadata is released// immediately after, so the slow content reads below never block// concurrent writers.//@@ -42,23 +42,25 @@ impl ConversationStore {// thread has no `MessageAppended`/`Stats` history (common before the// Stats log was introduced), `list_threads_unlocked` triggers// `measure_messages_unlocked` + a `Stats` append per thread — all under- // `CONVERSATION_STORE_LOCK` — reintroducing the multi-second stall this+ // the metadata lock — reintroducing the multi-second stall this// function is designed to avoid.let thread_ids: Vec<String> = {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _metadata = self.locks.metadata.lock();// Re-check after acquiring: a concurrent prime may have just- // finished while we waited for the outer lock.+ // finished while we waited for metadata.if CONVERSATION_INDEX_CACHE.lock().contains_key(&key) {return Ok(());}self.thread_index_unlocked()?.into_keys().collect()};- // Build the index with no locks held. The per-thread JSONL files are- // append-only so reads are safe without synchronisation. A message+ // Build the index with no shared metadata lock held. Each JSONL file is+ // read under its own thread lock. A message// appended during this window stays absent from the in-memory index// until the next cold rebuild — the accepted tradeoff for issue #2849.let mut idx = InvertedIndex::new();for thread_id in &thread_ids {+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();let path = self.thread_messages_path(thread_id);if !path.exists() {continue;@@ -78,55 +80,21 @@ impl ConversationStore {Ok(())}- /// Acquire the cached inverted index for this workspace (building it from- /// JSONL on first access) and run `f` against it. Caller MUST hold- /// `CONVERSATION_STORE_LOCK` for the duration of the closure.- ///- /// In the normal path the index has already been warmed by- /// `prime_index_if_cold`, so the cold-build branch here is a safety net for- /// any future callers that bypass the priming step.+ /// Acquire the cached inverted index for this workspace and run `f` against+ /// it. `search_cross_thread_messages` warms it first while holding the+ /// root's lifecycle read guard, so purge cannot remove it between the two.pub(super) fn with_index<R>(&self,f: impl FnOnce(&mut InvertedIndex) -> R,) -> Result<R, String> {let key = self.root_dir();let mut cache = CONVERSATION_INDEX_CACHE.lock();- if !cache.contains_key(&key) {- let mut idx = InvertedIndex::new();- self.populate_index_unlocked(&mut idx)?;- cache.insert(key.clone(), idx);- }- let idx = cache.get_mut(&key).expect("inserted above if absent");+ let idx = cache+ .get_mut(&key)+ .ok_or_else(|| "conversation index missing after prime".to_string())?;Ok(f(idx))}- /// Walk every per-thread JSONL file in the workspace and insert each- /// message into `idx`. Used as the fallback cold-build path inside- /// `with_index`; `prime_index_if_cold` handles the normal first-access- /// case outside the outer lock. The JSONL files are the source of truth so- /// a rebuild after a process crash is always safe.- pub(super) fn populate_index_unlocked(&self, idx: &mut InvertedIndex) -> Result<(), String> {- // Caller (`with_index`) already holds `CONVERSATION_STORE_LOCK`, so we- // must NOT re-acquire it here — `parking_lot::Mutex` is not reentrant- // and doing so would deadlock. Use the `_unlocked` thread reader- // directly.- let threads = self.list_threads_unlocked()?;- for thread in threads {- let path = self.thread_messages_path(&thread.id);- if !path.exists() {- continue;- }- let messages = match read_jsonl::<ConversationMessage>(&path) {- Ok(m) => m,- Err(_) => continue,- };- for msg in messages {- idx.insert(&thread.id, msg);- }- }- Ok(())- }-/// Ensure the `memory/conversations` directory tree (and an empty/// `threads.jsonl`) exists, returning the conversation root.pub(super) fn ensure_root(&self) -> Result<PathBuf, String> {@@ -204,6 +172,62 @@ impl ConversationStore {}}+ Ok(Self::threads_from_index(index))+ }++ /// Fold and repair thread metadata without inverting the lock order used+ /// by message mutations. Recovery reads take the target thread lock before+ /// metadata; a newly-created thread discovered between passes is handled+ /// by the next iteration.+ pub(super) fn list_threads_coordinated(&self) -> Result<Vec<ConversationThread>, String> {+ loop {+ let (index, missing) = {+ let _metadata = self.locks.metadata.lock();+ let index = self.thread_index_unlocked()?;+ let missing = index+ .iter()+ .filter(|(_, entry)| {+ entry.message_count.is_none() || entry.last_message_at.is_none()+ })+ .map(|(thread_id, _)| thread_id.clone())+ .collect::<Vec<_>>();+ (index, missing)+ };+ if missing.is_empty() {+ return Ok(Self::threads_from_index(index));+ }++ for thread_id in missing {+ let thread_lock = self.locks.thread(&thread_id);+ let _thread = thread_lock.lock();+ let _metadata = self.locks.metadata.lock();+ let index = self.thread_index_unlocked()?;+ let Some(entry) = index.get(&thread_id) else {+ continue;+ };+ if entry.message_count.is_some() && entry.last_message_at.is_some() {+ continue;+ }+ let Ok((count, last_message_at)) = self.measure_messages_unlocked(&thread_id)+ else {+ // One unreadable transcript must not make navigation+ // unavailable or cause an unbounded retry loop.+ return Ok(Self::threads_from_index(index));+ };+ let resolved_last = last_message_at.unwrap_or_else(|| entry.created_at.clone());+ append_jsonl(+ &self.ensure_root()?.join(THREADS_FILENAME),+ &ThreadLogEntry::Stats {+ thread_id,+ message_count: count,+ last_message_at: resolved_last,+ },+ )?;+ }+ }+ }++ fn threads_from_index(index: BTreeMap<String, ThreadIndexEntry>) -> Vec<ConversationThread> {let mut threads: Vec<ConversationThread> = index.iter().map(|(thread_id, entry)| {@@ -231,7 +255,7 @@ impl ConversationStore {.cmp(×tamp_millis(&a.last_message_at)).then_with(|| timestamp_millis(&b.created_at).cmp(×tamp_millis(&a.created_at)))});- Ok(threads)+ threads}/// Count messages and find the newest timestamp by reading the per-threaddiff --git a/src/openhuman/memory/conversations/store/store_locks.rs b/src/openhuman/memory/conversations/store/store_locks.rsnew file mode 100644index 0000000000..2401abb449--- /dev/null+++ b/src/openhuman/memory/conversations/store/store_locks.rs@@ -0,0 +1,48 @@+//! Lock registry for the JSONL conversation store.+//!+//! A root owns shared metadata (`threads.jsonl`) and many independent message+//! files. Keeping those synchronization scopes separate lets unrelated agent+//! sessions write their message files concurrently while preserving atomic+//! metadata appends and purge semantics.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, LazyLock, Weak};++use parking_lot::{Mutex, RwLock};++#[derive(Debug, Default)]+pub(super) struct StoreLocks {+ /// Ordinary operations take a read guard; purge takes the write guard.+ pub(super) lifecycle: RwLock<()>,+ /// Serializes reads and appends of the root's shared `threads.jsonl`.+ pub(super) metadata: Mutex<()>,+ threads: Mutex<HashMap<String, Arc<Mutex<()>>>>,+}++impl StoreLocks {+ pub(super) fn thread(&self, thread_id: &str) -> Arc<Mutex<()>> {+ let mut locks = self.threads.lock();+ Arc::clone(+ locks+ .entry(thread_id.to_string())+ .or_insert_with(|| Arc::new(Mutex::new(()))),+ )+ }+}++/// Separate `ConversationStore::new` calls for the same root must coordinate.+/// Weak entries avoid retaining one lock set for every temporary workspace a+/// long-running process has ever touched.+static ROOTS: LazyLock<Mutex<HashMap<PathBuf, Weak<StoreLocks>>>> =+ LazyLock::new(|| Mutex::new(HashMap::new()));++pub(super) fn for_root(root: &Path) -> Arc<StoreLocks> {+ let mut roots = ROOTS.lock();+ if let Some(existing) = roots.get(root).and_then(Weak::upgrade) {+ return existing;+ }+ let locks = Arc::new(StoreLocks::default());+ roots.insert(root.to_path_buf(), Arc::downgrade(&locks));+ locks+}diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rsindex a96322dc58..306460fe7b 100644--- a/src/openhuman/memory/conversations/store/store_ops.rs+++ b/src/openhuman/memory/conversations/store/store_ops.rs@@ -12,7 +12,7 @@ use super::super::types::{use super::{append_jsonl, find_message_by_id, normalize_labels, read_jsonl, rewrite_jsonl,ConversationPurgeStats, ConversationStore, ThreadLogEntry, CONVERSATION_INDEX_CACHE,- CONVERSATION_STORE_LOCK, THREADS_FILENAME,+ THREADS_FILENAME,};impl ConversationStore {@@ -21,7 +21,10 @@ impl ConversationStore {&self,request: CreateConversationThread,) -> Result<ConversationThread, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(&request.id);+ let _thread = thread_lock.lock();+ let _metadata = self.locks.metadata.lock();let root = self.ensure_root()?;let threads_path = root.join(THREADS_FILENAME);let now = request.created_at.clone();@@ -44,15 +47,20 @@ impl ConversationStore {/// List all live threads (folding the upsert/delete log).pub fn list_threads(&self) -> Result<Vec<ConversationThread>, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();- self.list_threads_unlocked()+ let _lifecycle = self.locks.lifecycle.read();+ self.list_threads_coordinated()}/// Read every persisted message for a thread in append order.pub fn get_messages(&self, thread_id: &str) -> Result<Vec<ConversationMessage>, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();- if !self.thread_exists_unlocked(thread_id)? {- return Ok(Vec::new());+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ {+ let _metadata = self.locks.metadata.lock();+ if !self.thread_exists_unlocked(thread_id)? {+ return Ok(Vec::new());+ }}let path = self.thread_messages_path(thread_id);if !path.exists() {@@ -82,14 +90,14 @@ impl ConversationStore {////// # Lock strategy (issue #2849)///- /// **Fast path (warm cache):** acquires only `CONVERSATION_INDEX_CACHE`- /// — no outer store lock — and returns immediately.+ /// **Fast path (warm cache):** acquires the root lifecycle read guard and+ /// `CONVERSATION_INDEX_CACHE`, with no metadata or thread lock.////// **Cold path (first access):** snapshots the thread list under- /// `CONVERSATION_STORE_LOCK` (brief), then releases it before reading JSONL- /// files to build the inverted index. This avoids blocking other store- /// operations during the potentially-long rebuild. JSONL files are- /// append-only, so a concurrent write during the rebuild may mean the+ /// the root metadata lock (brief), then releases it before reading each+ /// JSONL file under its per-thread lock. This avoids blocking unrelated+ /// threads during the potentially-long rebuild. A concurrent write during+ /// the rebuild may mean the/// rebuilt index misses that one message until the cache is evicted and/// rebuilt — an accepted tradeoff for issue #2849.pub fn search_cross_thread_messages(@@ -98,14 +106,13 @@ impl ConversationStore {limit: usize,exclude_thread_id: Option<&str>,) -> Result<Vec<CrossThreadHit>, String> {- // Warm the index outside the outer lock so concurrent+ // Warm the index without the metadata lock so concurrent// append_message / get_messages calls are not stalled during the// cold JSONL rebuild. After this returns the cache entry is// guaranteed to exist, so with_index will not trigger a second// rebuild.+ let _lifecycle = self.locks.lifecycle.read();self.prime_index_if_cold()?;-- let _guard = CONVERSATION_STORE_LOCK.lock();self.with_index(|idx| idx.search(query, limit, exclude_thread_id))}@@ -129,16 +136,21 @@ impl ConversationStore {/// The lookup is deliberately narrow. Every other id in the store is/// UUID-fresh by construction and cannot be re-presented, so it must not/// pay to have that verified: a lookup on *every* append would put a scan- /// of the thread's transcript on the hot write path, under the- /// process-wide store lock, and make growing a thread quadratic.+ /// of the thread's transcript on every hot write and make growing a thread+ /// quadratic.pub fn append_message(&self,thread_id: &str,message: ConversationMessage,) -> Result<ConversationMessage, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();- if !self.thread_exists_unlocked(thread_id)? {- return Err(format!("thread {} not found", thread_id));+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ {+ let _metadata = self.locks.metadata.lock();+ if !self.thread_exists_unlocked(thread_id)? {+ return Err(format!("thread {} not found", thread_id));+ }}let path = self.thread_messages_path(thread_id);if is_deterministic_message_id(&message.id) {@@ -154,14 +166,17 @@ impl ConversationStore {// Bump the threads-log stat trail so subsequent `list_threads`// calls can compute (message_count, last_message_at) without// re-reading this file.- let threads_path = self.root_dir().join(THREADS_FILENAME);- append_jsonl(- &threads_path,- &ThreadLogEntry::MessageAppended {- thread_id: thread_id.to_string(),- last_message_at: message.created_at.clone(),- },- )?;+ {+ let _metadata = self.locks.metadata.lock();+ let threads_path = self.root_dir().join(THREADS_FILENAME);+ append_jsonl(+ &threads_path,+ &ThreadLogEntry::MessageAppended {+ thread_id: thread_id.to_string(),+ last_message_at: message.created_at.clone(),+ },+ )?;+ }// Keep the inverted index in sync. We only update if the index has// already been materialized for this workspace — otherwise the next// search will lazily rebuild and pick up this message anyway, and we@@ -182,7 +197,10 @@ impl ConversationStore {title: &str,updated_at: &str,) -> Result<ConversationThread, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ let _metadata = self.locks.metadata.lock();let index = self.thread_index_unlocked()?;let entry = index.get(thread_id)@@ -211,7 +229,10 @@ impl ConversationStore {labels: Vec<String>,updated_at: &str,) -> Result<ConversationThread, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ let _metadata = self.locks.metadata.lock();let index = self.thread_index_unlocked()?;let entry = index.get(thread_id)@@ -241,7 +262,9 @@ impl ConversationStore {message_id: &str,patch: ConversationMessagePatch,) -> Result<ConversationMessage, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();let path = self.thread_messages_path(thread_id);let mut messages = read_jsonl::<ConversationMessage>(&path)?;let mut updated: Option<ConversationMessage> = None;@@ -263,19 +286,24 @@ impl ConversationStore {/// Append a `Delete` entry and remove the thread's messages file. Returns/// `false` if the thread did not exist.pub fn delete_thread(&self, thread_id: &str, deleted_at: &str) -> Result<bool, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();- if !self.thread_exists_unlocked(thread_id)? {- return Ok(false);+ let _lifecycle = self.locks.lifecycle.read();+ let thread_lock = self.locks.thread(thread_id);+ let _thread = thread_lock.lock();+ {+ let _metadata = self.locks.metadata.lock();+ if !self.thread_exists_unlocked(thread_id)? {+ return Ok(false);+ }+ let root = self.ensure_root()?;+ let threads_path = root.join(THREADS_FILENAME);+ append_jsonl(+ &threads_path,+ &ThreadLogEntry::Delete {+ thread_id: thread_id.to_string(),+ deleted_at: deleted_at.to_string(),+ },+ )?;}- let root = self.ensure_root()?;- let threads_path = root.join(THREADS_FILENAME);- append_jsonl(- &threads_path,- &ThreadLogEntry::Delete {- thread_id: thread_id.to_string(),- deleted_at: deleted_at.to_string(),- },- )?;let messages_path = self.thread_messages_path(thread_id);match fs::remove_file(&messages_path) {Ok(()) => {}@@ -300,7 +328,8 @@ impl ConversationStore {/// Wipe the entire conversation directory and re-create an empty layout.pub fn purge_threads(&self) -> Result<ConversationPurgeStats, String> {- let _guard = CONVERSATION_STORE_LOCK.lock();+ let _lifecycle = self.locks.lifecycle.write();+ let _metadata = self.locks.metadata.lock();let stats = self.purge_stats_unlocked()?;let root = self.root_dir();if root.exists() {diff --git a/src/openhuman/memory/conversations/store/store_tests.rs b/src/openhuman/memory/conversations/store/store_tests.rsindex a9a982c07d..8524fdc115 100644--- a/src/openhuman/memory/conversations/store/store_tests.rs+++ b/src/openhuman/memory/conversations/store/store_tests.rs@@ -104,9 +104,9 @@ fn append_message_is_idempotent_by_message_id() {fn append_message_does_not_dedupe_client_generated_ids() {// The idempotency lookup is scoped to the ids the core mints// deterministically. Client-generated ids are UUID-fresh per message, so- // paying a transcript scan to verify that on every append would put a- // quadratic write path under the process-wide store lock — the store takes- // them at face value instead.+ // paying a transcript scan to verify that on every append would make the+ // per-thread write path quadratic — the store takes them at face value+ // instead.let (_temp, store) = make_store();store.ensure_thread(CreateConversationThread {diff --git a/src/openhuman/memory/conversations/store/store_tests_late.rs b/src/openhuman/memory/conversations/store/store_tests_late.rsindex 4927ae2dac..6566d6e40c 100644--- a/src/openhuman/memory/conversations/store/store_tests_late.rs+++ b/src/openhuman/memory/conversations/store/store_tests_late.rs@@ -174,6 +174,24 @@ fn read_jsonl_skips_invalid_lines_but_keeps_valid_ones() {assert_eq!(messages[1].id, "m2");}+#[test]+fn one_hundred_agent_threads_use_independent_message_locks() {+ let temp = TempDir::new().unwrap();+ let store = ConversationStore::new(temp.path().to_path_buf());+ let root_lock = store.lock_identity_for_test();+ let mut message_locks = std::collections::HashSet::new();++ for index in 0..100 {+ let clone = ConversationStore::new(temp.path().to_path_buf());+ assert_eq!(clone.lock_identity_for_test(), root_lock);+ assert!(+ message_locks.insert(clone.thread_lock_identity_for_test(&format!("agent-{index}")))+ );+ }++ assert_eq!(message_locks.len(), 100);+}+// ── concurrency: search cold rebuild must not block concurrent append ────────/// Regression test for issue #2849.@@ -181,14 +199,14 @@ fn read_jsonl_skips_invalid_lines_but_keeps_valid_ones() {/// Before the fix, `search_cross_thread_messages` held `CONVERSATION_STORE_LOCK`/// for the entire cold index rebuild, stalling every concurrent/// `append_message` call for as long as the rebuild took. The fix-/// moves the rebuild outside the outer lock (`prime_index_if_cold`), so-/// an append in flight during a cold rebuild acquires the outer lock-/// independently and completes promptly.+/// moved the rebuild outside that lock (`prime_index_if_cold`). The current+/// store additionally takes only the target thread lock while reading each+/// transcript, so unrelated appends complete independently.////// The test seeds a fresh workspace (cold cache), races a search against/// an append using a barrier, and asserts the append finishes within a/// generous timeout that would be violated if the two operations were-/// serialised through the outer lock.+/// serialized through one shared lock.#[test]fn search_cold_rebuild_does_not_block_concurrent_append() {use std::sync::{mpsc, Arc, Barrier};@@ -291,12 +309,13 @@ fn search_cold_rebuild_does_not_block_concurrent_append() {/// data written before the Stats log was introduced. When/// `list_threads_unlocked` encounters such threads it calls/// `measure_messages_unlocked` per thread and appends a `Stats` entry to-/// `threads.jsonl`, all while holding `CONVERSATION_STORE_LOCK`.+/// `threads.jsonl`, formerly while holding `CONVERSATION_STORE_LOCK` and now+/// while holding the root's metadata lock.////// `prime_index_if_cold` must NOT call `list_threads_unlocked`. It uses/// `thread_index_unlocked` (header-only, no per-thread I/O) to snapshot-/// thread IDs under the lock, then reads per-thread JSONL content outside-/// the lock. This test verifies that a cold search on such a workspace+/// thread IDs under the metadata lock, then reads each JSONL file under its+/// per-thread lock. This test verifies that a cold search on such a workspace/// still finds the correct messages, and that the former blocking code path/// is no longer reachable from `prime_index_if_cold`.#[test]@@ -346,7 +365,7 @@ fn prime_index_cold_build_works_on_legacy_workspace_without_stats() {}// Cold build on a pre-Stats workspace must index all messages without- // triggering measure_messages_unlocked under CONVERSATION_STORE_LOCK.+ // triggering measure_messages_unlocked under the metadata lock.let hits = store.search_cross_thread_messages("kitten", 10, None).expect("search on legacy workspace");@@ -476,3 +495,6 @@ fn legacy_workspace_cold_rebuild_does_not_block_concurrent_append() {search_result.err());}++#[path = "store_concurrency_tests.rs"]+mod concurrency;diff --git a/tests/harness_embed.rs b/tests/harness_embed.rsindex 69cd1c7681..38758e0911 100644--- a/tests/harness_embed.rs+++ b/tests/harness_embed.rs@@ -18,7 +18,7 @@use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};use openhuman_core::openhuman::config::Config;-use openhuman_core::{Access, Harness, Provider, Session, Workspace};+use openhuman_core::{Access, Harness, Provider, Workspace};use serde_json::json;use wiremock::matchers::{any, method, path};use wiremock::{Mock, MockServer, ResponseTemplate};@@ -74,118 +74,169 @@ fn runtime() -> tokio::runtime::Runtime {fn a_harness_runs_a_turn_against_the_provider_it_was_given() {let _ = env_logger::builder().is_test(true).try_init();- runtime().block_on(async {- // A stub backend. Not optional scenery: a harness that is not signed in- // to the real backend still makes non-inference calls (the session- // check, integrations), and a 401 from those publishes `SessionExpired`- // — which fails the *next* turn's custom-provider gate for reasons- // unrelated to the turn. Pointing the backend at a stub is what- // `backend_url` exists for.- let backend = MockServer::start().await;- Mock::given(any())- .respond_with(ResponseTemplate::new(200).set_body_json(json!({- "success": true,- "data": { "id": "harness-embed-test", "email": "[email protected]" }- })))- .mount(&backend)- .await;-- let provider_server = MockServer::start().await;- Mock::given(method("POST"))- .and(path("/v1/chat/completions"))- .respond_with(ResponseTemplate::new(200).set_body_json(chat_completion(REPLY)))- .mount(&provider_server)- .await;-- let harness = Harness::builder()- .config(offline_config())- .workspace(Workspace::Ephemeral)- .backend_url(backend.uri())- .provider(- Provider::openai_compatible(format!("{}/v1", provider_server.uri()), "sk-test")- .model("harness-embed-model"),- )- // Read-only: the turn has no business acting, and this keeps the- // test from depending on the approval gate's timing.- .access(Access::readonly())- // Routing at a custom provider is gated on an active app session,- // even though this harness was handed its own endpoint and key. A- // local session satisfies that gate without asserting anything at- // the backend — see `Session::local`.- .session(Session::local("harness-embed-test"))- .build()- .await- .expect("harness builds");-- // The workspace is the harness's own, not the operator's.- let workspace_dir = harness.workspace_dir().to_path_buf();- assert!(workspace_dir.is_dir(), "workspace was not created");- assert!(- !harness.action_dir().starts_with(&workspace_dir),- "action_dir must not sit inside the workspace, or every agent write \+ let runtime = runtime();+ runtime.block_on(async {+ // `Runtime::block_on` polls its root future on this test thread, whose+ // default stack is much smaller than the tuned worker stacks. Put the+ // agent host itself on a worker so the documented stack setting+ // actually applies to the large turn futures.+ tokio::spawn(async move {+ // A stub backend keeps incidental non-inference calls local. The+ // caller-supplied provider itself requires no app login in library+ // mode.+ let backend = MockServer::start().await;+ Mock::given(any())+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": true,+ "data": { "id": "harness-embed-test", "email": "[email protected]" }+ })))+ .mount(&backend)+ .await;++ let provider_server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/chat/completions"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_delay(std::time::Duration::from_millis(250))+ .set_body_json(chat_completion(REPLY)),+ )+ .mount(&provider_server)+ .await;++ let harness = std::sync::Arc::new(+ Harness::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .provider(+ Provider::openai_compatible(+ format!("{}/v1", provider_server.uri()),+ "sk-test",+ )+ .model("harness-embed-model"),+ )+ // Read-only: the turn has no business acting, and this keeps the+ // test from depending on the approval gate's timing.+ .access(Access::readonly())+ .build()+ .await+ .expect("harness builds"),+ );++ // The workspace is the harness's own, not the operator's.+ let workspace_dir = harness.workspace_dir().to_path_buf();+ assert!(workspace_dir.is_dir(), "workspace was not created");+ assert!(+ !harness.action_dir().starts_with(&workspace_dir),+ "action_dir must not sit inside the workspace, or every agent write \is blocked by is_workspace_internal_path"- );-- // No listener was bound: `ServiceSet` selects nothing that binds, and- // `serve()` was never called.- assert!(- std::env::var("OPENHUMAN_CORE_RPC_URL").is_err(),- "a library harness must not bind an RPC listener"- );-- let first = harness.run("Say the magic word.").await.expect("turn runs");- assert!(- first.reply.contains(REPLY),- "reply {:?} does not carry the provider's response",- first.reply- );- assert!(- !first.session_id.is_empty(),- "the harness must mint a session id — the core returns none, so \+ );++ // No listener was bound: `ServiceSet` selects nothing that binds, and+ // `serve()` was never called.+ assert!(+ std::env::var("OPENHUMAN_CORE_RPC_URL").is_err(),+ "a library harness must not bind an RPC listener"+ );++ let first = harness.run("Say the magic word.").await.expect("turn runs");+ assert!(+ first.reply.contains(REPLY),+ "reply {:?} does not carry the provider's response",+ first.reply+ );+ assert!(+ !first.session_id.is_empty(),+ "the harness must mint a session id — the core returns none, so \without this a caller cannot continue a conversation at all"- );-- // The turn went to the endpoint we named, not to the account's route.- let requests = provider_server- .received_requests()- .await- .expect("mock recorded requests");- assert!(- !requests.is_empty(),- "the provider endpoint received nothing — the per-call route was ignored"- );-- // Continuing a conversation reuses the caller's session id verbatim.- let second = harness- .turn("And again.")- .session(&first.session_id)- .send()- .await- .expect("second turn runs");- assert_eq!(second.session_id, first.session_id);-- // The session database landed in the harness's workspace.- assert!(- workspace_dir.join("session_db/sessions.db").exists(),- "sessions were not persisted under the harness workspace"- );-- // A second harness in this process must be refused rather than silently- // sharing process-global core state with the first.- let err = Harness::builder()- .workspace(Workspace::Ephemeral)- .build()- .await- .expect_err("a second harness must be refused");- assert!(- matches!(err, openhuman_core::HarnessError::AlreadyRunning),- "got {err:?}"- );-- drop(harness);- assert!(- !workspace_dir.exists(),- "an ephemeral workspace must be removed with its harness"- );+ );++ // The turn went to the endpoint we named, not to the account's route.+ let requests = provider_server+ .received_requests()+ .await+ .expect("mock recorded requests");+ assert!(+ !requests.is_empty(),+ "the provider endpoint received nothing — the per-call route was ignored"+ );++ // Continuing a conversation reuses the caller's session id verbatim.+ let second = harness+ .turn("And again.")+ .session(&first.session_id)+ .send()+ .await+ .expect("second turn runs");+ assert_eq!(second.session_id, first.session_id);++ // One core must support many live agents. The delayed provider makes+ // serialization observable: sequential execution would take at least+ // 25 seconds before agent construction and persistence overhead. All+ // futures are created together and each receives a distinct session,+ // matching a host such as OpenCompany running independent agents.+ let started = std::time::Instant::now();+ let mut turns = tokio::task::JoinSet::new();+ for index in 0..100 {+ let harness = std::sync::Arc::clone(&harness);+ turns.spawn(async move {+ harness+ .turn(format!("Concurrent agent {index}"))+ .session(format!("concurrent-agent-{index}"))+ .send()+ .await+ });+ }+ let mut outcomes = Vec::with_capacity(100);+ while let Some(outcome) = turns.join_next().await {+ outcomes.push(outcome.expect("concurrent turn task did not panic"));+ }+ let elapsed = started.elapsed();+ eprintln!("100 concurrent library turns completed in {elapsed:?}");+ assert!(+ elapsed < std::time::Duration::from_secs(20),+ "100 turns serialized instead of overlapping: {elapsed:?}"+ );+ let mut session_ids = std::collections::HashSet::new();+ for outcome in outcomes {+ let outcome = outcome.expect("concurrent turn runs");+ assert!(outcome.reply.contains(REPLY));+ assert!(session_ids.insert(outcome.session_id));+ }+ assert_eq!(session_ids.len(), 100);++ let requests = provider_server+ .received_requests()+ .await+ .expect("mock recorded concurrent requests");+ assert_eq!(requests.len(), 102, "two serial + 100 concurrent turns");++ // The session database landed in the harness's workspace.+ assert!(+ workspace_dir.join("session_db/sessions.db").exists(),+ "sessions were not persisted under the harness workspace"+ );++ // A second harness in this process must be refused rather than silently+ // sharing process-global core state with the first.+ let err = Harness::builder()+ .workspace(Workspace::Ephemeral)+ .build()+ .await+ .expect_err("a second harness must be refused");+ assert!(+ matches!(err, openhuman_core::HarnessError::AlreadyRunning),+ "got {err:?}"+ );++ drop(harness);+ assert!(+ !workspace_dir.exists(),+ "an ephemeral workspace must be removed with its harness"+ );+ })+ .await+ .expect("library host task did not panic");});}