Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/blob/main/rust/crates/interplane-probe/src/lib.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-mv / rust / crates / interplane-probe / src / lib.rs` 851 lines ยท 30404 bytes Raw Blame History 1 //! Interplane Probe: measured capability qualification of an OpenAI-compatible endpoint. 2 //! Every verdict cites a request and response digest. Nothing is inferred from the model name. 3 //! The credential (`INTERPLANE_PROBE_API_KEY`) is used only in a request header and never stored. 4 use std::time::{Instant, SystemTime, UNIX_EPOCH}; 5 6 use interplane_core::{ 7 canonicalize, digest, digest_bytes, Environment, ProbeReport, ProbeReportKind, ProbeResult, 8 ProfileResult, ProfileStatus, Verdict, 9 }; 10 use interplane_lenshift::{Dialect, ParseContext}; 11 use serde_json::{json, Map, Value}; 12 13 pub const PROBE_VERSION: &str = "0.1.0"; 14 15 /// A raw HTTP answer. 16 #[derive(Debug, Clone)] 17 pub struct HttpResponse { 18 pub status: u16, 19 pub body: String, 20 } 21 22 /// The only thing the probe needs from the network. Tests supply canned answers. 23 pub trait Transport { 24 fn get(&self, path: &str) -> Result; 25 fn post(&self, path: &str, body: &Value) -> Result; 26 } 27 28 /// `ureq`-backed transport. 29 pub struct UreqTransport { 30 base: String, 31 api_key: Option, 32 agent: ureq::Agent, 33 } 34 35 impl UreqTransport { 36 pub fn new(endpoint: &str, api_key: Option, timeout_secs: u64) -> Self { 37 let agent = ureq::AgentBuilder::new() 38 .timeout(std::time::Duration::from_secs(timeout_secs)) 39 .build(); 40 Self { 41 base: base_url(endpoint), 42 api_key, 43 agent, 44 } 45 } 46 fn finish(&self, r: Result) -> Result { 47 match r { 48 Ok(resp) => { 49 let status = resp.status(); 50 let body = resp.into_string().map_err(|e| self.scrub(e.to_string()))?; 51 Ok(HttpResponse { status, body }) 52 } 53 Err(ureq::Error::Status(status, resp)) => Ok(HttpResponse { 54 status, 55 body: resp.into_string().unwrap_or_default(), 56 }), 57 Err(e) => Err(self.scrub(e.to_string())), 58 } 59 } 60 fn scrub(&self, s: String) -> String { 61 match &self.api_key { 62 Some(k) if !k.is_empty() => s.replace(k.as_str(), "[redacted]"), 63 _ => s, 64 } 65 } 66 } 67 68 impl Transport for UreqTransport { 69 fn get(&self, path: &str) -> Result { 70 let mut req = self.agent.get(&format!("{}{}", self.base, path)); 71 if let Some(k) = &self.api_key { 72 req = req.set("Authorization", &format!("Bearer {k}")); 73 } 74 self.finish(req.call()) 75 } 76 fn post(&self, path: &str, body: &Value) -> Result { 77 let mut req = self.agent.post(&format!("{}{}", self.base, path)); 78 if let Some(k) = &self.api_key { 79 req = req.set("Authorization", &format!("Bearer {k}")); 80 } 81 self.finish(req.send_json(body.clone())) 82 } 83 } 84 85 /// The API base: the endpoint without a trailing slash, with `/v1` appended unless present. 86 pub fn base_url(endpoint: &str) -> String { 87 let e = endpoint.trim_end_matches('/'); 88 if e.ends_with("/v1") { 89 e.to_string() 90 } else { 91 format!("{e}/v1") 92 } 93 } 94 95 /// Redacted endpoint: no credentials, no query string, no fragment. 96 pub fn redact_endpoint(url: &str) -> String { 97 let (scheme, rest) = url 98 .split_once("://") 99 .map(|(s, r)| (format!("{s}://"), r)) 100 .unwrap_or((String::new(), url)); 101 let rest = rest.split(['?', '#']).next().unwrap_or(""); 102 let rest = match rest.split_once('/') { 103 Some((auth, path)) => format!("{}/{}", auth.rsplit('@').next().unwrap_or(auth), path), 104 None => rest.rsplit('@').next().unwrap_or(rest).to_string(), 105 }; 106 format!("{scheme}{}", rest.trim_end_matches('/')) 107 } 108 109 /// Settings for one run. 110 #[derive(Debug, Clone, Default)] 111 pub struct ProbeConfig { 112 pub endpoint: String, 113 pub model: String, 114 pub backend: Option, 115 /// Probe names or prefixes to skip (`context` skips every `context.*`). 116 pub skip: Vec, 117 pub environment: Environment, 118 } 119 120 // ---------- pure evaluators (unit-tested with canned responses) ---------- 121 122 /// `choices[0].message`. 123 fn message(v: &Value) -> Option<&Value> { 124 v.pointer("/choices/0/message") 125 } 126 fn content(v: &Value) -> String { 127 message(v) 128 .and_then(|m| m.get("content")) 129 .and_then(Value::as_str) 130 .unwrap_or("") 131 .to_string() 132 } 133 fn tool_calls(v: &Value) -> Vec<&Value> { 134 message(v) 135 .and_then(|m| m.get("tool_calls")) 136 .and_then(Value::as_array) 137 .map(|a| a.iter().collect()) 138 .unwrap_or_default() 139 } 140 fn call_name(c: &Value) -> &str { 141 c.pointer("/function/name") 142 .and_then(Value::as_str) 143 .unwrap_or("") 144 } 145 fn call_args_object(c: &Value) -> bool { 146 match c.pointer("/function/arguments") { 147 Some(Value::String(s)) => matches!(serde_json::from_str::(s), Ok(Value::Object(_))), 148 Some(Value::Object(_)) => true, 149 _ => false, 150 } 151 } 152 /// Reasoning text from `reasoning_content`, `reasoning`, or a `` block in content. 153 pub fn reasoning_text(v: &Value) -> Option { 154 let m = message(v)?; 155 for k in ["reasoning_content", "reasoning"] { 156 if let Some(s) = m 157 .get(k) 158 .and_then(Value::as_str) 159 .filter(|s| !s.trim().is_empty()) 160 { 161 return Some(s.to_string()); 162 } 163 } 164 let c = content(v); 165 c.contains("").then_some(c) 166 } 167 168 type Eval = (Verdict, String); 169 fn ev(v: Verdict, d: &str) -> Eval { 170 (v, d.to_string()) 171 } 172 173 pub fn eval_chat_basic(v: &Value) -> Eval { 174 if content(v).trim().is_empty() { 175 if reasoning_text(v).is_some() { 176 ev( 177 Verdict::Fail, 178 "empty content; reasoning channel consumed the completion budget", 179 ) 180 } else { 181 ev(Verdict::Fail, "empty content") 182 } 183 } else { 184 ev(Verdict::Pass, "non-empty content") 185 } 186 } 187 /// Assemble an SSE body into text. 188 pub fn assemble_sse(body: &str) -> (usize, String) { 189 let (mut chunks, mut text) = (0, String::new()); 190 for line in body.lines() { 191 let Some(data) = line.strip_prefix("data:").map(str::trim) else { 192 continue; 193 }; 194 if data == "[DONE]" { 195 continue; 196 } 197 if let Ok(v) = serde_json::from_str::(data) { 198 chunks += 1; 199 if let Some(s) = v 200 .pointer("/choices/0/delta/content") 201 .and_then(Value::as_str) 202 { 203 text.push_str(s); 204 } 205 } 206 } 207 (chunks, text) 208 } 209 pub fn eval_streaming(body: &str) -> Eval { 210 let (chunks, text) = assemble_sse(body); 211 if chunks == 0 { 212 ev(Verdict::Fail, "no SSE chunks") 213 } else if text.trim().is_empty() { 214 ev(Verdict::Fail, "chunks assembled to empty content") 215 } else { 216 ev( 217 Verdict::Pass, 218 &format!("{chunks} chunks assembled to non-empty content"), 219 ) 220 } 221 } 222 pub fn eval_tools_native(v: &Value, want: &str) -> Eval { 223 let calls = tool_calls(v); 224 match calls.first() { 225 None => ev(Verdict::Fail, "no tool_calls in response"), 226 Some(c) if call_name(c) != want => ev( 227 Verdict::Fail, 228 &format!("called {:?}, wanted {want:?}", call_name(c)), 229 ), 230 Some(c) if !call_args_object(c) => ev(Verdict::Fail, "arguments are not a JSON object"), 231 Some(_) => ev(Verdict::Pass, "tool call with object arguments"), 232 } 233 } 234 pub fn eval_text_qwen35(v: &Value, want: &str) -> Eval { 235 let turn = interplane_lenshift::qwen35::Qwen35.parse( 236 &Value::String(content(v)), 237 &ParseContext { 238 trace_id: "probe".into(), 239 turn: 0, 240 model: "probe".into(), 241 }, 242 ); 243 if turn.partial || !turn.rejected.is_empty() { 244 ev( 245 Verdict::Fail, 246 "tool call markup present but malformed or truncated", 247 ) 248 } else if turn.intents.iter().any(|i| i.tool.name == want) { 249 ev(Verdict::Pass, "parseable block") 250 } else if !tool_calls(v).is_empty() { 251 ev( 252 Verdict::Degraded, 253 "backend parsed the text form into native tool_calls itself (content empty)", 254 ) 255 } else if content(v).trim().is_empty() { 256 ev( 257 Verdict::Unsupported, 258 "empty content and no tool_calls: the backend parser consumed or suppressed the text-form call (compare a raw-completion capture)", 259 ) 260 } else if content(v).contains("") { 261 ev( 262 Verdict::Degraded, 263 "tool_call markup present but not parseable as qwen35", 264 ) 265 } else { 266 ev(Verdict::Unsupported, "no markup in content") 267 } 268 } 269 pub fn eval_parallel(v: &Value) -> Eval { 270 match tool_calls(v).len() { 271 0 => ev(Verdict::Fail, "no tool_calls"), 272 1 => ev(Verdict::Degraded, "only one tool call in the turn"), 273 n => ev(Verdict::Pass, &format!("{n} tool calls in one turn")), 274 } 275 } 276 pub fn eval_result_replay(v: &Value, needle: &str) -> Eval { 277 let c = content(v); 278 if c.contains(needle) { 279 ev(Verdict::Pass, "final answer uses the tool result") 280 } else if c.trim().is_empty() { 281 ev(Verdict::Fail, "no final answer") 282 } else { 283 ev(Verdict::Degraded, "answered without using the tool result") 284 } 285 } 286 pub fn eval_unknown_refusal(v: &Value, provided: &[&str]) -> Eval { 287 let calls = tool_calls(v); 288 if calls.is_empty() { 289 ev(Verdict::Pass, "did not call a tool that was not provided") 290 } else if calls.iter().all(|c| provided.contains(&call_name(c))) { 291 ev( 292 Verdict::Degraded, 293 "called a provided tool instead of declining", 294 ) 295 } else { 296 ev(Verdict::Fail, "called a nonexistent tool") 297 } 298 } 299 pub fn eval_reasoning_channel(v: &Value) -> Eval { 300 if reasoning_text(v).is_some() { 301 ev(Verdict::Pass, "reasoning channel present") 302 } else { 303 ev( 304 Verdict::Unsupported, 305 "no reasoning_content, reasoning or seen", 306 ) 307 } 308 } 309 pub fn eval_json_structured(v: &Value) -> Eval { 310 match serde_json::from_str::(content(v).trim()) { 311 Ok(Value::Object(_)) => ev(Verdict::Pass, "valid JSON object"), 312 Ok(_) => ev(Verdict::Fail, "valid JSON but not an object"), 313 Err(_) => ev(Verdict::Fail, "content is not valid JSON"), 314 } 315 } 316 pub fn eval_context(v: &Value, needle: &str) -> Eval { 317 let c = content(v); 318 if c.contains(needle) { 319 ev(Verdict::Pass, "needle found") 320 } else if c.trim().is_empty() { 321 ev(Verdict::Fail, "empty answer") 322 } else { 323 ev(Verdict::Degraded, "answered but the needle was wrong") 324 } 325 } 326 pub fn eval_models_list(v: &Value, model: &str) -> Eval { 327 let ids: Vec<&str> = v 328 .get("data") 329 .and_then(Value::as_array) 330 .map(|a| a.iter().filter_map(|m| m["id"].as_str()).collect()) 331 .unwrap_or_default(); 332 if ids.contains(&model) { 333 ev(Verdict::Pass, "model listed") 334 } else if ids.is_empty() && v.get("data").is_none() { 335 ev(Verdict::Fail, "response has no data array") 336 } else { 337 ev(Verdict::Fail, "model not listed") 338 } 339 } 340 341 /// Profiles and their required probes (PROBE.md). 342 pub const PROFILES: [(&str, &[&str]); 4] = [ 343 ("interplane.core.0.1", &["chat.basic", "models.list"]), 344 ( 345 "lenshift.openai.1", 346 &["tools.native", "tools.result_replay"], 347 ), 348 ( 349 "lenshift.qwen35.1", 350 &["tools.text_qwen35", "tools.result_replay"], 351 ), 352 ( 353 "relayline.tool_replay.1", 354 &["tools.result_replay", "chat.streaming"], 355 ), 356 ]; 357 358 /// compatible only when every required probe PASSed; incompatible when any ran and did not PASS 359 /// (UNKNOWN and SKIPPED are not failures); untested otherwise. 360 pub fn compute_profiles(probes: &[ProbeResult]) -> Vec { 361 PROFILES 362 .iter() 363 .map(|(name, req)| { 364 let verdicts: Vec> = req 365 .iter() 366 .map(|r| probes.iter().find(|p| p.name == *r).map(|p| &p.verdict)) 367 .collect(); 368 let status = if verdicts.iter().all(|v| matches!(v, Some(Verdict::Pass))) { 369 ProfileStatus::Compatible 370 } else if verdicts.iter().any(|v| { 371 matches!( 372 v, 373 Some(Verdict::Fail | Verdict::Degraded | Verdict::Unsupported) 374 ) 375 }) { 376 ProfileStatus::Incompatible 377 } else { 378 ProfileStatus::Untested 379 }; 380 ProfileResult { 381 name: (*name).into(), 382 status, 383 required_probes: req.iter().map(|s| s.to_string()).collect(), 384 extensions: Map::new(), 385 } 386 }) 387 .collect() 388 } 389 390 // ---------- running ---------- 391 392 /// How an HTTP exchange maps to a verdict before any content evaluation. 393 #[derive(Debug)] 394 enum Exchange { 395 Body(Value), 396 Text(String), 397 /// Verdict decided by the transport/status alone. 398 Verdict(Eval), 399 } 400 401 fn classify(r: &Result, feature_probe: bool, want_json: bool) -> Exchange { 402 match r { 403 Err(e) => Exchange::Verdict(ev(Verdict::Fail, &format!("transport error: {e}"))), 404 Ok(h) if h.status == 401 || h.status == 403 => Exchange::Verdict(ev( 405 Verdict::Fail, 406 &format!("HTTP {}: authentication required", h.status), 407 )), 408 Ok(h) if (400..500).contains(&h.status) && feature_probe => Exchange::Verdict(ev( 409 Verdict::Unsupported, 410 &format!("HTTP {}: endpoint rejected the request", h.status), 411 )), 412 Ok(h) if h.status >= 400 => { 413 Exchange::Verdict(ev(Verdict::Fail, &format!("HTTP {}", h.status))) 414 } 415 Ok(h) if want_json => match serde_json::from_str::(&h.body) { 416 Ok(v) => Exchange::Body(v), 417 Err(_) => Exchange::Verdict(ev(Verdict::Fail, "response is not JSON")), 418 }, 419 Ok(h) => Exchange::Text(h.body.clone()), 420 } 421 } 422 423 struct Runner<'a> { 424 t: &'a dyn Transport, 425 cfg: &'a ProbeConfig, 426 results: Vec, 427 } 428 429 /// Tool fixtures and prompts below are pinned (spec/PROBE.md: every probe sends these bodies); the 430 /// retired Python probe sent the same. 431 fn user_msg(s: &str) -> Value { 432 json!([{"role": "user", "content": s}]) 433 } 434 435 fn dir_tool(name: &str, description: &str) -> Value { 436 json!({"type": "function", "function": {"name": name, "description": description, 437 "parameters": {"type": "object", "properties": {"path": {"type": "string", "description": "Relative path."}}, "required": ["path"]}}}) 438 } 439 440 fn read_file_tool() -> Value { 441 dir_tool("read_file", "Read a UTF-8 text file from the workspace.") 442 } 443 444 fn list_dir_tool() -> Value { 445 dir_tool("list_dir", "List the entries of a workspace directory.") 446 } 447 448 const QWEN35_TOOL_INSTRUCTION: &str = "# Tools\n\nYou have access to the following functions:\n\n\n{\"name\": \"read_file\", \"description\": \"Read a UTF-8 text file from the workspace.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\", \"description\": \"Relative path.\"}}, \"required\": [\"path\"]}}\n\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format\n- Required parameters MUST be specified\n"; 449 450 const READ_README: &str = "Read the file README.md and tell me what it says."; 451 const REPLY_READY: &str = "Reply with the single word: ready"; 452 const SEVENTEEN: &str = "What is 17 times 23? Answer with the number."; 453 const NEEDLE: &str = "PELICAN-4410"; 454 455 impl Runner<'_> { 456 fn skipped(&self, name: &str) -> bool { 457 self.cfg 458 .skip 459 .iter() 460 .any(|s| name == s || name.starts_with(&format!("{s}."))) 461 } 462 /// Base body, identical to Python's `Endpoint.chat` defaults: model, temperature 0, seed 42. 463 /// `max_tokens` is added only where the Python probe adds it. 464 fn chat(&self, messages: Value) -> Value { 465 json!({"model": self.cfg.model, "messages": messages, "temperature": 0, "seed": 42}) 466 } 467 fn chat_capped(&self, messages: Value) -> Value { 468 let mut b = self.chat(messages); 469 b["max_tokens"] = json!(2048); 470 b 471 } 472 fn record(&mut self, name: &str, verdict: Eval, req: &Value, resp: Option<&str>, ms: u64) { 473 self.record_digest(name, verdict, digest(req), resp, ms); 474 } 475 fn record_digest( 476 &mut self, 477 name: &str, 478 verdict: Eval, 479 req_digest: String, 480 resp: Option<&str>, 481 ms: u64, 482 ) { 483 self.results.push(ProbeResult { 484 name: name.into(), 485 verdict: verdict.0, 486 detail: Some(verdict.1.chars().take(4096).collect()), 487 duration_ms: Some(ms), 488 attempts: Some(1), 489 request_digest: Some(req_digest), 490 response_digest: resp.map(|r| match serde_json::from_str::(r) { 491 Ok(v) => digest(&v), 492 Err(_) => digest_bytes(r.as_bytes()), 493 }), 494 extensions: Map::new(), 495 }); 496 } 497 fn skip(&mut self, name: &str) { 498 self.results.push(ProbeResult { 499 name: name.into(), 500 verdict: Verdict::Skipped, 501 detail: Some("skipped by request".into()), 502 duration_ms: None, 503 attempts: None, 504 request_digest: None, 505 response_digest: None, 506 extensions: Map::new(), 507 }); 508 } 509 /// POST a chat body and evaluate the JSON answer. Returns the answer when the call succeeded. 510 fn post_eval( 511 &mut self, 512 name: &str, 513 body: Value, 514 feature: bool, 515 f: impl Fn(&Value) -> Eval, 516 ) -> Option { 517 if self.skipped(name) { 518 self.skip(name); 519 return None; 520 } 521 let t0 = Instant::now(); 522 let r = self.t.post("/chat/completions", &body); 523 let ms = t0.elapsed().as_millis() as u64; 524 let raw = r.as_ref().ok().map(|h| h.body.clone()); 525 match classify(&r, feature, true) { 526 Exchange::Body(v) => { 527 let verdict = f(&v); 528 self.record(name, verdict, &body, raw.as_deref(), ms); 529 Some(v) 530 } 531 Exchange::Verdict(v) => { 532 self.record(name, v, &body, raw.as_deref(), ms); 533 None 534 } 535 Exchange::Text(_) => None, 536 } 537 } 538 539 fn run(&mut self) { 540 let user = |s: &str| json!([{"role": "user", "content": s}]); 541 self.post_eval( 542 "chat.basic", 543 self.chat_capped(user(REPLY_READY)), 544 false, 545 eval_chat_basic, 546 ); 547 548 // streaming 549 let name = "chat.streaming"; 550 if self.skipped(name) { 551 self.skip(name); 552 } else { 553 let mut body = self.chat_capped(user(REPLY_READY)); 554 body["stream"] = json!(true); 555 let t0 = Instant::now(); 556 let r = self.t.post("/chat/completions", &body); 557 let ms = t0.elapsed().as_millis() as u64; 558 let raw = r.as_ref().ok().map(|h| h.body.clone()); 559 let verdict = match classify(&r, true, false) { 560 Exchange::Text(s) => eval_streaming(&s), 561 Exchange::Verdict(v) => v, 562 Exchange::Body(_) => ev(Verdict::Fail, "unexpected body"), 563 }; 564 self.record(name, verdict, &body, raw.as_deref(), ms); 565 } 566 567 let mut native = self.chat(user(READ_README)); 568 native["tools"] = json!([read_file_tool()]); 569 let native_resp = self.post_eval("tools.native", native, true, |v| { 570 eval_tools_native(v, "read_file") 571 }); 572 // Like Python, the replay probe reuses the call the backend produced when tools.native passed. 573 let native_call: Option = native_resp 574 .filter(|v| eval_tools_native(v, "read_file").0 == Verdict::Pass) 575 .and_then(|v| tool_calls(&v).first().map(|c| (*c).clone())); 576 577 let text_body = self.chat(json!([{"role": "system", "content": QWEN35_TOOL_INSTRUCTION}, {"role": "user", "content": READ_README}])); 578 self.post_eval("tools.text_qwen35", text_body, false, |v| { 579 eval_text_qwen35(v, "read_file") 580 }); 581 582 let mut par = self.chat(user( 583 "Read both README.md and LICENSE now, in one go, then summarize both.", 584 )); 585 par["tools"] = json!([read_file_tool()]); 586 self.post_eval("tools.parallel", par, true, eval_parallel); 587 588 let call = native_call.unwrap_or_else(|| { 589 json!({"id": "call_probe0001", "type": "function", 590 "function": {"name": "read_file", "arguments": "{\"path\":\"README.md\"}"}}) 591 }); 592 let call_id = call 593 .get("id") 594 .and_then(Value::as_str) 595 .filter(|s| !s.is_empty()) 596 .unwrap_or("call_probe0001") 597 .to_string(); 598 let mut replay = self.chat(json!([ 599 {"role": "user", "content": READ_README}, 600 {"role": "assistant", "content": "", "tool_calls": [call]}, 601 {"role": "tool", "tool_call_id": call_id, "content": "{\"content\": \"INTERPLANE probe marker ZEBRA-7731.\"}"} 602 ])); 603 replay["tools"] = json!([read_file_tool()]); 604 self.post_eval("tools.result_replay", replay, true, |v| { 605 eval_result_replay(v, "ZEBRA-7731") 606 }); 607 608 let mut unk = self.chat(user("Use the compile_project tool to build the project.")); 609 unk["tools"] = json!([read_file_tool(), list_dir_tool()]); 610 self.post_eval("tools.unknown_refusal", unk, true, |v| { 611 eval_unknown_refusal(v, &["read_file", "list_dir"]) 612 }); 613 614 let chan = self.post_eval( 615 "reasoning.channel", 616 self.chat(user(SEVENTEEN)), 617 true, 618 eval_reasoning_channel, 619 ); 620 self.reasoning_disable(chan.as_ref().is_some_and(|v| reasoning_text(v).is_some())); 621 622 let mut js = self.chat(user("Return a JSON object with key answer set to 42.")); 623 js["response_format"] = json!({"type": "json_object"}); 624 self.post_eval("json.structured", js, true, eval_json_structured); 625 626 for (name, kib) in [ 627 ("context.8k", 8usize), 628 ("context.16k", 16), 629 ("context.32k", 32), 630 ] { 631 let body = self.chat_capped(user(&needle_prompt(kib, NEEDLE))); 632 self.post_eval(name, body, false, |v| eval_context(v, NEEDLE)); 633 } 634 635 self.models_list(); 636 } 637 638 fn reasoning_disable(&mut self, baseline_has_reasoning: bool) { 639 let name = "reasoning.disable"; 640 if self.skipped(name) { 641 self.skip(name); 642 return; 643 } 644 let base = self.chat(user_msg(SEVENTEEN)); 645 let mechanisms: [(&str, Value); 3] = [ 646 ( 647 "chat_template_kwargs.enable_thinking=false", 648 json!({"chat_template_kwargs": {"enable_thinking": false}}), 649 ), 650 ("think=false", json!({"think": false})), 651 ("reasoning_effort=none", json!({"reasoning_effort": "none"})), 652 ]; 653 let t0 = Instant::now(); 654 let (mut last_body, mut last_raw) = (base.clone(), None); 655 let mut accepted = 0; 656 let mut verdict = None; 657 for (label, extra) in mechanisms { 658 let mut body = base.clone(); 659 for (k, v) in extra.as_object().cloned().unwrap_or_default() { 660 body[k] = v; 661 } 662 let r = self.t.post("/chat/completions", &body); 663 last_body = body; 664 last_raw = r.as_ref().ok().map(|h| h.body.clone()); 665 match classify(&r, true, true) { 666 Exchange::Body(v) => { 667 accepted += 1; 668 if reasoning_text(&v).is_none() { 669 verdict = Some(if baseline_has_reasoning { 670 ev(Verdict::Pass, &format!("reasoning absent with {label}")) 671 } else { 672 ev(Verdict::Undetermined, "no reasoning channel without the switch either, so disabling is not demonstrated") 673 }); 674 break; 675 } 676 } 677 Exchange::Verdict((Verdict::Fail, d)) => { 678 verdict = Some((Verdict::Fail, d)); 679 break; 680 } 681 _ => {} 682 } 683 } 684 let verdict = verdict.unwrap_or_else(|| { 685 if accepted == 0 { 686 ev(Verdict::Unsupported, "no disable mechanism was accepted") 687 } else { 688 ev( 689 Verdict::Fail, 690 "reasoning still present with every accepted disable mechanism", 691 ) 692 } 693 }); 694 let ms = t0.elapsed().as_millis() as u64; 695 self.record(name, verdict, &last_body, last_raw.as_deref(), ms); 696 } 697 698 fn models_list(&mut self) { 699 let name = "models.list"; 700 if self.skipped(name) { 701 self.skip(name); 702 return; 703 } 704 let t0 = Instant::now(); 705 let r = self.t.get("/models"); 706 let ms = t0.elapsed().as_millis() as u64; 707 let raw = r.as_ref().ok().map(|h| h.body.clone()); 708 let verdict = match classify(&r, true, true) { 709 Exchange::Body(v) => eval_models_list(&v, &self.cfg.model), 710 Exchange::Verdict(v) => v, 711 Exchange::Text(_) => ev(Verdict::Fail, "unexpected body"), 712 }; 713 // Python digests the literal request line "GET /models". 714 self.record_digest( 715 name, 716 verdict, 717 digest_bytes(b"GET /models"), 718 raw.as_deref(), 719 ms, 720 ); 721 } 722 } 723 724 /// A prompt of roughly `kib` thousand tokens with the needle in the middle. 725 pub fn needle_prompt(kib: usize, needle_code: &str) -> String { 726 // Port of Python `context_probe`: repeated filler lines up to ~3 bytes per token, needle in the middle. 727 let filler = format!( 728 "{}\n", 729 "The quick brown fox jumps over the lazy dog. ".repeat(8) 730 ); 731 let target = kib * 1024 * 3; 732 let mut lines: Vec = Vec::new(); 733 let mut size = 0; 734 while size < target { 735 lines.push(filler.clone()); 736 size += filler.len(); 737 } 738 let mid = lines.len() / 2; 739 lines.insert(mid, format!("The secret code word is {needle_code}.\n")); 740 format!( 741 "{}\n\nWhat is the secret code word? Answer with just the code word.", 742 lines.concat() 743 ) 744 } 745 746 /// RFC 3339 UTC timestamp for `secs` since the epoch. 747 pub fn rfc3339(secs: u64) -> String { 748 let (days, rem) = (secs / 86400, secs % 86400); 749 let z = days as i64 + 719468; 750 let era = z.div_euclid(146097); 751 let doe = z.rem_euclid(146097); 752 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; 753 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); 754 let mp = (5 * doy + 2) / 153; 755 let d = doy - (153 * mp + 2) / 5 + 1; 756 let m = if mp < 10 { mp + 3 } else { mp - 9 }; 757 let y = yoe + era * 400 + i64::from(m <= 2); 758 format!( 759 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", 760 rem / 3600, 761 rem % 3600 / 60, 762 rem % 60 763 ) 764 } 765 766 fn now() -> String { 767 rfc3339( 768 SystemTime::now() 769 .duration_since(UNIX_EPOCH) 770 .map(|d| d.as_secs()) 771 .unwrap_or(0), 772 ) 773 } 774 775 /// Hardware and OS from /proc (Linux), falling back to the compile-time architecture. 776 pub fn detect_environment() -> Environment { 777 let read = |p: &str| { 778 std::fs::read_to_string(p) 779 .ok() 780 .map(|s| s.trim().trim_end_matches('\0').to_string()) 781 .filter(|s| !s.is_empty()) 782 }; 783 let cpu = read("/proc/device-tree/model").or_else(|| { 784 std::fs::read_to_string("/proc/cpuinfo") 785 .ok()? 786 .lines() 787 .find_map(|l| { 788 l.strip_prefix("model name") 789 .and_then(|r| r.split_once(':')) 790 .map(|(_, v)| v.trim().to_string()) 791 }) 792 }); 793 let hardware = Some(match cpu { 794 Some(c) => format!("{c} ({})", std::env::consts::ARCH), 795 None => std::env::consts::ARCH.to_string(), 796 }); 797 let os = match ( 798 read("/proc/sys/kernel/ostype"), 799 read("/proc/sys/kernel/osrelease"), 800 ) { 801 (Some(a), Some(b)) => Some(format!("{a} {b}")), 802 _ => Some(std::env::consts::OS.to_string()), 803 }; 804 Environment { 805 hardware, 806 os, 807 endpoint_type: Some("openai_compatible".into()), 808 interplane_version: Some(interplane_core::PROTOCOL_VERSION.into()), 809 fixture_revision: std::env::var("INTERPLANE_FIXTURE_REVISION").ok(), 810 model_revision: None, 811 extensions: Map::new(), 812 } 813 } 814 815 /// Run every probe and build the report. 816 pub fn run_probes(t: &dyn Transport, cfg: &ProbeConfig) -> ProbeReport { 817 let started = now(); 818 let mut r = Runner { 819 t, 820 cfg, 821 results: vec![], 822 }; 823 r.run(); 824 let probes = r.results; 825 let profiles = compute_profiles(&probes); 826 ProbeReport { 827 kind: ProbeReportKind, 828 probe_version: PROBE_VERSION.into(), 829 endpoint: redact_endpoint(&cfg.endpoint), 830 backend: cfg.backend.clone(), 831 backend_version: None, 832 model: cfg.model.clone(), 833 model_digest: Some(digest( 834 &json!({"model": cfg.model, "checkpoint": cfg.environment.model_revision}), 835 )), 836 started_at: started, 837 finished_at: Some(now()), 838 probes, 839 profiles, 840 environment: Some(cfg.environment.clone()), 841 extensions: Map::new(), 842 } 843 } 844 845 /// Canonical text of a report (for stable files). 846 pub fn report_text(r: &ProbeReport) -> String { 847 canonicalize(&serde_json::to_value(r).unwrap_or(Value::Null)) 848 } 849 850 #[cfg(test)] 851 mod tests;