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