The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: remove prompt cache segment middleware and its tests
Steven Enamakeled019d7bc460
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rsindex 8b6b1165f9..da4a1bf614 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs@@ -32,7 +32,6 @@ mod embedder_hooks;mod loop_guards;mod memory_protocol;mod packed_tool_route;-mod prompt_cache;mod repeated_failure;mod research_budget;mod tool_exposure;@@ -49,7 +48,6 @@ pub(crate) use embedder_hooks::EmbedderToolHooksMiddleware;pub(crate) use loop_guards::is_repeat_call_exempt;pub use memory_protocol::memory_protocol_middleware;pub(crate) use packed_tool_route::PackedToolRouteMiddleware;-pub(crate) use prompt_cache::PromptCacheSegmentMiddleware;pub(crate) use repeated_failure::RepeatedToolFailureMiddleware;pub(crate) use research_budget::ResearchBudgetMiddleware;pub(crate) use tool_exposure::OpenHumanToolExposureShadowMiddleware;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rsdeleted file mode 100644index adf9231254..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/prompt_cache.rs+++ /dev/null@@ -1,169 +0,0 @@-//! [`PromptCacheSegmentMiddleware`]: declare the turn's stable prompt prefix-//! (system prompt + tool schemas) as the harness-layout cache segments-//! (`system` / `tools`) with a content-derived request fingerprint, so the-//! crate `PromptCacheGuardMiddleware` has a prefix to protect and the provider-//! prompt-cache routing key stays stable across a thread's turns.--use async_trait::async_trait;-use sha2::{Digest, Sha256};--use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::Middleware;-use tinyinference_llm::message::Message as TaMessage;-use tinyinference_llm::model::{ModelRequest, PromptSegment, SegmentRole};--/// Stable SHA-256 fingerprint over canonical JSON. TinyAgents' prompt builder-/// uses the same shape for `ModelRequest::prompt_fingerprint`; OpenHuman builds-/// requests directly, so this adapter must stamp equivalent content-derived-/// segment ids and request fingerprints.-fn stable_prefix_fingerprint(value: &serde_json::Value) -> String {- let mut hasher = Sha256::new();- if serde_json::to_writer(&mut hasher, value).is_err() {- hasher = Sha256::new();- }- hasher- .finalize()- .iter()- .map(|byte| format!("{byte:02x}"))- .collect()-}--/// `before_model`: declare the turn's stable prompt prefix (system prompt + tool-/// schemas) as [`PromptSegment`]s on the [`ModelRequest`] (issue #4249, 03.2).-///-/// OpenHuman assembles the request's messages/tools directly rather than through-/// the crate prompt builder, so `cache_segments` would otherwise stay empty and-/// the crate `PromptCacheGuardMiddleware` (installed immediately after this)-/// would have no prefix to protect. The segments use the harness-layout ids-/// `system` (`system.1`, … per frozen system tier) and `tools` — exactly-/// those for an ordinary session. If a resumed session has no recoverable-/// frozen prefix, a noncacheable marker prevents the dispatch layer from-/// promoting its leading System history summary into one. The crate's-/// `refresh_prompt_cache_fingerprint` (agent_loop/run_loop.rs) recognises that-/// layout at dispatch and rebuilds `prompt_fingerprint` from the bytes actually-/// sent (system messages + tool schemas), so an unchanged system prompt +-/// tool-schema set yields the same fingerprint on every call of a thread, while-/// an injected timestamp/uuid/etc. or a changed tool schema flips it and the-/// guard records a-/// [`CacheLayoutEvent`](tinyagents_harness::cache::CacheLayoutEvent). Any-/// *other* id shape (an earlier version stamped `system:<sha>` / `tools:<sha>`)-/// is treated by the crate as a custom annotation and fingerprinted over the-/// **whole request**, which changed the provider `prompt_cache_key` on every-/// call — OpenRouter uses that key for sticky endpoint routing, so each call-/// re-rolled the endpoint and the per-endpoint prefix cache missed. This is-/// the structured, crate-native replacement for the deleted warn-only-/// `CacheAlignMiddleware` volatile-token scan (C3): the crate-/// `PromptCacheGuardMiddleware` now owns KV-cache-prefix drift detection via-/// recorded `CacheLayoutEvent`s. Read-only w.r.t. the transcript — only sets-/// `cache_segments` / `prompt_fingerprint`.-pub(crate) struct PromptCacheSegmentMiddleware;--/// Tools segment id the crate's `refresh_prompt_cache_fingerprint` recognises-/// as its own stable-prefix layout (system ids come from-/// `tinyagents_harness::prompt::system_segment_id`). Any other id opts the-/// request into whole-request fingerprinting (see the middleware docs).-const HARNESS_TOOLS_SEGMENT_ID: &str = "tools";-/// Explicitly opt out of auto-promoting a leading System history row when a-/// resumed session has no recoverable frozen prompt prefix.-const VOLATILE_SYSTEM_HISTORY_SEGMENT_ID: &str = "volatile-system-history";--#[async_trait]-impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for PromptCacheSegmentMiddleware-{- fn name(&self) -> &str {- "prompt_cache_segments"- }-- async fn before_model(- &self,- ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- _state: &(),- request: &mut ModelRequest,- ) -> TaResult<()> {- let mut segments: Vec<PromptSegment> = Vec::new();- // 1. System prompt — one segment per leading system message, named- // `system`, `system.1`, … exactly as the harness's- // `refresh_prompt_cache_fingerprint` expects. The session sends its- // prompt as tiers (stable+context, then volatile, see- // `runtime_session::prepare`), so a rewritten volatile tier shows up- // as a change to `system.1` while `system` keeps its id and the- // layout guard can say which tier moved.- let observed_leading_system = request- .messages- .iter()- .take_while(|m| matches!(m, TaMessage::System(_)))- .count();- let leading_system = match ctx.data.cacheable_system_prefix_len {- Some(frozen) => frozen.min(observed_leading_system),- None => {- // A new session renders its prefix during the first turn's- // prepare hook, after the run context was constructed. Learn- // that initial tier count once; later System summaries do not- // become new cacheable tiers within the run.- ctx.data.cacheable_system_prefix_len = Some(observed_leading_system);- observed_leading_system- }- };- for index in 0..leading_system {- segments.push(PromptSegment {- id: tinyagents_harness::prompt::system_segment_id(index),- role: SegmentRole::System,- cacheable: true,- });- }- // 2. Tool schemas — advertised tool surface identity (full schemas, in- // registration order) forms the next stable prefix segment. A changed- // tool surface legitimately busts the prefix; an unchanged one keeps- // it stable. Under a text dialect the harness folds the catalogue- // into the system prompt and clears `tools` *after* this hook ran,- // so declaring a `tools` segment here would no longer match the- // layout the harness rebuilds at dispatch — and a mismatch demotes- // the whole request to a per-call digest, which is exactly the- // routing-key churn this middleware exists to prevent.- let schemas_stay_on_wire = matches!(- ctx.data.tool_dialect,- tinyagents_harness::config::ToolDispatcher::Auto- | tinyagents_harness::config::ToolDispatcher::Native- );- if schemas_stay_on_wire && !request.tools.is_empty() {- segments.push(PromptSegment {- id: HARNESS_TOOLS_SEGMENT_ID.to_string(),- role: SegmentRole::Tools,- cacheable: true,- });- }- if segments.is_empty()- && matches!(ctx.data.cacheable_system_prefix_len, Some(0))- && observed_leading_system > 0- {- segments.push(PromptSegment {- id: VOLATILE_SYSTEM_HISTORY_SEGMENT_ID.to_string(),- role: SegmentRole::Volatile,- cacheable: false,- });- }- if !segments.is_empty() {- // Content-derived, so a guard reading it before dispatch sees a- // system-prompt or tool-schema edit; the crate recomputes it from- // the final bytes at dispatch.- // Steering nudges and other runtime notes may be System messages- // after the first user turn. They belong to the changing history,- // not to the cacheable leading system tiers declared above.- let system_messages: Vec<&TaMessage> =- request.messages.iter().take(leading_system).collect();- request.prompt_fingerprint = Some(stable_prefix_fingerprint(&serde_json::json!({- "system": system_messages,- "tools": &request.tools,- })));- tracing::debug!(- segment_count = segments.len(),- fingerprint = request.prompt_fingerprint.as_deref().unwrap_or(""),- "[cache] declared stable prompt-prefix segments for KV-cache guard"- );- request.cache_segments = segments;- }- Ok(())- }-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_prompt_cache_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_prompt_cache_tests.rsdeleted file mode 100644index b085e8ff47..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware_prompt_cache_tests.rs+++ /dev/null@@ -1,244 +0,0 @@-use super::*;--#[tokio::test]-async fn prompt_cache_segments_fingerprint_full_tool_schema() {- let mw = PromptCacheSegmentMiddleware;- let mut first =- ModelRequest::new(vec![TaMessage::system("sys")]).with_tools(vec![ToolSchema::new(- "lookup",- "lookup a user",- json!({- "type": "object",- "properties": {- "id": { "type": "string" }- },- }),- )]);- mw.before_model(&mut ctx(), &(), &mut first).await.unwrap();-- let mut second =- ModelRequest::new(vec![TaMessage::system("sys")]).with_tools(vec![ToolSchema::new(- "lookup",- "lookup a user",- json!({- "type": "object",- "properties": {- "id": { "type": "integer" }- },- }),- )]);- mw.before_model(&mut ctx(), &(), &mut second).await.unwrap();-- let first_tool_segment = first- .cache_segments- .iter()- .find(|segment| segment.role == SegmentRole::Tools)- .expect("tool segment");- let second_tool_segment = second- .cache_segments- .iter()- .find(|segment| segment.role == SegmentRole::Tools)- .expect("tool segment");-- // Segment ids are the harness-layout constants, never content-suffixed:- // `refresh_prompt_cache_fingerprint` only recognises exactly `system` /- // `tools`, and any other id is fingerprinted over the whole request, which- // re-rolls the provider `prompt_cache_key` (OpenRouter's sticky-routing- // key) on every call.- assert_eq!(first_tool_segment.id, "tools");- assert_eq!(second_tool_segment.id, "tools");- assert!(first.cache_segments.iter().all(|s| s.cacheable));- assert_eq!(- first- .cache_segments- .iter()- .find(|s| s.role == SegmentRole::System)- .expect("system segment")- .id,- "system"- );- // The content difference is carried by the request fingerprint instead.- assert_ne!(- first.prompt_fingerprint, second.prompt_fingerprint,- "same-name tools with different schemas must bust the stable prefix"- );- assert_eq!(- first.prompt_fingerprint.as_deref().unwrap().len(),- 64,- "request prompt fingerprints use TinyAgents' SHA-256 shape"- );-}--#[tokio::test]-async fn prompt_cache_segments_are_stable_across_a_threads_turns() {- // The whole point: two calls of one thread — same system prompt, same- // tools, longer conversation — must declare identical segments and an- // identical request fingerprint, so the provider routing key derived from- // them (`tap-<fingerprint>`) does not change turn to turn.- let mw = PromptCacheSegmentMiddleware;- let tools = vec![ToolSchema::new(- "lookup",- "lookup a user",- json!({ "type": "object", "properties": { "id": { "type": "string" } } }),- )];- let mut turn_one = ModelRequest::new(vec![TaMessage::system("sys"), TaMessage::user("hi")])- .with_tools(tools.clone());- let mut turn_two = ModelRequest::new(vec![- TaMessage::system("sys"),- TaMessage::user("hi"),- TaMessage::assistant("hello"),- TaMessage::user("and again, later"),- ])- .with_tools(tools);- mw.before_model(&mut ctx(), &(), &mut turn_one)- .await- .unwrap();- mw.before_model(&mut ctx(), &(), &mut turn_two)- .await- .unwrap();-- let ids = |r: &ModelRequest| {- r.cache_segments- .iter()- .map(|s| (s.id.clone(), s.role, s.cacheable))- .collect::<Vec<_>>()- };- assert_eq!(ids(&turn_one), ids(&turn_two));- assert_eq!(- ids(&turn_one),- vec![- ("system".to_string(), SegmentRole::System, true),- ("tools".to_string(), SegmentRole::Tools, true),- ]- );- assert_eq!(turn_one.prompt_fingerprint, turn_two.prompt_fingerprint);- assert!(turn_one.prompt_fingerprint.is_some());-}--#[tokio::test]-async fn prompt_cache_segments_ignore_system_nudges_after_the_user_turn() {- let mw = PromptCacheSegmentMiddleware;- let tools = vec![ToolSchema::new(- "shell",- "run a command",- json!({"type": "object"}),- )];- let prefix = vec![- TaMessage::system("stable"),- TaMessage::system("context"),- TaMessage::user("work on this"),- ];- let mut before = ModelRequest::new(prefix.clone()).with_tools(tools.clone());- let mut after = ModelRequest::new(- prefix- .into_iter()- .chain([TaMessage::system(- "[no progress since step 4] change strategy",- )])- .collect(),- )- .with_tools(tools);-- mw.before_model(&mut ctx(), &(), &mut before).await.unwrap();- mw.before_model(&mut ctx(), &(), &mut after).await.unwrap();-- assert_eq!(before.cache_segments, after.cache_segments);- assert_eq!(before.prompt_fingerprint, after.prompt_fingerprint);-}--#[tokio::test]-async fn prompt_cache_segments_do_not_promote_a_compaction_summary() {- let mw = PromptCacheSegmentMiddleware;- let mut run = ctx();- run.data.cacheable_system_prefix_len = Some(2);- let mut before = ModelRequest::new(vec![- TaMessage::system("stable"),- TaMessage::system("context"),- TaMessage::user("first"),- ]);- let mut after = ModelRequest::new(vec![- TaMessage::system("stable"),- TaMessage::system("context"),- TaMessage::system("changing history summary"),- TaMessage::user("later"),- ]);-- mw.before_model(&mut run, &(), &mut before).await.unwrap();- mw.before_model(&mut run, &(), &mut after).await.unwrap();-- assert_eq!(before.cache_segments, after.cache_segments);- assert_eq!(before.prompt_fingerprint, after.prompt_fingerprint);-}--#[tokio::test]-async fn prompt_cache_segments_keep_an_unrecoverable_prefix_uncacheable() {- let mw = PromptCacheSegmentMiddleware;- let mut run = ctx();- run.data.cacheable_system_prefix_len = Some(0);- let mut request = ModelRequest::new(vec![- TaMessage::system("history summary"),- TaMessage::user("continue"),- ]);-- mw.before_model(&mut run, &(), &mut request).await.unwrap();-- assert_eq!(request.cache_segments.len(), 1);- assert_eq!(request.cache_segments[0].role, SegmentRole::Volatile);- assert!(!request.cache_segments[0].cacheable);-}--#[tokio::test]-async fn prompt_cache_segments_name_each_system_tier_and_skip_tools_under_a_text_dialect() {- // Two leading system messages (stable+context, then volatile) are two- // segments named the way the harness's `refresh_prompt_cache_fingerprint`- // expects (`system`, `system.1`). Under a text dialect the harness folds- // the catalogue into the prompt and clears `tools` after this hook, so- // no `tools` segment is declared: declaring one would not match the- // rebuilt layout and would demote the request to a per-call digest.- let mw = PromptCacheSegmentMiddleware;- let tools = vec![ToolSchema::new(- "lookup",- "lookup a user",- json!({ "type": "object", "properties": { "id": { "type": "string" } } }),- )];- let messages = vec![- TaMessage::system("stable"),- TaMessage::system("volatile"),- TaMessage::user("hi"),- ];- let ids = |r: &ModelRequest| {- r.cache_segments- .iter()- .map(|s| (s.id.clone(), s.role))- .collect::<Vec<_>>()- };-- let mut native = ModelRequest::new(messages.clone()).with_tools(tools.clone());- mw.before_model(&mut ctx(), &(), &mut native).await.unwrap();- assert_eq!(- ids(&native),- vec![- ("system".to_string(), SegmentRole::System),- ("system.1".to_string(), SegmentRole::System),- ("tools".to_string(), SegmentRole::Tools),- ]- );-- let mut python_ctx = ctx();- python_ctx.data = python_ctx- .data- .clone()- .with_tool_dialect(tinyagents_harness::config::ToolDispatcher::Python);- let mut python = ModelRequest::new(messages).with_tools(tools);- mw.before_model(&mut python_ctx, &(), &mut python)- .await- .unwrap();- assert_eq!(- ids(&python),- vec![- ("system".to_string(), SegmentRole::System),- ("system.1".to_string(), SegmentRole::System),- ]- );- assert!(python.prompt_fingerprint.is_some());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex f7c8f66ddb..24cd259d71 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -396,8 +396,6 @@ mod approval_guard_tests;mod classified_failure_tests;#[path = "middleware_loop_guard_tests.rs"]mod loop_guard_tests;-#[path = "middleware_prompt_cache_tests.rs"]-mod prompt_cache_tests;#[path = "middleware_research_budget_tests.rs"]mod research_budget_tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/prompt_cache_golden_tests.rs b/crates/openhuman-core/src/agent/tinyagents/prompt_cache_golden_tests.rsindex 4b0c0a3077..7c49d64322 100644--- a/crates/openhuman-core/src/agent/tinyagents/prompt_cache_golden_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/prompt_cache_golden_tests.rs@@ -87,14 +87,12 @@ async fn run(s: &Scenario) -> Value {let mut policy = run_policy_for(8, false);policy.tool_dialect = s.dialect;harness.with_policy(policy);- harness.push_middleware(Arc::new(super::middleware::PromptCacheSegmentMiddleware)); // BEFORE-ONLYharness.push_middleware(Arc::new(PromptCacheGuardMiddleware::new()));let host = OpenHumanRunContext::new().with_tool_dialect(s.dialect);let mut ctx = host.into_tinyagents(RunConfig::new("golden"));if let Some(frozen) = s.frozen {ctx = ctx.with_frozen_system_prefix_len(frozen);- ctx.data.cacheable_system_prefix_len = Some(frozen); // BEFORE-ONLY}harness.invoke_in_context(&(), ctx, s.input.clone())