From 728a7c3929e33f7dc9f6c99698e6f5c46163a587 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 22:35:36 +0800 Subject: [PATCH 1/4] fix: follow up the tool mode merge - The usage cache key fingerprints the whole tool definition, so a schema-only change no longer reuses the previous request's cost. - #2206 removed ExecStop after #2197 added its face; drop the face and the ShellSession page's stop wording, and align the dependency table with the part's injects. This restores the repository check. Refs #2135 --- .../src/context_usage.rs | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index c0a446a053..dae95bf5fc 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -1109,12 +1109,7 @@ impl ContextUsage { .request_tools(through) .await? .unwrap_or_else(|| self.registry.visible_definitions()); - let tools_fingerprint = fingerprint( - &tools - .iter() - .map(|tool| (&tool.name, &tool.description)) - .collect::>(), - )?; + let tools_fingerprint = fingerprint(&tools)?; let versions = format!("{versions}:{tools_fingerprint}"); if let Some(cached) = self .dynamic_fixed @@ -1454,3 +1449,26 @@ impl DynPlugin for ContextUsagePlugin { }) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_tool_fingerprint_covers_the_input_schema() { + let plain = crate::tool_registry::definition( + "execute", + "Run a command.", + serde_json::json!({"type": "object"}), + ); + let mut typed = plain.clone(); + typed.input_schema = serde_json::from_value(serde_json::json!({ + "type": "object", + "properties": {"command": {"type": "string"}}, + })) + .unwrap(); + let before = fingerprint(&vec![plain]).unwrap(); + let after = fingerprint(&vec![typed]).unwrap(); + assert_ne!(before, after, "a schema-only change changes the cache key"); + } +} From e75aca1d67e996392057ae06e79be7bfba2d1762 Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 23:18:05 +0800 Subject: [PATCH 2/4] fix: key the usage cache by the request, not its schemas A request always declares the same tools, so its position is the cache identity. Warm reads no longer serialize the declaration list; only the pre-request fallback hashes the live set. The standalone hash test is replaced by a flow test over a tool source whose schema changes: warm reads keep the fixed contribution, the next request prices the new schema. Refs #2135 --- .../src/context_usage.rs | 56 ++-- .../tests/context_flow/context_reads.rs | 240 ++++++++++++++++++ 2 files changed, 261 insertions(+), 35 deletions(-) diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index dae95bf5fc..c66b378555 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -1044,8 +1044,10 @@ impl ContextUsage { reading(through, &summary, None) } - /// The tools the last model request at or before `through` declared. - async fn request_tools(&self, through: u64) -> Result>> { + /// The tools the last model request at or before `through` declared, + /// with that request's position: the same request always declares the + /// same tools, so the position is their cache identity. + async fn request_tools(&self, through: u64) -> Result, u64)>> { let reply = self .timeline .query(TimelineQuery { @@ -1061,7 +1063,7 @@ impl ContextUsage { values: vec![serde_json::json!("model/call")], }), select: QuerySelect::Fields { - fields: vec!["data.request.tools".into()], + fields: vec!["data.request.tools".into(), "position.sequence".into()], }, group_by: vec![], pick: None, @@ -1076,10 +1078,13 @@ impl ContextUsage { }), }) .await?; - let Some(value) = (match &reply.result { + let Some((value, sequence)) = (match &reply.result { QueryOutput::Rows { rows } => { rows.first().and_then(|row| match row.values.as_slice() { - [QueryValue::Value { value }] => Some(value.clone()), + [ + QueryValue::Value { value }, + QueryValue::Value { value: sequence }, + ] => Some((value.clone(), sequence.as_u64()?)), _ => None, }) } @@ -1089,7 +1094,8 @@ impl ContextUsage { }; Ok(serde_json::from_value::>>(value) .ok() - .flatten()) + .flatten() + .map(|tools| (tools, sequence))) } async fn current_tools( @@ -1105,12 +1111,15 @@ impl ContextUsage { .map(|source| (&source.key, &source.version)) .collect::>(), )?; - let tools = self - .request_tools(through) - .await? - .unwrap_or_else(|| self.registry.visible_definitions()); - let tools_fingerprint = fingerprint(&tools)?; - let versions = format!("{versions}:{tools_fingerprint}"); + let (tools, identity) = match self.request_tools(through).await? { + Some((tools, sequence)) => (tools, format!("request:{sequence}")), + None => { + let tools = self.registry.visible_definitions(); + let identity = format!("live:{}", fingerprint(&tools)?); + (tools, identity) + } + }; + let versions = format!("{versions}:{identity}"); if let Some(cached) = self .dynamic_fixed .lock() @@ -1449,26 +1458,3 @@ impl DynPlugin for ContextUsagePlugin { }) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_tool_fingerprint_covers_the_input_schema() { - let plain = crate::tool_registry::definition( - "execute", - "Run a command.", - serde_json::json!({"type": "object"}), - ); - let mut typed = plain.clone(); - typed.input_schema = serde_json::from_value(serde_json::json!({ - "type": "object", - "properties": {"command": {"type": "string"}}, - })) - .unwrap(); - let before = fingerprint(&vec![plain]).unwrap(); - let after = fingerprint(&vec![typed]).unwrap(); - assert_ne!(before, after, "a schema-only change changes the cache key"); - } -} diff --git a/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs b/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs index a9c37a3203..557018c9f5 100644 --- a/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs +++ b/crates/dim-agent-capabilities/tests/context_flow/context_reads.rs @@ -5706,3 +5706,243 @@ async fn model_only_reload_hands_off_a_running_preparation_at_its_recovery_cut() .unwrap_or_else(|_| panic!("ModelProvider-only {window} handoff timed out")); } } + +struct SchemaSource { + sets: std::sync::Mutex>>, + emitter: Option<(Ctx, rutis::host::InstanceId)>, +} +impl PublicService for SchemaSource {} +impl SchemaSource { + fn shared() -> Arc { + Arc::new(Self { + sets: std::sync::Mutex::default(), + emitter: None, + }) + } + fn offered(&self, sets: Vec>) { + let (ctx, session) = self + .emitter + .as_ref() + .expect("offered after the source started"); + *self.sets.lock().unwrap() = sets; + ctx.emit(dim_agent_capabilities::tool_registry::ToolProviderChanged { + name: dim_agent_capabilities::tool_registry::tool_provider_changes(*session), + }) + .unwrap(); + } +} +impl dim_agent_capabilities::tool_registry::ToolProvider for SchemaSource { + fn sets(&self) -> Vec> { + self.sets.lock().unwrap().clone() + } +} + +struct SchemaHandler; +impl dim_agent_capabilities::tool_registry::ToolHandler for SchemaHandler { + fn execute( + &self, + _: ToolCall, + _: ToolExecutionContext, + _: CancellationToken, + ) -> HostFuture<'_, ToolResult> { + Box::pin(async { Ok(ToolResult::text("ok")) }) + } +} + +fn schema_set( + version: &str, + schema: serde_json::Value, +) -> Arc { + Arc::new(dim_agent_capabilities::tool_registry::ToolSourceSet { + key: "schema".into(), + version: version.into(), + tools: vec![Arc::new( + dim_agent_capabilities::tool_registry::ToolContribution { + definition: dim_agent_capabilities::tool_registry::definition( + "report", + "Report a result.", + schema, + ), + handler: Arc::new(SchemaHandler), + }, + )], + }) +} + +struct SchemaPlugin { + session: rutis::host::InstanceId, + key: Key, + tools: Key, + source: Arc, +} +impl DynPlugin for SchemaPlugin { + fn name(&self) -> &str { + "SchemaSource" + } + fn injects(&self) -> Vec { + vec![self.tools.erase()] + } + fn apply<'a>(&'a self, ctx: &'a Ctx) -> BoxFuture<'a, rutis::Result> { + Box::pin(async move { + let tools = ctx.require_at(&self.tools)?; + let source = Arc::new(SchemaSource { + sets: std::sync::Mutex::new(std::mem::take(&mut *self.source.sets.lock().unwrap())), + emitter: Some((ctx.clone(), self.session)), + }); + ctx.provide_at(self.key.clone(), source.clone())?; + tools.register_source(ctx, "schema", source)?; + Ok(Effect::Done) + }) + } +} + +fn add_schema_source(builder: &mut AgentBuilder, source: Arc) { + names::register::(builder.catalog_mut(), Some(SESSION_GROUP)); + builder.require_feature( + Feature::new("SchemaSource").session("SchemaSource", move |names| { + Ok(Box::new(SchemaPlugin { + session: names.instance(SESSION_GROUP)?, + key: names.key()?, + tools: names.key()?, + source: source.clone(), + })) + }), + ); +} + +#[tokio::test] +async fn usage_reuses_a_warm_request_and_prices_a_changed_tool_schema() { + use dim_agent_capabilities::context_preparation::ContextPreparation; + use dim_agent_capabilities::tool_registry::ToolSourcesView; + let counter = Arc::new(ObservedCounter::default()); + let source = SchemaSource::shared(); + source + .sets + .lock() + .unwrap() + .push(schema_set("1", serde_json::json!({"type": "object"}))); + let mut profile = builder_with_usage_resolver(counter.clone()); + add_schema_source(&mut profile, source.clone()); + let cell = Arc::new(std::sync::OnceLock::new()); + let capture = cell.clone(); + profile.require_feature(Feature::new("test.raw-timeline").branch( + "test.raw-timeline", + move |names| { + Ok(Box::new(super::manual_compaction::RawTimeline::new( + names, + capture.clone(), + )?)) + }, + )); + let agent = MinimalHost::start(&profile).await.unwrap(); + let session = agent + .create_session(SessionConfig::default(), Default::default()) + .await + .unwrap(); + let timeline = cell.get().unwrap(); + timeline + .append( + EventKind::ContextConfigured(ContextConfiguredData { + timeline: "main".into(), + revision: "fixture".into(), + previous: None, + prompt: None, + settings: Box::new(ModelConfiguration { + provider_id: "fixture".into(), + model_id: "counter".into(), + capability_snapshot: None, + tools: None, + tool_sources: vec![], + config: None, + metadata: None, + }), + system: None, + system_source: None, + }) + .into(), + ) + .unwrap(); + let preparation = session.service::("main").unwrap(); + session + .submit("bootstrap request".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let first = preparation.usage(CancellationToken::new()).await.unwrap(); + let counted = counter.fixed.load(Ordering::SeqCst); + let bytes = counter.fixed_value.lock().unwrap().0; + assert!( + counter + .fixed_value + .lock() + .unwrap() + .1 + .iter() + .any(|name| name == "report"), + "the request declares the source tool" + ); + for _ in 0..2 { + assert_eq!( + preparation + .usage(CancellationToken::new()) + .await + .unwrap() + .estimated_input_tokens, + first.estimated_input_tokens + ); + } + assert_eq!(counter.fixed.load(Ordering::SeqCst), counted); + assert_eq!(counter.fixed_value.lock().unwrap().0, bytes); + session + .session_service::() + .unwrap() + .offered(vec![schema_set( + "2", + serde_json::json!({ + "type": "object", + "properties": { + "query": {"type": "string"}, + "limit": {"type": "integer"}, + "flags": {"type": "array", "items": {"type": "string"}}, + } + }), + )]); + let view = session.session_service::().unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if view + .get() + .0 + .get("schema") + .and_then(|status| status.adopted.as_deref()) + == Some("2") + { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("source v2 visible"); + session + .submit("second".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let after = preparation.usage(CancellationToken::new()).await.unwrap(); + assert!( + after.estimated_input_tokens > first.estimated_input_tokens, + "the schema change is priced by the next request" + ); + let changed = counter.fixed_value.lock().unwrap().0; + assert!( + changed > bytes, + "the fixed contribution counts the new schema" + ); + let priced = counter.fixed.load(Ordering::SeqCst); + assert!(priced > counted, "the changed schema is counted again"); + let settled = preparation.usage(CancellationToken::new()).await.unwrap(); + assert_eq!(settled.estimated_input_tokens, after.estimated_input_tokens); + assert_eq!(counter.fixed.load(Ordering::SeqCst), priced); + agent.close().await.unwrap(); +} From 29079c5291d7a7b02adb0dec11e0a0decd4a3d4d Mon Sep 17 00:00:00 2001 From: scotares Date: Thu, 26 Nov 2026 23:52:01 +0800 Subject: [PATCH 3/4] fix: read the request tools only on a usage cache miss The warm path queries the last request's position and checks the fixed cache; data.request.tools is read and parsed only when the entry is absent. ShellSession.md now describes the shell, queue and handoff and gives BackgroundExec its actual job registration. Refs #2135 --- .../src/context_usage.rs | 74 +++++++++++++++---- 1 file changed, 59 insertions(+), 15 deletions(-) diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index c66b378555..860f103349 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -1044,10 +1044,8 @@ impl ContextUsage { reading(through, &summary, None) } - /// The tools the last model request at or before `through` declared, - /// with that request's position: the same request always declares the - /// same tools, so the position is their cache identity. - async fn request_tools(&self, through: u64) -> Result, u64)>> { + /// The position of the last model request at or before `through`. + async fn request_position(&self, through: u64) -> Result> { let reply = self .timeline .query(TimelineQuery { @@ -1063,7 +1061,7 @@ impl ContextUsage { values: vec![serde_json::json!("model/call")], }), select: QuerySelect::Fields { - fields: vec!["data.request.tools".into(), "position.sequence".into()], + fields: vec!["position.sequence".into()], }, group_by: vec![], pick: None, @@ -1078,13 +1076,53 @@ impl ContextUsage { }), }) .await?; - let Some((value, sequence)) = (match &reply.result { + Ok(match &reply.result { QueryOutput::Rows { rows } => { rows.first().and_then(|row| match row.values.as_slice() { - [ - QueryValue::Value { value }, - QueryValue::Value { value: sequence }, - ] => Some((value.clone(), sequence.as_u64()?)), + [QueryValue::Value { value }] => value.as_u64(), + _ => None, + }) + } + _ => None, + }) + } + + /// The tools the last model request at or before `through` declared. + async fn request_tools(&self, through: u64) -> Result>> { + let reply = self + .timeline + .query(TimelineQuery { + scope: TimelineQueryScope::Branch, + from: None, + through: Some(through), + include_publishing: false, + query: QuerySpec { + filter: Some(QueryFilter::In { + value: QueryOperand::Field { + path: "kind".into(), + }, + values: vec![serde_json::json!("model/call")], + }), + select: QuerySelect::Fields { + fields: vec!["data.request.tools".into()], + }, + group_by: vec![], + pick: None, + order_by: vec![QueryOrder { + key: QueryOrderKey::Position, + direction: TimelineQueryDirection::Descending, + }], + }, + page: Some(QueryPage { + limit: NonZeroU64::MIN, + after: None, + }), + }) + .await?; + let Some(value) = (match &reply.result { + QueryOutput::Rows { rows } => { + rows.first().and_then(|row| match row.values.as_slice() { + [QueryValue::Value { value }] => Some(value.clone()), _ => None, }) } @@ -1094,8 +1132,7 @@ impl ContextUsage { }; Ok(serde_json::from_value::>>(value) .ok() - .flatten() - .map(|tools| (tools, sequence))) + .flatten()) } async fn current_tools( @@ -1111,12 +1148,12 @@ impl ContextUsage { .map(|source| (&source.key, &source.version)) .collect::>(), )?; - let (tools, identity) = match self.request_tools(through).await? { - Some((tools, sequence)) => (tools, format!("request:{sequence}")), + let (identity, cached_tools) = match self.request_position(through).await? { + Some(sequence) => (format!("request:{sequence}"), None), None => { let tools = self.registry.visible_definitions(); let identity = format!("live:{}", fingerprint(&tools)?); - (tools, identity) + (identity, Some(tools)) } }; let versions = format!("{versions}:{identity}"); @@ -1131,6 +1168,13 @@ impl ContextUsage { { return Ok(cached.clone()); } + let tools = match cached_tools { + Some(tools) => tools, + None => self + .request_tools(through) + .await? + .unwrap_or_else(|| self.registry.visible_definitions()), + }; let mut system = self .fields(&configuration.event_id, through, &["data.system"]) .await?; From 9c5e9bce418b284b4480ddecc8e072f9ca83c576 Mon Sep 17 00:00:00 2001 From: scotares Date: Fri, 27 Nov 2026 00:28:41 +0800 Subject: [PATCH 4/4] fix: count a request's own tool declarations only A published request that omits tools no longer takes the live registry set on its cold read; the fallback stays for the pre-request window. The fixed contribution and its identity take the request's Option directly. Refs #2135 --- crates/dim-agent-capabilities/src/context_usage.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/dim-agent-capabilities/src/context_usage.rs b/crates/dim-agent-capabilities/src/context_usage.rs index 860f103349..de986e65f5 100644 --- a/crates/dim-agent-capabilities/src/context_usage.rs +++ b/crates/dim-agent-capabilities/src/context_usage.rs @@ -1169,11 +1169,8 @@ impl ContextUsage { return Ok(cached.clone()); } let tools = match cached_tools { - Some(tools) => tools, - None => self - .request_tools(through) - .await? - .unwrap_or_else(|| self.registry.visible_definitions()), + Some(tools) => Some(tools), + None => self.request_tools(through).await?, }; let mut system = self .fields(&configuration.event_id, through, &["data.system"]) @@ -1181,7 +1178,7 @@ impl ContextUsage { let system: Option = sources::optional(system.remove(0))?; let identity = fingerprint(&( &configuration.control_identity, - fingerprint(&(&system, &Some(&tools)))?, + fingerprint(&(&system, &tools))?, ))?; let previous = self .dynamic_fixed @@ -1196,7 +1193,7 @@ impl ContextUsage { .contribution_counter() .filter(|counter| counter.algorithm() == configuration.algorithm) .ok_or_else(|| fault("context counter algorithm changed"))?; - let fixed = previous.unwrap_or_else(|| counter.fixed(system.as_ref(), Some(&tools))); + let fixed = previous.unwrap_or_else(|| counter.fixed(system.as_ref(), tools.as_deref())); let value = DynamicFixed { configuration: configuration.event_id.clone(), versions,