zeph_core/agent/speculative/
mod.rs1pub mod cache;
32pub mod partial_json;
33pub mod paste;
34pub mod prediction;
35pub mod stream_drainer;
36
37use std::sync::Arc;
38use std::time::Duration;
39
40use tokio::time::Instant;
41use tokio_util::sync::CancellationToken;
42use tracing::debug;
43use zeph_common::SkillTrustLevel;
44use zeph_tools::{ErasedToolExecutor, ToolCall, ToolError, ToolOutput};
45
46use cache::{HandleKey, SpeculativeCache, SpeculativeHandle, hash_args, hash_context};
47use prediction::Prediction;
48
49pub use zeph_config::tools::{SpeculationMode, SpeculativeConfig};
50
51struct SweepHandle(zeph_common::task_supervisor::TaskHandle);
52
53impl SweepHandle {
54 fn abort(self) {
55 self.0.abort();
56 }
57}
58
59#[derive(Debug, Default, Clone)]
61pub struct SpeculativeMetrics {
62 pub committed: u32,
64 pub cancelled: u32,
66 pub evicted_oldest: u32,
68 pub skipped_confirmation: u32,
70 pub wasted_ms: u64,
72}
73
74pub struct SpeculationEngine {
92 executor: Arc<dyn ErasedToolExecutor>,
93 config: SpeculativeConfig,
94 cache: SpeculativeCache,
95 metrics: parking_lot::Mutex<SpeculativeMetrics>,
96 sweeper: Option<SweepHandle>,
97 task_supervisor: Option<Arc<zeph_common::TaskSupervisor>>,
100}
101
102impl SpeculationEngine {
103 #[must_use]
105 pub fn new(executor: Arc<dyn ErasedToolExecutor>, config: SpeculativeConfig) -> Self {
106 Self::new_with_supervisor(executor, config, None)
107 }
108
109 #[must_use]
114 pub fn new_with_supervisor(
115 executor: Arc<dyn ErasedToolExecutor>,
116 config: SpeculativeConfig,
117 supervisor: Option<Arc<zeph_common::TaskSupervisor>>,
118 ) -> Self {
119 let cache = SpeculativeCache::new(config.max_in_flight);
120
121 let shared = cache.shared_inner();
123
124 let sweeper_handle = if let Some(sup) = &supervisor {
125 let task_handle = sup.spawn(zeph_common::task_supervisor::TaskDescriptor {
128 name: "agent.speculative.sweeper",
129 restart: zeph_common::task_supervisor::RestartPolicy::RunOnce,
130 factory: move || {
131 let shared = Arc::clone(&shared);
132 async move {
133 let mut interval = tokio::time::interval(Duration::from_secs(5));
134 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
135 loop {
136 interval.tick().await;
137 SpeculativeCache::sweep_expired_inner(&shared);
138 }
139 }
140 },
141 });
142 Some(SweepHandle(task_handle))
143 } else {
144 None
145 };
146
147 Self {
148 executor,
149 config,
150 cache,
151 metrics: parking_lot::Mutex::new(SpeculativeMetrics::default()),
152 sweeper: sweeper_handle,
153 task_supervisor: supervisor,
154 }
155 }
156
157 #[must_use]
159 pub fn mode(&self) -> SpeculationMode {
160 self.config.mode
161 }
162
163 #[must_use]
165 pub fn is_active(&self) -> bool {
166 self.config.mode != SpeculationMode::Off
167 }
168
169 #[must_use]
171 pub fn confidence_threshold(&self) -> f32 {
172 self.config.confidence_threshold
173 }
174
175 pub fn try_dispatch(&self, prediction: &Prediction, trust_level: SkillTrustLevel) -> bool {
183 if trust_level != SkillTrustLevel::Trusted {
184 return false;
185 }
186
187 let tool_id = &prediction.tool_id;
188 if !self.executor.is_tool_speculatable_erased(tool_id.as_ref()) {
189 return false;
190 }
191
192 let call = prediction.to_tool_call(format!("spec-{}", uuid::Uuid::new_v4()));
193 let args_hash = hash_args(&call.params);
194 let context_hash = hash_context(call.context.as_ref());
195
196 if self.executor.requires_confirmation_erased(&call) {
199 let mut m = self.metrics.lock();
200 m.skipped_confirmation += 1;
201 debug!(tool_id = %tool_id, "speculative skip: requires_confirmation");
202 return false;
203 }
204
205 let exec = Arc::clone(&self.executor);
206 let call_clone = call.clone();
207 let cancel = CancellationToken::new();
208 let cancel_child = cancel.child_token();
209
210 let task_name: Arc<str> = Arc::from(format!(
211 "agent.speculative.dispatch.{}",
212 uuid::Uuid::new_v4()
213 ));
214 let sup = self.task_supervisor.clone().unwrap_or_else(|| {
218 Arc::new(zeph_common::TaskSupervisor::new(
219 tokio_util::sync::CancellationToken::new(),
220 ))
221 });
222 let join = sup.spawn_oneshot(task_name, move || async move {
223 tokio::select! {
224 result = exec.execute_tool_call_erased(&call_clone) => result,
225 () = cancel_child.cancelled() => {
226 Err(ToolError::Execution(std::io::Error::other("speculative cancelled")))
227 }
228 }
229 });
230
231 let handle = SpeculativeHandle {
232 key: HandleKey {
233 tool_id: tool_id.clone(),
234 args_hash,
235 context_hash,
236 },
237 join,
238 cancel,
239 ttl_deadline: Instant::now() + Duration::from_secs(self.config.ttl_seconds),
240 started_at: std::time::Instant::now(),
241 };
242
243 debug!(tool_id = %tool_id, confidence = prediction.confidence, "speculative dispatch");
244 self.cache.insert(handle);
245 true
246 }
247
248 pub async fn try_commit(
253 &self,
254 call: &ToolCall,
255 ) -> Option<Result<Option<ToolOutput>, ToolError>> {
256 let args_hash = hash_args(&call.params);
257 let context_hash = hash_context(call.context.as_ref());
258 if let Some(handle) = self
259 .cache
260 .take_match(&call.tool_id, &args_hash, &context_hash)
261 {
262 {
263 let mut m = self.metrics.lock();
264 m.committed += 1;
265 }
266 debug!(tool_id = %call.tool_id, "speculative commit");
267 Some(handle.commit().await)
268 } else {
269 None
270 }
271 }
272
273 pub fn cancel_for(&self, tool_id: &zeph_common::ToolName) {
277 debug!(tool_id = %tool_id, "speculative cancel for tool");
278 self.cache.cancel_by_tool_id(tool_id);
279 let mut m = self.metrics.lock();
280 m.cancelled += 1;
281 }
282
283 pub fn end_turn(&self) -> SpeculativeMetrics {
285 self.cache.cancel_all();
286 std::mem::take(&mut *self.metrics.lock())
287 }
288
289 #[must_use]
291 pub fn metrics_snapshot(&self) -> SpeculativeMetrics {
292 self.metrics.lock().clone()
293 }
294}
295
296impl Drop for SpeculationEngine {
297 fn drop(&mut self) {
298 self.cache.cancel_all();
299 if let Some(handle) = self.sweeper.take() {
300 handle.abort();
301 }
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308 use zeph_tools::{ToolCall, ToolError, ToolExecutor, ToolOutput};
309
310 struct AlwaysOkExecutor;
311
312 impl ToolExecutor for AlwaysOkExecutor {
313 async fn execute(&self, _: &str) -> Result<Option<ToolOutput>, ToolError> {
314 Ok(None)
315 }
316
317 async fn execute_tool_call(
318 &self,
319 _call: &ToolCall,
320 ) -> Result<Option<ToolOutput>, ToolError> {
321 Ok(Some(ToolOutput {
322 tool_name: zeph_common::ToolName::new("test"),
323 summary: "ok".into(),
324 blocks_executed: 1,
325 filter_stats: None,
326 diff: None,
327 streamed: false,
328 terminal_id: None,
329 locations: None,
330 raw_response: None,
331 claim_source: None,
332 }))
333 }
334
335 fn is_tool_speculatable(&self, _: &str) -> bool {
336 true
337 }
338 }
339
340 #[tokio::test]
341 async fn dispatch_and_commit_succeeds() {
342 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
343 let config = SpeculativeConfig {
344 mode: SpeculationMode::Decoding,
345 ..Default::default()
346 };
347 let engine = SpeculationEngine::new(exec, config);
348
349 let pred = Prediction {
350 tool_id: zeph_common::ToolName::new("test"),
351 args: serde_json::Map::new(),
352 confidence: 0.9,
353 source: prediction::PredictionSource::StreamPartial,
354 };
355
356 let dispatched = engine.try_dispatch(&pred, SkillTrustLevel::Trusted);
357 let _ = dispatched;
358 }
359
360 #[tokio::test]
361 async fn untrusted_skill_skips_dispatch() {
362 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
363 let config = SpeculativeConfig {
364 mode: SpeculationMode::Decoding,
365 ..Default::default()
366 };
367 let engine = SpeculationEngine::new(exec, config);
368
369 let pred = Prediction {
370 tool_id: zeph_common::ToolName::new("test"),
371 args: serde_json::Map::new(),
372 confidence: 0.9,
373 source: prediction::PredictionSource::StreamPartial,
374 };
375
376 let dispatched = engine.try_dispatch(&pred, SkillTrustLevel::Quarantined);
377 assert!(
378 !dispatched,
379 "untrusted skill must not dispatch speculatively"
380 );
381 }
382
383 #[tokio::test]
384 async fn cancel_for_removes_handle() {
385 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
386 let config = SpeculativeConfig {
387 mode: SpeculationMode::Decoding,
388 ..Default::default()
389 };
390 let engine = SpeculationEngine::new(exec, config);
391
392 let pred = Prediction {
393 tool_id: zeph_common::ToolName::new("test"),
394 args: serde_json::Map::new(),
395 confidence: 0.9,
396 source: prediction::PredictionSource::StreamPartial,
397 };
398
399 engine.try_dispatch(&pred, SkillTrustLevel::Trusted);
400 engine.cancel_for(&zeph_common::ToolName::new("test"));
402 assert!(
403 engine.cache.is_empty(),
404 "cancel_for must remove handle from cache"
405 );
406 }
407
408 #[tokio::test]
409 async fn end_turn_cancels_handles_and_resets_metrics() {
410 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
411 let config = SpeculativeConfig {
412 mode: SpeculationMode::Decoding,
413 ..Default::default()
414 };
415 let engine = SpeculationEngine::new(exec, config);
416
417 let pred = Prediction {
418 tool_id: zeph_common::ToolName::new("test"),
419 args: serde_json::Map::new(),
420 confidence: 0.9,
421 source: prediction::PredictionSource::StreamPartial,
422 };
423
424 engine.try_dispatch(&pred, SkillTrustLevel::Trusted);
425 assert!(
426 !engine.cache.is_empty(),
427 "precondition: handle must be in cache before end_turn"
428 );
429
430 let _metrics = engine.end_turn();
431 assert!(
432 engine.cache.is_empty(),
433 "end_turn must cancel all in-flight handles"
434 );
435
436 let snapshot = engine.metrics_snapshot();
438 assert_eq!(snapshot.committed, 0, "metrics must reset after end_turn");
439 assert_eq!(snapshot.cancelled, 0, "metrics must reset after end_turn");
440 }
441
442 #[tokio::test]
443 async fn is_active_reflects_mode() {
444 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
445
446 let engine_off = SpeculationEngine::new(
447 Arc::clone(&exec),
448 SpeculativeConfig {
449 mode: SpeculationMode::Off,
450 ..Default::default()
451 },
452 );
453 assert!(!engine_off.is_active(), "mode=Off means is_active()=false");
454
455 let engine_on = SpeculationEngine::new(
456 exec,
457 SpeculativeConfig {
458 mode: SpeculationMode::Decoding,
459 ..Default::default()
460 },
461 );
462 assert!(
463 engine_on.is_active(),
464 "mode=Decoding means is_active()=true"
465 );
466 }
467
468 #[tokio::test]
470 async fn sweeper_none_without_supervisor() {
471 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
472 let config = SpeculativeConfig {
473 mode: SpeculationMode::Decoding,
474 ..Default::default()
475 };
476
477 let engine = SpeculationEngine::new(Arc::clone(&exec), config);
480 assert!(
481 engine.sweeper.is_none(),
482 "sweeper must be None when no supervisor is provided"
483 );
484 drop(engine);
485 }
486
487 #[tokio::test]
489 async fn sweeper_supervised_aborted_on_drop() {
490 let exec: Arc<dyn ErasedToolExecutor> = Arc::new(AlwaysOkExecutor);
491 let config = SpeculativeConfig {
492 mode: SpeculationMode::Decoding,
493 ..Default::default()
494 };
495
496 let cancel = tokio_util::sync::CancellationToken::new();
497 let supervisor = Arc::new(zeph_common::TaskSupervisor::new(cancel));
498
499 let engine =
500 SpeculationEngine::new_with_supervisor(Arc::clone(&exec), config, Some(supervisor));
501 assert!(
502 engine.sweeper.is_some(),
503 "sweeper handle must be Some with supervisor"
504 );
505 drop(engine); }
507}