1use std::path::{Path, PathBuf};
18use std::time::Instant;
19
20use anyhow::{Result, bail};
21use ed25519_dalek::SigningKey;
22use serde::{Deserialize, Serialize};
23
24use super::build_request;
25use super::conditions::{Condition, DEFAULT_BUDGET_TOKENS, assemble};
26use super::model::{ModelFingerprint, ModelRequest, ModelRunner, PROVIDER_RECORDED};
27use super::scorers::score_task;
28use super::suite::EvalSuite;
29
30const SCHEMA_VERSION: u32 = 1;
31pub const KIND: &str = "lean-ctx.speed-proof";
32pub const DEFAULT_RUNS: usize = 3;
33
34#[derive(Debug, Clone, Copy)]
35pub struct SpeedConfig {
36 pub budget_tokens: usize,
38 pub runs: usize,
40}
41
42impl Default for SpeedConfig {
43 fn default() -> Self {
44 Self {
45 budget_tokens: DEFAULT_BUDGET_TOKENS,
46 runs: DEFAULT_RUNS,
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct SpeedTask {
54 pub task_id: String,
55 pub baseline_tokens: usize,
56 pub lean_ctx_tokens: usize,
57 pub baseline_context_digest: String,
58 pub lean_ctx_context_digest: String,
59 pub baseline_us: Vec<u64>,
61 pub lean_ctx_us: Vec<u64>,
62 pub baseline_passes: usize,
64 pub lean_ctx_passes: usize,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69pub struct SpeedSummary {
70 pub tasks: usize,
71 pub runs: usize,
72 pub baseline_median_us: u64,
74 pub lean_ctx_median_us: u64,
75 pub tasks_faster: usize,
77 pub baseline_context_tokens: usize,
78 pub lean_ctx_context_tokens: usize,
79 pub baseline_passes: usize,
80 pub lean_ctx_passes: usize,
81}
82
83impl SpeedSummary {
84 pub fn from_tasks(tasks: &[SpeedTask], runs: usize) -> Self {
85 let pooled = |pick: fn(&SpeedTask) -> &Vec<u64>| {
86 median(tasks.iter().flat_map(|t| pick(t).iter().copied()).collect())
87 };
88 Self {
89 tasks: tasks.len(),
90 runs,
91 baseline_median_us: pooled(|t| &t.baseline_us),
92 lean_ctx_median_us: pooled(|t| &t.lean_ctx_us),
93 tasks_faster: tasks
94 .iter()
95 .filter(|t| median(t.lean_ctx_us.clone()) < median(t.baseline_us.clone()))
96 .count(),
97 baseline_context_tokens: tasks.iter().map(|t| t.baseline_tokens).sum(),
98 lean_ctx_context_tokens: tasks.iter().map(|t| t.lean_ctx_tokens).sum(),
99 baseline_passes: tasks.iter().map(|t| t.baseline_passes).sum(),
100 lean_ctx_passes: tasks.iter().map(|t| t.lean_ctx_passes).sum(),
101 }
102 }
103
104 pub fn latency_reduction(&self) -> f64 {
106 if self.baseline_median_us == 0 {
107 return 0.0;
108 }
109 1.0 - self.lean_ctx_median_us as f64 / self.baseline_median_us as f64
110 }
111
112 pub fn quality_held(&self) -> bool {
114 self.lean_ctx_passes >= self.baseline_passes
115 }
116
117 pub fn is_headline(&self) -> bool {
119 self.latency_reduction() > 0.0 && self.quality_held()
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct SpeedProofV1 {
126 pub schema_version: u32,
127 pub kind: String,
128 pub created_at: String,
129 pub lean_ctx_version: String,
130 pub agent_id: String,
131 pub suite: String,
132 pub budget_tokens: usize,
133 pub model: ModelFingerprint,
135 pub tasks: Vec<SpeedTask>,
136 pub summary: SpeedSummary,
137 pub signer_public_key: Option<String>,
138 pub signature: Option<String>,
139}
140
141#[derive(Debug, Clone, PartialEq)]
142pub struct SpeedVerifyResult {
143 pub signature_valid: bool,
144 pub summary_matches: bool,
146 pub error: Option<String>,
147}
148
149impl SpeedVerifyResult {
150 pub fn ok(&self) -> bool {
151 self.signature_valid && self.summary_matches
152 }
153}
154
155impl SpeedProofV1 {
156 fn canonical_bytes(&self) -> Result<Vec<u8>, String> {
157 let mut clone = self.clone();
158 clone.signature = None;
159 clone.signer_public_key = None;
160 serde_json::to_vec(&clone).map_err(|e| format!("serialize for signing: {e}"))
161 }
162
163 pub fn sign(&mut self) -> Result<(), String> {
165 let key = crate::core::agent_identity::get_or_create_keypair(&self.agent_id)?;
166 self.sign_with_key(&key)
167 }
168
169 pub fn sign_with_key(&mut self, key: &SigningKey) -> Result<(), String> {
170 self.signature = None;
171 self.signer_public_key = None;
172 let sig = crate::core::agent_identity::sign_bytes_with(key, &self.canonical_bytes()?);
173 self.signer_public_key = Some(crate::core::agent_identity::hex_encode(
174 &key.verifying_key().to_bytes(),
175 ));
176 self.signature = Some(crate::core::agent_identity::hex_encode(&sig));
177 Ok(())
178 }
179
180 pub fn verify(&self) -> SpeedVerifyResult {
182 let summary_matches =
183 SpeedSummary::from_tasks(&self.tasks, self.summary.runs) == self.summary;
184 let fail = |msg: &str| SpeedVerifyResult {
185 signature_valid: false,
186 summary_matches,
187 error: Some(msg.to_string()),
188 };
189 let (Some(sig_hex), Some(pk_hex)) = (&self.signature, &self.signer_public_key) else {
190 return fail("proof is not signed");
191 };
192 let (Ok(sig), Ok(pk)) = (
193 crate::core::agent_identity::hex_decode(sig_hex),
194 crate::core::agent_identity::hex_decode(pk_hex),
195 ) else {
196 return fail("malformed signature or public key hex");
197 };
198 let canonical = match self.canonical_bytes() {
199 Ok(c) => c,
200 Err(e) => return fail(&e),
201 };
202 if crate::core::agent_identity::verify_signature(&pk, &canonical, &sig) {
203 SpeedVerifyResult {
204 signature_valid: true,
205 summary_matches,
206 error: (!summary_matches).then(|| "summary does not match the samples".to_string()),
207 }
208 } else {
209 fail("signature does not match payload (tampered or wrong key)")
210 }
211 }
212}
213
214pub fn run_speed(
217 suite: &EvalSuite,
218 suite_name: &str,
219 runner: &dyn ModelRunner,
220 cfg: SpeedConfig,
221 agent_id: &str,
222) -> Result<SpeedProofV1> {
223 if runner.fingerprint().provider == PROVIDER_RECORDED {
224 bail!("speed must be measured against a live model, not a recording");
225 }
226 if cfg.runs == 0 {
227 bail!("--runs must be at least 1");
228 }
229 suite.validate()?;
230
231 let mut prepared = Vec::with_capacity(suite.tasks.len());
232 for task in &suite.tasks {
233 let workspace = task.resolve_workspace_path(&suite.dir)?;
234 let base = assemble(
235 Condition::Baseline,
236 &workspace,
237 task.query(),
238 cfg.budget_tokens,
239 )?;
240 let lean = assemble(
241 Condition::LeanCtx,
242 &workspace,
243 task.query(),
244 cfg.budget_tokens,
245 )?;
246 prepared.push((task, workspace, base, lean));
247 }
248
249 if let Some((task, _, base, _)) = prepared.first() {
251 runner.run(&build_request(&base.text, &task.prompt))?;
252 }
253
254 let mut tasks = Vec::with_capacity(prepared.len());
255 for (index, (task, workspace, base, lean)) in prepared.iter().enumerate() {
256 let requests = [
257 build_request(&base.text, &task.prompt),
258 build_request(&lean.text, &task.prompt),
259 ];
260 let mut row = SpeedTask {
261 task_id: task.id.clone(),
262 baseline_tokens: base.tokens,
263 lean_ctx_tokens: lean.tokens,
264 baseline_context_digest: base.digest.clone(),
265 lean_ctx_context_digest: lean.digest.clone(),
266 baseline_us: Vec::with_capacity(cfg.runs),
267 lean_ctx_us: Vec::with_capacity(cfg.runs),
268 baseline_passes: 0,
269 lean_ctx_passes: 0,
270 };
271 for round in 0..cfg.runs {
272 for arm in arm_order(index, round) {
273 let (micros, text) = timed(runner, &requests[arm])?;
274 let passed = score_task(task, &text, workspace)?.passed;
275 if arm == 0 {
276 row.baseline_us.push(micros);
277 row.baseline_passes += usize::from(passed);
278 } else {
279 row.lean_ctx_us.push(micros);
280 row.lean_ctx_passes += usize::from(passed);
281 }
282 }
283 }
284 tasks.push(row);
285 }
286
287 let summary = SpeedSummary::from_tasks(&tasks, cfg.runs);
288 Ok(SpeedProofV1 {
289 schema_version: SCHEMA_VERSION,
290 kind: KIND.to_string(),
291 created_at: chrono::Utc::now().to_rfc3339(),
292 lean_ctx_version: env!("CARGO_PKG_VERSION").to_string(),
293 agent_id: agent_id.to_string(),
294 suite: suite_name.to_string(),
295 budget_tokens: cfg.budget_tokens,
296 model: runner.fingerprint().clone(),
297 tasks,
298 summary,
299 signer_public_key: None,
300 signature: None,
301 })
302}
303
304fn arm_order(task_index: usize, round: usize) -> [usize; 2] {
306 if (task_index + round).is_multiple_of(2) {
307 [0, 1]
308 } else {
309 [1, 0]
310 }
311}
312
313fn timed(runner: &dyn ModelRunner, request: &ModelRequest) -> Result<(u64, String)> {
314 let started = Instant::now();
315 let response = runner.run(request)?;
316 let micros = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
317 Ok((micros, response.text))
318}
319
320fn median(mut values: Vec<u64>) -> u64 {
321 if values.is_empty() {
322 return 0;
323 }
324 values.sort_unstable();
325 let mid = values.len() / 2;
326 if values.len().is_multiple_of(2) {
327 values[mid - 1].midpoint(values[mid])
328 } else {
329 values[mid]
330 }
331}
332
333fn speed_dir() -> Result<PathBuf, String> {
334 Ok(crate::core::data_dir::lean_ctx_data_dir()?
335 .join("value")
336 .join("speed"))
337}
338
339pub fn write_proof(proof: &SpeedProofV1, out: Option<&Path>) -> Result<PathBuf, String> {
341 let dir = speed_dir()?;
342 let path = out.map_or_else(
343 || {
344 let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ");
345 dir.join(format!("speed-proof-v1_{stamp}.json"))
346 },
347 Path::to_path_buf,
348 );
349 let json = serde_json::to_string_pretty(proof).map_err(|e| format!("serialize: {e}"))?;
350 for target in [path.as_path(), &dir.join("latest.json")] {
351 if let Some(parent) = target.parent() {
352 std::fs::create_dir_all(parent).map_err(|e| format!("mkdir: {e}"))?;
353 }
354 std::fs::write(target, &json).map_err(|e| format!("write {}: {e}", target.display()))?;
355 }
356 Ok(path)
357}
358
359pub fn load_proof(path: &Path) -> Result<SpeedProofV1, String> {
361 let raw = std::fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?;
362 let proof: SpeedProofV1 =
363 serde_json::from_str(&raw).map_err(|e| format!("parse {}: {e}", path.display()))?;
364 if proof.kind != KIND {
365 return Err(format!("not a {KIND} artifact (kind = {:?})", proof.kind));
366 }
367 Ok(proof)
368}
369
370pub fn latest_path() -> Option<PathBuf> {
371 speed_dir().ok().map(|d| d.join("latest.json"))
372}
373
374pub fn latest_verified() -> Option<SpeedProofV1> {
376 let proof = load_proof(&latest_path()?).ok()?;
377 proof.verify().ok().then_some(proof)
378}
379
380#[derive(Debug, Clone, PartialEq)]
383pub struct SpeedHeadline {
384 pub faster_pct: f64,
385 pub measured_on: String,
386 pub tasks: usize,
387 pub runs: usize,
388 pub model: String,
389}
390
391impl SpeedHeadline {
392 pub fn latest() -> Option<Self> {
393 Self::from_proof(&latest_verified()?)
394 }
395
396 pub fn from_proof(proof: &SpeedProofV1) -> Option<Self> {
397 let s = &proof.summary;
398 s.is_headline().then(|| Self {
399 faster_pct: s.latency_reduction() * 100.0,
400 measured_on: proof
401 .created_at
402 .get(..10)
403 .unwrap_or(&proof.created_at)
404 .to_string(),
405 tasks: s.tasks,
406 runs: s.runs,
407 model: proof.model.params.model.clone(),
408 })
409 }
410
411 pub fn phrase(&self) -> String {
413 format!(
414 "model answered {:.0}% faster with lean-ctx context",
415 self.faster_pct
416 )
417 }
418
419 pub fn detail(&self) -> String {
421 format!(
422 "measured {} · {} tasks × {} runs · {}",
423 self.measured_on, self.tasks, self.runs, self.model
424 )
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 use crate::core::eval_ab::model::{ModelParams, ModelResponse, PROVIDER_OPENAI};
432 use std::cell::RefCell;
433
434 struct Fake {
436 fp: ModelFingerprint,
437 calls: RefCell<Vec<usize>>,
438 }
439
440 impl ModelRunner for Fake {
441 fn fingerprint(&self) -> &ModelFingerprint {
442 &self.fp
443 }
444 fn run(&self, req: &ModelRequest) -> Result<ModelResponse> {
445 self.calls.borrow_mut().push(req.user.len());
446 Ok(ModelResponse::new("bm25 graph knowledge session"))
447 }
448 }
449
450 fn fake(provider: &str) -> Fake {
451 Fake {
452 fp: ModelFingerprint {
453 provider: provider.into(),
454 endpoint: "test".into(),
455 params: ModelParams {
456 model: "fixture".into(),
457 ..ModelParams::default()
458 },
459 },
460 calls: RefCell::new(Vec::new()),
461 }
462 }
463
464 fn suite(root: &Path) -> EvalSuite {
465 let ws = root.join("corpus");
466 std::fs::create_dir_all(&ws).unwrap();
467 std::fs::write(
468 ws.join("a-noise.md"),
469 "Unrelated notes about weather, cats, and lunch plans.\n".repeat(1_000),
470 )
471 .unwrap();
472 std::fs::write(
473 ws.join("z-answer.md"),
474 "Consolidation persists artifacts to bm25, graph, knowledge and session stores.",
475 )
476 .unwrap();
477 let raw = [
478 r#"{"id":"t1","domain":"qa","prompt":"Which stores does consolidation persist to?","workspace":"corpus","answers":["bm25 graph knowledge session"]}"#,
479 r#"{"id":"t2","domain":"qa","prompt":"Where does consolidation persist artifacts?","workspace":"corpus","answers":["bm25 graph knowledge session"]}"#,
480 ]
481 .join("\n");
482 EvalSuite::parse(&raw, root.to_path_buf()).unwrap()
483 }
484
485 fn task(id: &str, base: &[u64], lean: &[u64], passes: (usize, usize)) -> SpeedTask {
486 SpeedTask {
487 task_id: id.into(),
488 baseline_tokens: 4000,
489 lean_ctx_tokens: 900,
490 baseline_context_digest: "b".into(),
491 lean_ctx_context_digest: "l".into(),
492 baseline_us: base.to_vec(),
493 lean_ctx_us: lean.to_vec(),
494 baseline_passes: passes.0,
495 lean_ctx_passes: passes.1,
496 }
497 }
498
499 fn signed(tasks: Vec<SpeedTask>) -> (SpeedProofV1, SigningKey) {
500 let summary = SpeedSummary::from_tasks(&tasks, 3);
501 let mut proof = SpeedProofV1 {
502 schema_version: SCHEMA_VERSION,
503 kind: KIND.into(),
504 created_at: "2026-09-25T00:00:00Z".into(),
505 lean_ctx_version: "test".into(),
506 agent_id: "test".into(),
507 suite: "s".into(),
508 budget_tokens: 4000,
509 model: fake(PROVIDER_OPENAI).fp,
510 tasks,
511 summary,
512 signer_public_key: None,
513 signature: None,
514 };
515 let key = SigningKey::from_bytes(&[7u8; 32]);
516 proof.sign_with_key(&key).unwrap();
517 (proof, key)
518 }
519
520 #[test]
521 fn a_recording_cannot_prove_speed() {
522 let root = tempfile::tempdir().unwrap();
523 let err = run_speed(
524 &suite(root.path()),
525 "s",
526 &fake(PROVIDER_RECORDED),
527 SpeedConfig::default(),
528 "test",
529 )
530 .unwrap_err();
531 assert!(err.to_string().contains("live model"));
532 }
533
534 #[test]
535 fn warm_up_is_not_counted_and_the_first_arm_alternates() {
536 let root = tempfile::tempdir().unwrap();
537 let runner = fake(PROVIDER_OPENAI);
538 let cfg = SpeedConfig {
539 runs: 2,
540 ..SpeedConfig::default()
541 };
542 let proof = run_speed(&suite(root.path()), "s", &runner, cfg, "test").unwrap();
543
544 let calls = runner.calls.borrow();
545 assert_eq!(calls.len(), 1 + 2 * 2 * 2);
547 let first_arms: Vec<bool> = calls[1..].chunks(2).map(|pair| pair[0] > pair[1]).collect();
549 assert_eq!(first_arms, vec![true, false, false, true]);
550
551 for row in &proof.tasks {
552 assert_eq!(row.baseline_us.len(), 2);
553 assert_eq!(row.lean_ctx_us.len(), 2);
554 assert!(row.lean_ctx_tokens < row.baseline_tokens);
555 assert_eq!(row.lean_ctx_passes, 2);
556 }
557 assert_eq!(proof.summary.lean_ctx_passes, 4);
558 }
559
560 #[test]
561 fn summary_uses_pooled_medians_and_scores_quality() {
562 let tasks = vec![
563 task("a", &[100, 120, 110], &[60, 70, 65], (3, 3)),
564 task("b", &[200, 210, 190], &[220, 230, 210], (3, 3)),
565 ];
566 let s = SpeedSummary::from_tasks(&tasks, 3);
567 assert_eq!(s.baseline_median_us, 155);
568 assert_eq!(s.lean_ctx_median_us, 140);
569 assert_eq!(s.tasks_faster, 1);
570 assert!(s.is_headline());
571
572 let worse = SpeedSummary::from_tasks(&[task("a", &[100], &[50], (1, 0))], 1);
573 assert!(worse.latency_reduction() > 0.0);
574 assert!(!worse.is_headline(), "faster but worse is not a headline");
575 }
576
577 #[test]
578 fn verify_catches_an_edited_summary_and_a_forged_sample() {
579 let (proof, key) = signed(vec![task("a", &[100, 120, 110], &[60, 70, 65], (3, 3))]);
580 assert!(proof.verify().ok());
581
582 let mut edited = proof.clone();
583 edited.summary.lean_ctx_median_us = 1;
584 assert!(!edited.verify().ok());
585
586 let mut forged = proof.clone();
588 forged.tasks[0].lean_ctx_us = vec![1, 1, 1];
589 forged.sign_with_key(&key).unwrap();
590 let result = forged.verify();
591 assert!(result.signature_valid && !result.summary_matches);
592 }
593
594 #[test]
595 fn write_then_load_roundtrips() {
596 let dir = tempfile::tempdir().unwrap();
597 let (proof, _) = signed(vec![task("a", &[100], &[60], (1, 1))]);
598 let out = dir.path().join("p.json");
599 let json = serde_json::to_string_pretty(&proof).unwrap();
600 std::fs::write(&out, json).unwrap();
601 let loaded = load_proof(&out).unwrap();
602 assert_eq!(loaded, proof);
603 assert!(loaded.verify().ok());
604
605 std::fs::write(&out, r#"{"kind":"other"}"#).unwrap();
606 assert!(load_proof(&out).is_err());
607 }
608
609 #[test]
610 fn only_a_faster_and_not_worse_proof_becomes_a_headline() {
611 let (good, _) = signed(vec![task("a", &[100, 120, 110], &[60, 70, 65], (3, 3))]);
612 let h = SpeedHeadline::from_proof(&good).unwrap();
613 assert_eq!(
614 h.phrase(),
615 "model answered 41% faster with lean-ctx context"
616 );
617 assert_eq!(
618 h.detail(),
619 "measured 2026-09-25 · 1 tasks × 3 runs · fixture"
620 );
621
622 let (worse, _) = signed(vec![task("a", &[100, 120, 110], &[60, 70, 65], (3, 2))]);
623 assert!(SpeedHeadline::from_proof(&worse).is_none());
624 let (slower, _) = signed(vec![task("a", &[60, 70, 65], &[100, 120, 110], (3, 3))]);
625 assert!(SpeedHeadline::from_proof(&slower).is_none());
626 }
627
628 #[test]
629 fn median_handles_even_odd_and_empty() {
630 assert_eq!(median(vec![]), 0);
631 assert_eq!(median(vec![3, 1, 2]), 2);
632 assert_eq!(median(vec![1, 2, 3, 4]), 2);
633 assert_eq!(median(vec![u64::MAX, u64::MAX]), u64::MAX);
634 }
635}