crates/edge/verify/src/lib.rs 81.6 KiB 2417 lines Raw
1 //! The conformance runner for one binding.2 //!3 //! A binding is only useful if another process can judge it from the wire. The4 //! runner starts a command or connects to a socket, reads the catalogue, runs5 //! one job per capability, and reports every check as pass, fail, or skip.6 //! Skips are answers too: a binding that declares a capability and refuses it7 //! has said something true about itself.8 9 use std::collections::BTreeSet;10 use std::ffi::OsString;11 use std::fmt;12 use std::fs;13 use std::io;14 use std::os::fd::AsFd;15 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};16 use std::os::unix::net::{UnixListener, UnixStream};17 use std::path::{Path, PathBuf};18 use std::process::{Child, Command, Stdio};19 use std::sync::Arc;20 use std::sync::atomic::{AtomicU64, Ordering};21 use std::sync::mpsc::{self, Receiver};22 use std::thread;23 use std::time::{Duration, Instant};24 25 use inf3r_container::ContainerSpec;26 use inf3r_proto::Value;27 use inf3r_proto::body::{28     self, Cancel, Capability, Catalogue, Done, ErrorCode, Grant, Model, Open, Outcome, PartKind,29     Queue, Refusal, Stops,30 };31 use inf3r_proto::client::{Item, Job, Peer};32 use inf3r_proto::mirror;33 34 mod cache_host;35 use cache_host::HostCache;36 37 use inf3r_json::Value as JsonValue;38 39 /// The pause between polls of a socket or a child process. It is short enough40 /// that a check does not notice it and long enough that it does not spin.41 const POLL: Duration = Duration::from_millis(5);42 43 /// The quiet period in which no event may cross a full credit window. It is44 /// short because a binding that blocks on credit blocks immediately.45 const CREDIT_PAUSE: Duration = Duration::from_millis(50);46 47 /// The initial credit of an ordinary job. It is large enough for the small48 /// requests of this runner and small enough that a runaway binding still ends49 /// on its budget.50 const JOB_CREDIT: u64 = 1 << 20;51 52 /// The credit window of the credit check. One byte proves the gate without53 /// presupposing the size of the first event.54 const CREDIT_WINDOW: u64 = 1;55 56 /// The words in the prompt of the crash job. It is long enough that the57 /// binding is still writing when the child dies, so the crash is mid-job.58 const CRASH_WORDS: usize = 4096;59 60 /// The words in the prompt of the cancel job. It gives an engine enough work61 /// that a cancel has something to stop once the job is active.62 const CANCEL_WORDS: usize = 1024;63 64 /// The MIME of a text part.65 const TEXT_MIME: &str = "text/plain; charset=utf-8";66 67 /// The MIME of a JSON part.68 const JSON_MIME: &str = "application/json";69 70 /// The MIME of an audio part. The runner does not decode it.71 const AUDIO_MIME: &str = "audio/pcm; enc=s16le; rate=24000; channels=1";72 73 /// The MIME of an image part. The bytes are a signature, not a picture.74 const IMAGE_MIME: &str = "image/png";75 76 /// A few bytes that stand in for an audio part.77 const AUDIO_SAMPLE: &[u8] = &[0, 0, 0, 0];78 79 /// The bytes that mark a PNG. A binding that reads the header has enough.80 const IMAGE_SAMPLE: &[u8] = &[0x89, b'P', b'N', b'G'];81 82 /// The default deadline of one whole run. A real model may spend a minute83 /// loading and another minute answering, so the gate's clock is not the five84 /// seconds that a conformance mock needs.85 const DEFAULT_BUDGET: Duration = Duration::from_secs(300);86 87 /// The default time that a load and a handshake may take. A model that has to88 /// fill a device from disk is slower than a mock with no weights.89 const DEFAULT_LOAD_BUDGET: Duration = Duration::from_secs(120);90 91 /// The default time of one job check after the load. It is separate from the92 /// load so that a slow load cannot spend the whole gate.93 const DEFAULT_JOB_BUDGET: Duration = Duration::from_secs(60);94 95 /// The role that a grant dependency must carry for a weight file.96 const WEIGHTS_ROLE: &str = "weights";97 98 /// The suite that the runner reads when the caller does not name one. It is99 /// relative to the current directory so a binding outside the repo still gets100 /// judged by the built-in list when the file is absent.101 const DEFAULT_SUITE: &str = "goldens/conformance.json";102 103 /// The marker that opens every trace. It names the runner, not the binding, so104 /// two traces start at the same place.105 const BEGIN: &str = "verify";106 107 /// The capabilities of the built-in suite, in the order that the runner tries108 /// them. They are the twelve that the mock serves.109 const BUILTIN_CAPABILITIES: [&str; 12] = [110     "chat",111     "embed",112     "rerank",113     "decide",114     "extract",115     "tts",116     "stt",117     "music",118     "image-gen",119     "image-edit",120     "t2v-gen",121     "i2v-gen",122 ];123 124 /// The verdict of one check.125 #[derive(Clone, Copy, PartialEq, Eq, Debug)]126 pub enum State {127     /// The binding did what the check asked.128     Pass,129     /// The binding did something else.130     Fail,131     /// The check does not apply, or the binding honestly does not implement it.132     Skip,133 }134 135 /// One line of a report.136 #[derive(Clone, PartialEq, Eq, Debug)]137 pub struct Check {138     /// The capability or phase that this check judged.139     pub name: String,140     /// The verdict.141     pub state: State,142     /// The reason, in one sentence. It is shown for a fail or a skip.143     pub detail: String,144 }145 146 /// Every check that one run made, in the order that it made them.147 #[derive(Clone, PartialEq, Eq, Debug)]148 pub struct Report {149     /// The checks, in run order.150     pub checks: Vec<Check>,151 }152 153 impl Report {154     /// `0` when nothing failed, `1` otherwise.155     pub fn exit_code(&self) -> i32 {156         if self.checks.iter().any(|check| check.state == State::Fail) {157             1158         } else {159             0160         }161     }162 }163 164 impl fmt::Display for Report {165     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {166         for check in &self.checks {167             writeln!(f, "{check}")?;168         }169         Ok(())170     }171 }172 173 impl fmt::Display for Check {174     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {175         match self.state {176             State::Pass => write!(f, "pass {}", self.name),177             State::Fail => write!(f, "fail {}: {}", self.name, self.detail),178             State::Skip => write!(f, "skip {}: {}", self.name, self.detail),179         }180     }181 }182 183 /// The engine-visible shape of one run, as a sequence that two bindings can184 /// compare without sharing a model or a target.185 #[derive(Clone, PartialEq, Eq, Debug)]186 pub struct Trace {187     /// The marker that starts the sequence. It is the same for every binding so188     /// that a diff reports a real divergence and not a different name.189     pub begin: String,190     /// The events that the engine can see, in the order that they happened.191     pub steps: Vec<Step>,192 }193 194 /// One engine-visible event of a trace.195 #[derive(Clone, PartialEq, Eq, Debug)]196 pub struct Step {197     /// The phase or capability that the event belongs to.198     pub what: &'static str,199     /// The facts of the event. A diff compares this string, so it holds only200     /// what a binding must agree on.201     pub detail: String,202 }203 204 /// One place where two traces parted.205 #[derive(Clone, PartialEq, Eq, Debug)]206 pub struct Diff {207     /// The zero-based index of the step that differs.208     pub index: usize,209     /// The step from the first trace. A missing step is spelled `missing`.210     pub a: Step,211     /// The step from the second trace. A missing step is spelled `missing`.212     pub b: Step,213 }214 215 /// Every step that differs between two traces, including a shorter trace.216 ///217 /// A binding that declares fewer capabilities is allowed to have skip steps,218 /// so a skip is compared like any other detail; a pass against a fail is always219 /// reported.220 pub fn diff(a: &Trace, b: &Trace) -> Vec<Diff> {221     let mut diffs = Vec::new();222     let len = a.steps.len().max(b.steps.len());223     for index in 0..len {224         let left = a.steps.get(index).cloned().unwrap_or_else(missing);225         let right = b.steps.get(index).cloned().unwrap_or_else(missing);226         if left != right {227             diffs.push(Diff {228                 index,229                 a: left,230                 b: right,231             });232         }233     }234     diffs235 }236 237 /// A step that stands for a trace that ended before this index.238 fn missing() -> Step {239     Step {240         what: "missing",241         detail: String::new(),242     }243 }244 245 /// A command that can be started again, a container image, or a socket that is246 /// already there.247 enum Target {248     /// The command serves on the private socket that the runner names.249     Command(Recipe),250     /// The image serves on a private socket directory that the supervisor251     /// creates. The engine gets no host path except that directory.252     Container {253         spec: ContainerSpec,254         run_dir: PathBuf,255         host_dir: PathBuf,256     },257     /// Another process already listens on this filesystem path.258     Socket(PathBuf),259 }260 261 /// A command in pieces, so a crash and a restart can start it twice.262 struct Recipe {263     program: OsString,264     args: Vec<OsString>,265     envs: Vec<(OsString, Option<OsString>)>,266     dir: Option<PathBuf>,267 }268 269 impl Recipe {270     fn of(command: Command) -> Recipe {271         let program = command.get_program().to_os_string();272         let args = command.get_args().map(OsString::from).collect();273         let envs = command274             .get_envs()275             .map(|(key, value)| (key.to_os_string(), value.map(OsString::from)))276             .collect();277         let dir = command.get_current_dir().map(Path::to_path_buf);278         Recipe {279             program,280             args,281             envs,282             dir,283         }284     }285 286     fn with_env(&self, key: &str, value: &str) -> Recipe {287         let mut envs = self.envs.clone();288         envs.retain(|(name, _)| name != key);289         envs.push((OsString::from(key), Some(OsString::from(value))));290         Recipe {291             program: self.program.clone(),292             args: self.args.clone(),293             envs,294             dir: self.dir.clone(),295         }296     }297 298     fn command(&self) -> Command {299         let mut command = Command::new(&self.program);300         command.args(&self.args);301         for (key, value) in &self.envs {302             match value {303                 Some(value) => command.env(key, value),304                 None => command.env_remove(key),305             };306         }307         if let Some(dir) = &self.dir {308             command.current_dir(dir);309         }310         command311     }312 }313 314 /// One run: where the binding is, how long any wait may take, and which suite315 /// judges it. The suite is data so a new binding is judged by editing a file316 /// and not the runner.317 pub struct Verify {318     target: Target,319     budget: Duration,320     load_budget: Duration,321     job_budget: Duration,322     suite: PathBuf,323     weights: Vec<PathBuf>,324 }325 326 impl Verify {327     /// Starts a binding from a command. The runner adds `--socket` when it328     /// serves and `--describe` when it checks the catalogue.329     pub fn command(command: Command) -> Verify {330         Verify {331             target: Target::Command(Recipe::of(command)),332             budget: DEFAULT_BUDGET,333             load_budget: DEFAULT_LOAD_BUDGET,334             job_budget: DEFAULT_JOB_BUDGET,335             suite: PathBuf::from(DEFAULT_SUITE),336             weights: Vec::new(),337         }338     }339 340     /// Starts a binding as a sibling container.341     ///342     /// The private socket root is created by the supervisor; the image sees343     /// only its own instance directory. The image command receives344     /// `--socket <path>` after its own arguments.345     pub fn container(spec: ContainerSpec, run_dir: impl AsRef<Path>) -> Verify {346         Verify::container_at(spec, run_dir.as_ref(), run_dir.as_ref())347     }348 349     /// Starts a sibling whose private socket root has a host-side path.350     ///351     /// `run_dir` is the path in the gate process; `host_dir` is the path that352     /// the Docker daemon mounts. They are the same directory when the gate is353     /// on the host, and differ when the gate is inside a control container354     /// that maps a host runtime root.355     pub fn container_at(356         spec: ContainerSpec,357         run_dir: impl AsRef<Path>,358         host_dir: impl AsRef<Path>,359     ) -> Verify {360         Verify {361             target: Target::Container {362                 spec,363                 run_dir: run_dir.as_ref().to_path_buf(),364                 host_dir: host_dir.as_ref().to_path_buf(),365             },366             budget: DEFAULT_BUDGET,367             load_budget: DEFAULT_LOAD_BUDGET,368             job_budget: DEFAULT_JOB_BUDGET,369             suite: PathBuf::from(DEFAULT_SUITE),370             weights: Vec::new(),371         }372     }373 374     /// Connects to a binding that another process already started.375     pub fn socket(path: &str) -> Verify {376         Verify {377             target: Target::Socket(PathBuf::from(path)),378             budget: DEFAULT_BUDGET,379             load_budget: DEFAULT_LOAD_BUDGET,380             job_budget: DEFAULT_JOB_BUDGET,381             suite: PathBuf::from(DEFAULT_SUITE),382             weights: Vec::new(),383         }384     }385 386     /// Sets the whole deadline of the run. Every wait is bounded by what is387     /// left of it.388     pub fn budget(mut self, budget: Duration) -> Verify {389         self.budget = budget;390         self391     }392 393     /// Sets the time that the handshake, the catalogue, and the weight load394     /// may take. It is capped by the whole budget.395     pub fn load_budget(mut self, budget: Duration) -> Verify {396         self.load_budget = budget;397         self398     }399 400     /// Sets the time that one job check may take. It is capped by the whole401     /// budget and starts after the load.402     pub fn job_budget(mut self, budget: Duration) -> Verify {403         self.job_budget = budget;404         self405     }406 407     /// Reads the steps from this file instead of the default suite.408     pub fn suite(mut self, path: impl AsRef<Path>) -> Verify {409         self.suite = path.as_ref().to_path_buf();410         self411     }412 413     /// Hands one weight file to the binding as part of the grant.414     ///415     /// A binding that loads weights from a descriptor has no other way to see416     /// them, and the runner must judge the same path that the core uses.417     pub fn weights(mut self, path: PathBuf) -> Verify {418         self.weights.push(path);419         self420     }421 422     /// Runs the checks in order. A failed check is a report line, not an error423     /// of the runner. A suite that exists but cannot be read or parsed is an424     /// error, because a silently absent suite would judge the wrong binding.425     pub fn run(self) -> io::Result<Report> {426         Ok(self.execute()?.0)427     }428 429     /// Records the engine-visible sequence of the same run. The checks are the430     /// source of every step, so a trace cannot disagree with the report.431     pub fn trace(&self) -> io::Result<Trace> {432         Ok(self.execute()?.1)433     }434 435     fn execute(&self) -> io::Result<(Report, Trace)> {436         let now = Instant::now();437         let deadline = now + self.budget;438         let load_deadline = (now + self.load_budget).min(deadline);439         let suite = load_suite(&self.suite)?.unwrap_or_else(Suite::builtin);440         let mut steps = Vec::new();441         let checks = match &self.target {442             Target::Socket(path) => run_socket(443                 path,444                 &suite,445                 &self.weights,446                 self.job_budget,447                 load_deadline,448                 deadline,449                 &mut steps,450             ),451             Target::Command(recipe) => run_command(452                 recipe,453                 &suite,454                 &self.weights,455                 self.job_budget,456                 load_deadline,457                 deadline,458                 &mut steps,459             ),460             Target::Container {461                 spec,462                 run_dir,463                 host_dir,464             } => run_container(465                 ContainerRun {466                     spec,467                     run_dir,468                     host_dir,469                 },470                 &suite,471                 &self.weights,472                 self.job_budget,473                 load_deadline,474                 deadline,475                 &mut steps,476             ),477         };478         Ok((479             Report { checks },480             Trace {481                 begin: BEGIN.to_string(),482                 steps,483             },484         ))485     }486 }487 488 /// One step of a suite.489 struct Case {490     capability: String,491     parts: Vec<body::Part>,492     expect: Expect,493 }494 495 /// What counts as a pass for a step.496 #[derive(Clone, Copy, PartialEq, Eq)]497 enum Expect {498     /// The terminal frame must be `completed`.499     Completed,500     /// Any terminal frame is an answer.501     Any,502 }503 504 /// The steps that judge one binding.505 struct Suite {506     steps: Vec<Case>,507 }508 509 impl Suite {510     /// The twelve steps that the mock serves, so a binding outside the repo is511     /// still judged when no suite file is there.512     fn builtin() -> Suite {513         let steps = BUILTIN_CAPABILITIES514             .iter()515             .map(|name| Case {516                 capability: (*name).to_string(),517                 parts: job_parts(name),518                 expect: Expect::Completed,519             })520             .collect();521         Suite { steps }522     }523 524     /// Reads the suite document. The shape is one object with a `steps` array.525     fn parse(text: &str) -> Result<Suite, SuiteError> {526         let json = inf3r_json::parse(text).map_err(SuiteError::Json)?;527         let steps = json528             .get("steps")529             .and_then(JsonValue::as_array)530             .ok_or_else(|| SuiteError::Shape("steps is not an array".into()))?;531         let mut parsed = Vec::with_capacity(steps.len());532         for step in steps {533             parsed.push(parse_step(step)?);534         }535         Ok(Suite { steps: parsed })536     }537 538     /// Whether the suite names a capability.539     fn names(&self, name: &str) -> bool {540         self.steps.iter().any(|step| step.capability == name)541     }542 }543 544 /// Why a suite file was not a suite.545 enum SuiteError {546     /// The bytes are not JSON.547     Json(inf3r_json::JsonError),548     /// The JSON is not the shape that the runner reads.549     Shape(String),550 }551 552 impl fmt::Display for SuiteError {553     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {554         match self {555             SuiteError::Json(why) => write!(f, "{why}"),556             SuiteError::Shape(why) => f.write_str(why),557         }558     }559 }560 561 fn parse_step(json: &JsonValue) -> Result<Case, SuiteError> {562     let capability = json563         .get("capability")564         .and_then(JsonValue::as_str)565         .ok_or_else(|| SuiteError::Shape("a step has no capability".into()))?566         .to_string();567     let parts = json568         .get("parts")569         .and_then(JsonValue::as_array)570         .ok_or_else(|| SuiteError::Shape(format!("{capability} has no parts array")))?;571     let mut parsed = Vec::with_capacity(parts.len());572     for part in parts {573         parsed.push(parse_part(part)?);574     }575     let expect = match json576         .get("expect")577         .and_then(JsonValue::as_str)578         .ok_or_else(|| SuiteError::Shape(format!("{capability} has no expect")))?579     {580         "completed" => Expect::Completed,581         "any" => Expect::Any,582         other => {583             return Err(SuiteError::Shape(format!(584                 "{capability} has an unknown expect: {other}"585             )));586         }587     };588     Ok(Case {589         capability,590         parts: parsed,591         expect,592     })593 }594 595 fn parse_part(json: &JsonValue) -> Result<body::Part, SuiteError> {596     let kind = json597         .get("kind")598         .and_then(JsonValue::as_str)599         .ok_or_else(|| SuiteError::Shape("a part has no kind".into()))?;600     let text = json601         .get("text")602         .and_then(JsonValue::as_str)603         .ok_or_else(|| SuiteError::Shape(format!("a {kind} part has no text")))?;604     let role = json.get("role").and_then(JsonValue::as_str);605     let (kind, mime, bytes) = match kind {606         "text" => (PartKind::Text, TEXT_MIME, text.as_bytes()),607         "json" => (PartKind::Json, JSON_MIME, text.as_bytes()),608         "audio" => (PartKind::Audio, AUDIO_MIME, AUDIO_SAMPLE),609         "image" => (PartKind::Image, IMAGE_MIME, IMAGE_SAMPLE),610         other => {611             return Err(SuiteError::Shape(format!("unknown part kind: {other}")));612         }613     };614     Ok(body::Part {615         kind,616         mime: mime.to_string(),617         role: role.map(str::to_string),618         len: bytes.len() as u64,619         hold: body::Hold::Inline(bytes.to_vec()),620     })621 }622 623 fn load_suite(path: &Path) -> io::Result<Option<Suite>> {624     let text = match fs::read_to_string(path) {625         Ok(text) => text,626         Err(why) if why.kind() == io::ErrorKind::NotFound => return Ok(None),627         Err(why) => return Err(why),628     };629     match Suite::parse(&text) {630         Ok(suite) => Ok(Some(suite)),631         Err(why) => Err(io::Error::new(io::ErrorKind::InvalidData, why.to_string())),632     }633 }634 635 /// The end of a job as the caller saw it.636 enum End {637     Done(Done),638     Reject(Refusal),639     Closed,640     Timeout,641     Error(String),642 }643 644 /// The started peer that the runner must end.645 enum Runner {646     /// A command whose own process is the plugin.647     Process(Child),648     /// A `docker run` CLI process that owns the sibling container.649     Container(inf3r_supervisor::Child),650 }651 652 /// One connection and its catalogue.653 struct Connected {654     peer: Peer,655     child: Option<Runner>,656     _socket_dir: Option<SocketDir>,657     /// The engine's cache trace inside the private directory, when the target658     /// is a container. It is removed with the directory.659     trace: Option<PathBuf>,660 }661 662 /// A private directory that is removed when the run ends.663 struct SocketDir(PathBuf);664 665 impl SocketDir {666     fn new(kind: &str) -> io::Result<SocketDir> {667         static NEXT: AtomicU64 = AtomicU64::new(1);668         let path = Path::new("/tmp").join(format!(669             "inf3r-verify-{kind}-{}-{}",670             std::process::id(),671             NEXT.fetch_add(1, Ordering::Relaxed)672         ));673         fs::DirBuilder::new()674             .mode(0o700)675             .create(&path)676             .map_err(|why| io::Error::new(why.kind(), format!("{}: {why}", path.display())))?;677         Ok(SocketDir(path))678     }679 680     fn join(&self, name: &str) -> PathBuf {681         self.0.join(name)682     }683 }684 685 impl Drop for SocketDir {686     fn drop(&mut self) {687         let _ = fs::remove_dir_all(&self.0);688     }689 }690 691 fn run_socket(692     path: &Path,693     suite: &Suite,694     weights: &[PathBuf],695     job_budget: Duration,696     load_deadline: Instant,697     overall: Instant,698     steps: &mut Vec<Step>,699 ) -> Vec<Check> {700     let mut checks = Vec::new();701     let stream = match UnixStream::connect(path) {702         Ok(stream) => stream,703         Err(why) => {704             let check = fail("handshake", format!("connect {}: {why}", path.display()));705             steps.push(trace_of("handshake", &check));706             checks.push(check);707             return checks;708         }709     };710     let peer = match Peer::connect(stream, "verify", remaining(load_deadline)) {711         Ok(peer) => peer,712         Err(why) => {713             let check = fail("handshake", why.to_string());714             steps.push(trace_of("handshake", &check));715             checks.push(check);716             return checks;717         }718     };719     let connected = Connected {720         peer,721         child: None,722         _socket_dir: None,723         trace: None,724     };725     let check = handshake(&connected.peer);726     steps.push(handshake_step(&connected.peer, &check));727     checks.push(check);728     let Some(catalogue) = connected.peer.catalogue() else {729         let check = fail("catalogue", "the handshake carried no catalogue");730         steps.push(trace_of("catalogue", &check));731         checks.push(check);732         return checks;733     };734     let check = catalogue_check(&catalogue);735     steps.push(catalogue_step(&catalogue, &check));736     checks.push(check);737     let refused = load_weights(&connected.peer, weights, load_deadline).err();738     let cache = cache_check(&connected.peer, &catalogue, refused.as_deref());739     steps.push(trace_of("cache_fingerprint", &cache));740     checks.push(cache);741     if refused.is_none() && catalogue.cache.is_some() {742         checks.extend(cache_checks(743             &connected.peer,744             &catalogue,745             load_deadline,746             steps,747             connected.trace.as_deref(),748             None,749         ));750     }751     let job_deadline = job_deadline(job_budget, overall);752     checks.extend(run_jobs(753         &connected.peer,754         &catalogue,755         suite,756         job_deadline,757         steps,758         refused.as_deref(),759     ));760     checks.extend(protocol_checks(761         &connected.peer,762         &catalogue,763         job_deadline,764         steps,765         refused.as_deref(),766     ));767     let _ = connected.peer.close();768     checks769 }770 771 fn run_command(772     recipe: &Recipe,773     suite: &Suite,774     weights: &[PathBuf],775     job_budget: Duration,776     load_deadline: Instant,777     overall: Instant,778     steps: &mut Vec<Step>,779 ) -> Vec<Check> {780     let mut checks = Vec::new();781     let trace = std::env::temp_dir().join(format!(782         "inf3r-verify-trace-{}-{}",783         std::process::id(),784         now_token()785     ));786     let _ = fs::remove_file(&trace);787     let recipe = recipe.with_env("INF3R_CACHE_TRACE", &trace.to_string_lossy());788     let mut connected = match start_command(&recipe, load_deadline) {789         Ok(connected) => connected,790         Err(why) => {791             let check = fail("handshake", why.to_string());792             steps.push(trace_of("handshake", &check));793             checks.push(check);794             return checks;795         }796     };797     let check = handshake(&connected.peer);798     steps.push(handshake_step(&connected.peer, &check));799     checks.push(check);800     let Some(catalogue) = connected.peer.catalogue() else {801         let check = fail("catalogue", "the handshake carried no catalogue");802         steps.push(trace_of("catalogue", &check));803         checks.push(check);804         kill(&mut connected.child);805         return checks;806     };807     let check = catalogue_check(&catalogue);808     steps.push(catalogue_step(&catalogue, &check));809     checks.push(check);810     checks.push(describe(&recipe, &catalogue, load_deadline));811     let refused = load_weights(&connected.peer, weights, load_deadline).err();812     let cache = cache_check(&connected.peer, &catalogue, refused.as_deref());813     steps.push(trace_of("cache_fingerprint", &cache));814     checks.push(cache);815     if refused.is_none() && catalogue.cache.is_some() {816         checks.extend(cache_checks(817             &connected.peer,818             &catalogue,819             load_deadline,820             steps,821             Some(&trace),822             Some(&recipe),823         ));824     }825     // The job clock starts when the load is done, not when the gate starts.826     let job_deadline = job_deadline(job_budget, overall);827     checks.extend(run_jobs(828         &connected.peer,829         &catalogue,830         suite,831         job_deadline,832         steps,833         refused.as_deref(),834     ));835 836     checks.extend(protocol_checks(837         &connected.peer,838         &catalogue,839         job_deadline,840         steps,841         refused.as_deref(),842     ));843 844     // A credit violation ends the session by design, so the crash check has845     // nothing left to kill. Skip rather than report a second symptom of one846     // cause. A load that never happened has no job to crash either.847     let protocol_ended = checks.iter().any(|check| {848         check.state == State::Fail && matches!(check.name.as_str(), "extension" | "credit")849     });850     let crash = match (refused.as_deref(), chosen(&catalogue), protocol_ended) {851         (Some(detail), _, _) => skip("crash", format!("load refused: {detail}")),852         (None, None, _) => fail("crash", "the catalogue declares no capability"),853         (None, Some(_), true) => skip("crash", "the connection ended in a protocol check"),854         (None, Some((model, name)), false) => check_crash(855             &connected.peer,856             model,857             name,858             &mut connected.child,859             job_deadline,860         ),861     };862     steps.push(trace_of("crash", &crash));863     checks.push(crash);864     drop(connected.peer);865 866     let restart = if remaining(load_deadline).is_zero() {867         fail("restart", "the load budget was spent before the restart")868     } else {869         match start_command(&recipe, load_deadline) {870             Ok(restarted) => {871                 let check = handshake(&restarted.peer);872                 let check = if check.state == State::Pass {873                     pass("restart", "the binding accepted a second handshake")874                 } else {875                     fail("restart", check.detail)876                 };877                 let mut child = restarted.child;878                 kill(&mut child);879                 let _ = restarted.peer.close();880                 check881             }882             Err(why) => fail("restart", why.to_string()),883         }884     };885     steps.push(trace_of("restart", &restart));886     checks.push(restart);887     kill(&mut connected.child);888     let _ = fs::remove_file(&trace);889     checks890 }891 892 struct ContainerRun<'a> {893     spec: &'a ContainerSpec,894     run_dir: &'a Path,895     host_dir: &'a Path,896 }897 898 fn run_container(899     run: ContainerRun<'_>,900     suite: &Suite,901     weights: &[PathBuf],902     job_budget: Duration,903     load_deadline: Instant,904     overall: Instant,905     steps: &mut Vec<Step>,906 ) -> Vec<Check> {907     let ContainerRun {908         spec,909         run_dir,910         host_dir,911     } = run;912     let mut checks = Vec::new();913     let mut connected = match start_container(spec, run_dir, host_dir, load_deadline) {914         Ok(connected) => connected,915         Err(why) => {916             let check = fail("handshake", why.to_string());917             steps.push(trace_of("handshake", &check));918             checks.push(check);919             return checks;920         }921     };922     let check = handshake(&connected.peer);923     steps.push(handshake_step(&connected.peer, &check));924     checks.push(check);925     let Some(catalogue) = connected.peer.catalogue() else {926         let check = fail("catalogue", "the handshake carried no catalogue");927         steps.push(trace_of("catalogue", &check));928         checks.push(check);929         kill(&mut connected.child);930         return checks;931     };932     let check = catalogue_check(&catalogue);933     steps.push(catalogue_step(&catalogue, &check));934     checks.push(check);935     checks.push(describe_container(spec, &catalogue, load_deadline));936     let refused = load_weights(&connected.peer, weights, load_deadline).err();937     let cache = cache_check(&connected.peer, &catalogue, refused.as_deref());938     steps.push(trace_of("cache_fingerprint", &cache));939     checks.push(cache);940     if refused.is_none() && catalogue.cache.is_some() {941         // A container has no host trace file and no host fault-mode942         // environment. The round trip and the corrupt fallback still cross the943         // container boundary; only the check that needs the scripted crash944         // mode is reported as a skip, not as a pass.945         checks.extend(cache_checks(946             &connected.peer,947             &catalogue,948             load_deadline,949             steps,950             connected.trace.as_deref(),951             None,952         ));953     }954     let job_deadline = job_deadline(job_budget, overall);955     checks.extend(run_jobs(956         &connected.peer,957         &catalogue,958         suite,959         job_deadline,960         steps,961         refused.as_deref(),962     ));963     checks.extend(protocol_checks(964         &connected.peer,965         &catalogue,966         job_deadline,967         steps,968         refused.as_deref(),969     ));970 971     let protocol_ended = checks.iter().any(|check| {972         check.state == State::Fail && matches!(check.name.as_str(), "extension" | "credit")973     });974     let crash = match (refused.as_deref(), chosen(&catalogue), protocol_ended) {975         (Some(detail), _, _) => skip("crash", format!("load refused: {detail}")),976         (None, None, _) => fail("crash", "the catalogue declares no capability"),977         (None, Some(_), true) => skip("crash", "the connection ended in a protocol check"),978         (None, Some((model, name)), false) => check_crash(979             &connected.peer,980             model,981             name,982             &mut connected.child,983             job_deadline,984         ),985     };986     steps.push(trace_of("crash", &crash));987     checks.push(crash);988     drop(connected.peer);989 990     let restart = if remaining(load_deadline).is_zero() {991         fail("restart", "the load budget was spent before the restart")992     } else {993         match start_container(spec, run_dir, host_dir, load_deadline) {994             Ok(restarted) => {995                 let check = handshake(&restarted.peer);996                 let check = if check.state == State::Pass {997                     pass("restart", "the binding accepted a second handshake")998                 } else {999                     fail("restart", check.detail)1000                 };1001                 let mut child = restarted.child;1002                 kill(&mut child);1003                 let _ = restarted.peer.close();1004                 check1005             }1006             Err(why) => fail("restart", why.to_string()),1007         }1008     };1009     steps.push(trace_of("restart", &restart));1010     checks.push(restart);1011     kill(&mut connected.child);1012     checks1013 }1014 1015 fn start_container(1016     spec: &ContainerSpec,1017     run_dir: &Path,1018     host_dir: &Path,1019     deadline: Instant,1020 ) -> io::Result<Connected> {1021     let mut child = inf3r_supervisor::Child::spawn_container_in_host_with(1022         spec.clone(),1023         run_dir,1024         host_dir,1025         |directory| {1026             vec![(1027                 "INF3R_CACHE_TRACE".to_string(),1028                 directory.join("trace").to_string_lossy().into_owned(),1029             )]1030         },1031     )1032     .map_err(|why| io::Error::other(why.to_string()))?;1033     let trace = child.directory().map(|directory| directory.join("trace"));1034     let stream = match child.accept(remaining(deadline)) {1035         Ok(stream) => stream,1036         Err(why) => {1037             let logs = child.logs();1038             let _ = child.stop(Duration::from_secs(1));1039             return Err(io::Error::other(format!("{why}\n{logs}")));1040         }1041     };1042     match Peer::connect(stream, "verify", remaining(deadline)) {1043         Ok(peer) => Ok(Connected {1044             peer,1045             child: Some(Runner::Container(child)),1046             _socket_dir: None,1047             trace,1048         }),1049         Err(why) => {1050             let logs = child.logs();1051             let _ = child.stop(Duration::from_secs(1));1052             Err(io::Error::other(format!("{why}\n{logs}")))1053         }1054     }1055 }1056 1057 fn describe_container(spec: &ContainerSpec, catalogue: &Catalogue, deadline: Instant) -> Check {1058     if remaining(deadline).is_zero() {1059         return fail("describe", "the load budget was spent before describe");1060     }1061     let output = match spec.describe() {1062         Ok(output) => output,1063         Err(why) => return fail("describe", why.to_string()),1064     };1065     if !output.status.success() {1066         let why = String::from_utf8_lossy(&output.stderr);1067         return fail(1068             "describe",1069             format!("the image exited {}: {}", output.status, why.trim()),1070         );1071     }1072     let text = match String::from_utf8(output.stdout) {1073         Ok(text) => text,1074         Err(_) => return fail("describe", "the catalogue is not UTF-8"),1075     };1076     let json = match inf3r_json::parse(&text) {1077         Ok(json) => json,1078         Err(why) => return fail("describe", why.to_string()),1079     };1080     let wire = mirror::to_json(&catalogue.to_value());1081     if json == wire {1082         pass("describe", "the printed catalogue matches the wire")1083     } else {1084         fail("describe", "the printed catalogue differs from the wire")1085     }1086 }1087 1088 /// Hands the weights to the binding and returns the refusal detail, if any.1089 ///1090 /// A binding that refuses the load is not a broken binding: every job check1091 /// says so and the run still reports the truth about the other checks.1092 fn load_weights(peer: &Peer, weights: &[PathBuf], deadline: Instant) -> Result<(), String> {1093     let mut files = Vec::with_capacity(weights.len());1094     let mut deps = Vec::with_capacity(weights.len());1095     for (index, path) in weights.iter().enumerate() {1096         let file = fs::File::open(path).map_err(|why| format!("{}: {why}", path.display()))?;1097         let len = file1098             .metadata()1099             .map_err(|why| format!("{}: {why}", path.display()))?1100             .len();1101         let fd = u32::try_from(index).map_err(|_| "too many weight descriptors".to_string())?;1102         deps.push(body::Dependency {1103             role: WEIGHTS_ROLE.to_string(),1104             fd,1105             len,1106             path: path.to_string_lossy().into_owned(),1107         });1108         files.push(file);1109     }1110     let fds: Vec<_> = files.iter().map(AsFd::as_fd).collect();1111     peer.load_fds(&Grant { deps }, &fds, remaining(deadline))1112         .map(|_| ())1113         .map_err(|why| {1114             peer.refusal()1115                 .and_then(|refusal| refusal.detail)1116                 .unwrap_or_else(|| why.to_string())1117         })1118 }1119 1120 /// The four behavioural cache checks. The fingerprint check is separate1121 /// because it runs before any store exists.1122 fn cache_checks(1123     peer: &Peer,1124     catalogue: &Catalogue,1125     deadline: Instant,1126     steps: &mut Vec<Step>,1127     trace: Option<&Path>,1128     recipe: Option<&Recipe>,1129 ) -> Vec<Check> {1130     let Some(spec) = catalogue.cache.clone() else {1131         return [1132             "cache_roundtrip",1133             "cache_cold_erase",1134             "cache_corrupt_fallback",1135             "cache_abort_on_crash",1136         ]1137         .into_iter()1138         .map(|name| skip(name, "the catalogue declares no cache"))1139         .collect();1140     };1141     if peer.version() != Some(2) {1142         return [1143             "cache_roundtrip",1144             "cache_cold_erase",1145             "cache_corrupt_fallback",1146             "cache_abort_on_crash",1147         ]1148         .into_iter()1149         .map(|name| skip(name, "the peer did not negotiate Wire 2"))1150         .collect();1151     }1152     let Some((model, _)) = chat_model(catalogue) else {1153         return [1154             "cache_roundtrip",1155             "cache_cold_erase",1156             "cache_corrupt_fallback",1157             "cache_abort_on_crash",1158         ]1159         .into_iter()1160         .map(|name| skip(name, "the catalogue declares no chat capability"))1161         .collect();1162     };1163     let dir = std::env::temp_dir().join(format!(1164         "inf3r-verify-cache-{}-{}",1165         std::process::id(),1166         now_token()1167     ));1168     let fingerprint = peer1169         .ready()1170         .and_then(|ready| ready.cache_fingerprint)1171         .unwrap_or([0; 32]);1172     let host = match HostCache::open(&dir, &spec, fingerprint, Duration::from_secs(3600)) {1173         Ok(host) => host,1174         Err(why) => {1175             let check = fail("cache_roundtrip", format!("cache store: {why}"));1176             steps.push(trace_of("cache_roundtrip", &check));1177             return vec![check];1178         }1179     };1180     peer.install_cache(1, host.clone());1181     let mut checks = Vec::new();1182 1183     let cold = cache_job(peer, model, "verify cache cold erase", deadline);1184     let erase_seen = trace1185         .and_then(|path| fs::read_to_string(path).ok())1186         .is_some_and(|text| text.lines().any(|line| line == "erase"));1187     let check = match cold {1188         Err(why) => fail("cache_cold_erase", why),1189         Ok(()) if trace.is_none() => skip(1190             "cache_cold_erase",1191             "this target has no host trace environment",1192         ),1193         Ok(()) if erase_seen => pass("cache_cold_erase", "a miss erased the slot before the job"),1194         Ok(()) => fail("cache_cold_erase", "a cold miss did not report an erase"),1195     };1196     steps.push(trace_of("cache_cold_erase", &check));1197     checks.push(check);1198 1199     let prompt = "verify cache roundtrip";1200     let first = cache_job(peer, model, prompt, deadline);1201     let second = cache_job(peer, model, prompt, deadline);1202     let stats = host.stats();1203     let check = match (first, second) {1204         (Err(why), _) | (_, Err(why)) => fail("cache_roundtrip", why),1205         (Ok(()), Ok(())) if stats.save_count == 0 || stats.hits == 0 => fail(1206             "cache_roundtrip",1207             format!(1208                 "the store saw {} save(s) and {} hit(s)",1209                 stats.save_count, stats.hits1210             ),1211         ),1212         (Ok(()), Ok(())) => pass(1213             "cache_roundtrip",1214             format!(1215                 "{} save(s), {} hit(s), {} restore(s)",1216                 stats.save_count, stats.hits, stats.restore_count1217             ),1218         ),1219     };1220     steps.push(trace_of("cache_roundtrip", &check));1221     checks.push(check);1222 1223     host.next_hit_is_corrupt();1224     let corrupt = cache_job(peer, model, prompt, deadline);1225     let check = match corrupt {1226         Err(why) => fail("cache_corrupt_fallback", why),1227         Ok(()) if host.corrupt_was_seen() => pass(1228             "cache_corrupt_fallback",1229             "the corrupt hit was rejected and the job still completed",1230         ),1231         Ok(()) => fail(1232             "cache_corrupt_fallback",1233             "the corrupt hit was not reported to the host",1234         ),1235     };1236     steps.push(trace_of("cache_corrupt_fallback", &check));1237     checks.push(check);1238 1239     let crash = cache_crash_check(recipe, catalogue, deadline, Arc::clone(&host));1240     steps.push(trace_of("cache_abort_on_crash", &crash));1241     checks.push(crash);1242 1243     peer.uninstall_cache();1244     drop(host);1245     let _ = fs::remove_dir_all(&dir);1246     checks1247 }1248 1249 fn chat_model(catalogue: &Catalogue) -> Option<(&Model, ())> {1250     catalogue1251         .models1252         .iter()1253         .find(|model| model.capabilities.contains_key("chat"))1254         .map(|model| (model, ()))1255 }1256 1257 fn cache_job(peer: &Peer, model: &Model, prompt: &str, deadline: Instant) -> Result<(), String> {1258     let parts = vec![body::Part {1259         kind: PartKind::Text,1260         mime: TEXT_MIME.to_string(),1261         role: Some("user".to_string()),1262         len: prompt.len() as u64,1263         hold: body::Hold::Inline(prompt.as_bytes().to_vec()),1264     }];1265     let open = open_body(model, "chat", &parts, JOB_CREDIT, deadline);1266     let job = peer.open(open, &[]).map_err(|why| why.to_string())?;1267     let (_, rx) = read(job);1268     let (end, _) = terminal_count(&rx, deadline);1269     match end {1270         End::Done(done) if done.outcome == Outcome::Completed => Ok(()),1271         End::Done(done) => Err(format!("the cache job ended {:?}", done.outcome)),1272         End::Reject(refusal) => Err(format!("the cache job was refused: {refusal:?}")),1273         End::Closed => Err("the cache job closed before a terminal frame".into()),1274         End::Timeout => Err("the cache job timed out".into()),1275         End::Error(why) => Err(why),1276     }1277 }1278 1279 fn cache_crash_check(1280     recipe: Option<&Recipe>,1281     catalogue: &Catalogue,1282     deadline: Instant,1283     host: Arc<HostCache>,1284 ) -> Check {1285     let Some(recipe) = recipe else {1286         return skip(1287             "cache_abort_on_crash",1288             "this target has no scripted crash mode",1289         );1290     };1291     let name = Path::new(&recipe.program)1292         .file_name()1293         .and_then(|name| name.to_str())1294         .unwrap_or_default();1295     if !name.contains("mock") {1296         return skip(1297             "cache_abort_on_crash",1298             "this binding has no scripted mid-save crash",1299         );1300     }1301     let Some(spec) = catalogue.cache.clone() else {1302         return skip("cache_abort_on_crash", "the catalogue declares no cache");1303     };1304     let recipe = recipe.with_env("INF3R_MOCK_CACHE", "crash-save");1305     let mut connected = match start_command(&recipe, deadline) {1306         Ok(connected) => connected,1307         Err(why) => return fail("cache_abort_on_crash", why.to_string()),1308     };1309     let Some(catalogue) = connected.peer.catalogue() else {1310         kill(&mut connected.child);1311         return fail("cache_abort_on_crash", "the crash child sent no catalogue");1312     };1313     let Some((model, _)) = chat_model(&catalogue) else {1314         kill(&mut connected.child);1315         return skip("cache_abort_on_crash", "the crash child has no chat");1316     };1317     let _ = spec;1318     connected.peer.install_cache(1, host.clone());1319     let crashed = cache_job(&connected.peer, model, "verify cache crash", deadline);1320     kill(&mut connected.child);1321     // Drop the peer, not the host: the binding's `closed` callback is the1322     // path under test. The local host Arc remains so the store can be read.1323     drop(connected);1324     let stats = host.stats();1325     let check = if crashed.is_ok() {1326         fail(1327             "cache_abort_on_crash",1328             "the crash child returned a completed job",1329         )1330     } else if stats.active_writes == 0 && stats.active_reads == 0 && host.temp_files() == 0 {1331         pass(1332             "cache_abort_on_crash",1333             "the peer drop aborted the write lease when the child died",1334         )1335     } else {1336         fail(1337             "cache_abort_on_crash",1338             format!(1339                 "{} write and {} read leases and {} temp files survived the crash",1340                 stats.active_writes,1341                 stats.active_reads,1342                 host.temp_files()1343             ),1344         )1345     };1346     if check.state != State::Pass {1347         return check;1348     }1349 1350     // The same mock can stall its flush. A bounded flush must return at its1351     // budget and the caller must still be able to kill the child, rather than1352     // waiting for the engine's own sleep.1353     let stall = recipe.with_env("INF3R_MOCK_CACHE", "stall-flush");1354     let mut stalled = match start_command(&stall, deadline) {1355         Ok(connected) => connected,1356         Err(why) => return fail("cache_abort_on_crash", why.to_string()),1357     };1358     stalled.peer.install_cache(1, host.clone());1359     let started = Instant::now();1360     let flushed = stalled.peer.flush_cache(Duration::from_millis(50));1361     let waited = started.elapsed();1362     kill(&mut stalled.child);1363     if flushed.is_err() && waited < Duration::from_secs(1) {1364         pass(1365             "cache_abort_on_crash",1366             "the write lease was aborted when the child died; a stalled flush returned at its budget",1367         )1368     } else {1369         fail(1370             "cache_abort_on_crash",1371             format!("a stalled flush returned {flushed:?} after {waited:?}"),1372         )1373     }1374 }1375 1376 fn now_token() -> u128 {1377     std::time::SystemTime::now()1378         .duration_since(std::time::UNIX_EPOCH)1379         .map(|d| d.as_nanos())1380         .unwrap_or(0)1381 }1382 1383 /// A Wire 2 cache declaration must be internally consistent, and a loaded1384 /// plugin must report the bundle half of the composite fingerprint.1385 fn cache_check(peer: &Peer, catalogue: &Catalogue, refused: Option<&str>) -> Check {1386     let Some(spec) = &catalogue.cache else {1387         return skip("cache_fingerprint", "the catalogue declares no cache");1388     };1389     if spec.slots == 01390         || spec.max_entry_bytes == 01391         || !spec.supports_erase1392         || (!spec.supports_save && !spec.supports_restore)1393     {1394         return fail("cache_fingerprint", "the cache declaration is inconsistent");1395     }1396     if let Some(detail) = refused {1397         return skip("cache_fingerprint", format!("load refused: {detail}"));1398     }1399     match peer.ready() {1400         Some(ready) if ready.cache_fingerprint.is_some() => pass(1401             "cache_fingerprint",1402             "the plugin reported a cache fingerprint",1403         ),1404         Some(_) => fail("cache_fingerprint", "ready carried no cache fingerprint"),1405         None => fail("cache_fingerprint", "the plugin sent no ready"),1406     }1407 }1408 1409 fn protocol_checks(1410     peer: &Peer,1411     catalogue: &Catalogue,1412     deadline: Instant,1413     steps: &mut Vec<Step>,1414     refused: Option<&str>,1415 ) -> Vec<Check> {1416     let mut checks = Vec::new();1417     for name in ["extension", "cancel", "credit", "descriptor", "artifact"] {1418         if let Some(detail) = refused {1419             let check = skip(name, format!("load refused: {detail}"));1420             steps.push(trace_of(name, &check));1421             checks.push(check);1422             continue;1423         }1424         let Some((model, capability)) = chosen(catalogue) else {1425             let check = fail(name, "the catalogue declares no capability");1426             steps.push(trace_of(name, &check));1427             checks.push(check);1428             continue;1429         };1430         let check = match name {1431             "extension" => check_extension(peer, model, capability, deadline),1432             "cancel" => check_cancel(peer, model, capability, deadline),1433             "credit" => check_credit(peer, model, capability, deadline),1434             "descriptor" => check_descriptor(peer, model, capability, deadline),1435             _ => check_artifact(peer, catalogue, (model, capability), deadline),1436         };1437         steps.push(trace_of(name, &check));1438         checks.push(check);1439     }1440     checks1441 }1442 1443 fn handshake(peer: &Peer) -> Check {1444     match (peer.welcome(), peer.catalogue()) {1445         (Some(welcome), Some(catalogue)) => pass(1446             "handshake",1447             format!(1448                 "wire {} with {} model(s)",1449                 welcome.v,1450                 catalogue.models.len()1451             ),1452         ),1453         (Some(_), None) => fail("handshake", "welcome arrived without a catalogue"),1454         (None, _) => fail("handshake", "no welcome arrived"),1455     }1456 }1457 1458 fn trace_of(what: &'static str, check: &Check) -> Step {1459     let detail = match check.state {1460         State::Pass => "pass".to_string(),1461         State::Fail | State::Skip => format!("{} {}", state_name(check.state), check.detail),1462     };1463     Step { what, detail }1464 }1465 1466 fn handshake_step(peer: &Peer, check: &Check) -> Step {1467     let Some(welcome) = peer.welcome() else {1468         return trace_of("handshake", check);1469     };1470     Step {1471         what: "handshake",1472         detail: format!("{} wire {}", state_name(check.state), welcome.v),1473     }1474 }1475 1476 fn catalogue_step(catalogue: &Catalogue, check: &Check) -> Step {1477     let mut models: Vec<&str> = catalogue1478         .models1479         .iter()1480         .map(|model| model.serve.as_str())1481         .collect();1482     models.sort_unstable();1483     let mut capabilities = BTreeSet::new();1484     for model in &catalogue.models {1485         capabilities.extend(model.capabilities.keys().map(String::as_str));1486     }1487     let capabilities: Vec<&str> = capabilities.into_iter().collect();1488     Step {1489         what: "catalogue",1490         detail: format!(1491             "{} models [{}] capabilities [{}]",1492             state_name(check.state),1493             models.join(","),1494             capabilities.join(",")1495         ),1496     }1497 }1498 1499 fn state_name(state: State) -> &'static str {1500     match state {1501         State::Pass => "pass",1502         State::Fail => "fail",1503         State::Skip => "skip",1504     }1505 }1506 1507 fn catalogue_check(catalogue: &Catalogue) -> Check {1508     if catalogue.target.id.is_empty() {1509         return fail("catalogue", "the target has no id");1510     }1511     if catalogue.models.is_empty() {1512         return fail("catalogue", "the catalogue declares no model");1513     }1514     let mut capabilities = 0;1515     for model in &catalogue.models {1516         for (name, capability) in &model.capabilities {1517             capabilities += 1;1518             if let Some(reason) = capability_problem(name, capability) {1519                 return fail("catalogue", reason);1520             }1521         }1522     }1523     pass(1524         "catalogue",1525         format!("{capabilities} capability(s) on {}", catalogue.target.id),1526     )1527 }1528 1529 fn capability_problem(name: &str, capability: &Capability) -> Option<String> {1530     if capability.vocab.is_empty() {1531         return Some(format!("{name} has no vocab"));1532     }1533     if capability.parts.is_empty() {1534         return Some(format!("{name} has no parts"));1535     }1536     if matches!(capability.cancel, Cancel::Unknown(_)) {1537         return Some(format!(1538             "{name} has an unknown cancel: {}",1539             capability.cancel.as_str()1540         ));1541     }1542     if matches!(capability.stops, Stops::Unknown(_)) {1543         return Some(format!(1544             "{name} has an unknown stops: {}",1545             capability.stops.as_str()1546         ));1547     }1548     if matches!(capability.queue, Queue::Unknown(_)) {1549         return Some(format!(1550             "{name} has an unknown queue: {}",1551             capability.queue.as_str()1552         ));1553     }1554     None1555 }1556 1557 fn describe(recipe: &Recipe, catalogue: &Catalogue, deadline: Instant) -> Check {1558     let mut command = recipe.command();1559     command1560         .arg("--describe")1561         .stdout(Stdio::piped())1562         .stderr(Stdio::null());1563     let mut child = match command.spawn() {1564         Ok(child) => child,1565         Err(why) => return fail("describe", why.to_string()),1566     };1567     loop {1568         match child.try_wait() {1569             Ok(Some(_)) => break,1570             Ok(None) => {1571                 if remaining(deadline).is_zero() {1572                     kill_process(&mut Some(child));1573                     return fail("describe", "the command did not finish in the budget");1574                 }1575                 thread::sleep(POLL);1576             }1577             Err(why) => {1578                 kill_process(&mut Some(child));1579                 return fail("describe", why.to_string());1580             }1581         }1582     }1583     let output = match child.wait_with_output() {1584         Ok(output) => output,1585         Err(why) => return fail("describe", why.to_string()),1586     };1587     if !output.status.success() {1588         return fail("describe", format!("the command exited {}", output.status));1589     }1590     let text = match String::from_utf8(output.stdout) {1591         Ok(text) => text,1592         Err(_) => return fail("describe", "the catalogue is not UTF-8"),1593     };1594     let json = match inf3r_json::parse(&text) {1595         Ok(json) => json,1596         Err(why) => return fail("describe", why.to_string()),1597     };1598     let wire = mirror::to_json(&catalogue.to_value());1599     if json == wire {1600         pass("describe", "the printed catalogue matches the wire")1601     } else {1602         fail("describe", "the printed catalogue differs from the wire")1603     }1604 }1605 1606 fn run_jobs(1607     peer: &Peer,1608     catalogue: &Catalogue,1609     suite: &Suite,1610     deadline: Instant,1611     steps: &mut Vec<Step>,1612     refused: Option<&str>,1613 ) -> Vec<Check> {1614     let mut checks = Vec::new();1615     let mut exhausted = false;1616     for step in &suite.steps {1617         let name = step.capability.as_str();1618         let Some(model) = declared(catalogue, name) else {1619             let check = skip(name, "not declared");1620             steps.push(job_step(&check, 0, "none", true));1621             checks.push(check);1622             continue;1623         };1624         if let Some(detail) = refused {1625             let check = skip(name, format!("load refused: {detail}"));1626             steps.push(job_step(&check, 0, "none", true));1627             checks.push(check);1628             continue;1629         }1630         if exhausted {1631             let check = skip(name, "the budget was spent");1632             steps.push(job_step(&check, 0, "none", true));1633             checks.push(check);1634             continue;1635         }1636         let check = check_job(peer, model, step, deadline, steps);1637         if check.state == State::Fail && remaining(deadline).is_zero() {1638             exhausted = true;1639         }1640         checks.push(check);1641     }1642     for model in &catalogue.models {1643         for name in model.capabilities.keys() {1644             if !suite.names(name) {1645                 checks.push(skip(name, "not in the suite"));1646             }1647         }1648     }1649     checks1650 }1651 1652 fn declared<'a>(catalogue: &'a Catalogue, name: &str) -> Option<&'a Model> {1653     catalogue1654         .models1655         .iter()1656         .find(|model| model.capabilities.contains_key(name))1657 }1658 1659 fn check_job(1660     peer: &Peer,1661     model: &Model,1662     step: &Case,1663     deadline: Instant,1664     steps: &mut Vec<Step>,1665 ) -> Check {1666     let name = step.capability.as_str();1667     let open = open_body(model, name, &step.parts, JOB_CREDIT, deadline);1668     let job = match peer.open(open, &[]) {1669         Ok(job) => job,1670         Err(why) => {1671             let check = fail(name, why.to_string());1672             steps.push(job_step(&check, 0, "none", true));1673             return check;1674         }1675     };1676     let (_, rx) = read(job);1677     let (end, events) = terminal_count(&rx, deadline);1678     let outcome = end_name(&end);1679     let credit = credit_kept(&end);1680     let check = match end {1681         End::Done(done) if done.outcome == Outcome::Completed => pass(name, "the job completed"),1682         End::Done(done) if step.expect == Expect::Any => {1683             pass(name, format!("the job ended {:?}", done.outcome))1684         }1685         End::Done(done) if unimplemented_done(&done) => skip_unimplemented(name),1686         End::Done(done) => fail(name, format!("the job ended {:?}", done.outcome)),1687         End::Reject(refusal) if step.expect == Expect::Any => {1688             pass(name, format!("the binding answered: {refusal:?}"))1689         }1690         End::Reject(refusal) if unimplemented(&refusal) => skip_unimplemented(name),1691         End::Reject(refusal) => fail(name, format!("refused: {refusal:?}")),1692         End::Closed => fail(name, "the stream closed before a terminal frame"),1693         End::Timeout => fail(name, "no terminal frame before the budget"),1694         End::Error(why) => fail(name, why),1695     };1696     steps.push(job_step(&check, events, outcome, credit));1697     check1698 }1699 1700 fn job_step(check: &Check, events: usize, outcome: &str, credit: bool) -> Step {1701     let credit = if credit { "respected" } else { "crossed" };1702     Step {1703         what: "job",1704         detail: format!(1705             "{} {} events={events} outcome={outcome} credit={credit}",1706             state_name(check.state),1707             check.name1708         ),1709     }1710 }1711 1712 fn end_name(end: &End) -> &'static str {1713     match end {1714         End::Done(done) => match done.outcome {1715             Outcome::Completed => "completed",1716             Outcome::Cancelled => "cancelled",1717             Outcome::Failed => "failed",1718             Outcome::Expired => "expired",1719         },1720         End::Reject(_) => "rejected",1721         End::Closed => "closed",1722         End::Timeout => "timeout",1723         End::Error(_) => "error",1724     }1725 }1726 1727 fn credit_kept(end: &End) -> bool {1728     !matches!(end, End::Error(_))1729 }1730 1731 /// A file-backed input part. The bytes are real, but the plugin sees only the1732 /// descriptor; a binding that silently accepts inline bytes does not pass.1733 fn check_descriptor(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> Check {1734     let mut parts = job_parts(name);1735     let Some(index) = parts.iter().position(|part| part.kind == PartKind::Text) else {1736         return skip("descriptor", "the chosen capability has no text part");1737     };1738     let body::Hold::Inline(bytes) = parts[index].hold.clone() else {1739         return skip("descriptor", "the chosen text part is already a descriptor");1740     };1741     let path = temporary("part");1742     if let Err(why) = fs::write(&path, &bytes) {1743         return fail("descriptor", format!("{}: {why}", path.display()));1744     }1745     let file = match fs::File::open(&path) {1746         Ok(file) => file,1747         Err(why) => {1748             let _ = fs::remove_file(&path);1749             return fail("descriptor", format!("{}: {why}", path.display()));1750         }1751     };1752     let _ = fs::remove_file(&path);1753     parts[index].len = bytes.len() as u64;1754     parts[index].hold = body::Hold::Fd(0);1755     let open = open_body(model, name, &parts, JOB_CREDIT, deadline);1756     let job = match peer.open(open, &[file.as_fd()]) {1757         Ok(job) => job,1758         Err(why) => return fail("descriptor", why.to_string()),1759     };1760     let (_, rx) = read(job);1761     match terminal(&rx, deadline) {1762         End::Done(done) if done.outcome == Outcome::Completed => {1763             pass("descriptor", "the job read a descriptor input part")1764         }1765         End::Done(done) if unimplemented_done(&done) => {1766             skip("descriptor", "not implemented by this binding")1767         }1768         End::Done(done) => fail(1769             "descriptor",1770             format!(1771                 "the job ended {:?} with a descriptor part: {:?}",1772                 done.outcome, done.meta1773             ),1774         ),1775         End::Reject(refusal) if unimplemented(&refusal) => skip_unimplemented(name),1776         End::Reject(refusal) if matches!(refusal.code, ErrorCode::Part | ErrorCode::Capability) => {1777             skip(1778                 "descriptor",1779                 "the binding does not accept a descriptor part",1780             )1781         }1782         End::Reject(refusal) => fail("descriptor", format!("refused: {refusal:?}")),1783         End::Closed => fail("descriptor", "the stream closed before a terminal frame"),1784         End::Timeout => fail("descriptor", "no terminal frame before the budget"),1785         End::Error(why) => fail("descriptor", why),1786     }1787 }1788 1789 /// The capabilities that normally return a whole file in `done`.1790 fn artifact_target(catalogue: &Catalogue) -> Option<(&Model, &str)> {1791     const NAMES: [&str; 5] = ["image-gen", "image-edit", "music", "t2v-gen", "i2v-gen"];1792     for wanted in NAMES {1793         for model in &catalogue.models {1794             if let Some((name, _)) = model.capabilities.get_key_value(wanted) {1795                 return Some((model, name.as_str()));1796             }1797         }1798     }1799     None1800 }1801 1802 /// A descriptor artifact in the terminal frame. An inline artifact is not a1803 /// failure, but it does not prove the descriptor path either.1804 ///1805 /// The chosen capability is tried first, because a test peer may carry one on1806 /// any job. A capability that normally returns a whole file is the fallback.1807 fn check_artifact(1808     peer: &Peer,1809     catalogue: &Catalogue,1810     chosen: (&Model, &str),1811     deadline: Instant,1812 ) -> Check {1813     let mut targets = vec![chosen];1814     if let Some(target) = artifact_target(catalogue)1815         && (target.0.serve != chosen.0.serve || target.1 != chosen.1)1816     {1817         targets.push(target);1818     }1819     let mut skipped = None;1820     for (model, name) in targets {1821         match artifact_job(peer, model, name, deadline) {1822             ArtifactResult::Descriptor(count) => {1823                 return pass(1824                     "artifact",1825                     format!("the terminal frame carried {count} descriptor artifact(s)"),1826                 );1827             }1828             ArtifactResult::Missing | ArtifactResult::Inline => {}1829             ArtifactResult::Skip(why) => skipped = Some(why),1830             ArtifactResult::Fail(why) => return fail("artifact", why),1831         }1832     }1833     if let Some(why) = skipped {1834         skip("artifact", why)1835     } else {1836         skip("artifact", "no descriptor artifact was produced")1837     }1838 }1839 1840 /// What one artifact job proved.1841 enum ArtifactResult {1842     /// The frame carried this many descriptor artifacts.1843     Descriptor(usize),1844     /// The job completed without an artifact.1845     Missing,1846     /// The artifacts were all inline.1847     Inline,1848     /// The binding honestly does not run this capability.1849     Skip(&'static str),1850     /// The binding broke a rule.1851     Fail(String),1852 }1853 1854 fn artifact_job(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> ArtifactResult {1855     let open = open_body(model, name, &job_parts(name), JOB_CREDIT, deadline);1856     let job = match peer.open(open, &[]) {1857         Ok(job) => job,1858         Err(why) => return ArtifactResult::Fail(why.to_string()),1859     };1860     let (_, rx) = read(job);1861     loop {1862         match recv(&rx, deadline) {1863             None => return ArtifactResult::Fail("no terminal frame before the budget".into()),1864             Some(Err(why)) => return ArtifactResult::Fail(why.to_string()),1865             Some(Ok(None)) => {1866                 return ArtifactResult::Fail("the stream closed before a terminal frame".into());1867             }1868             Some(Ok(Some(Item::Accepted(_) | Item::Event { .. }))) => {}1869             Some(Ok(Some(Item::Reject(refusal)))) if unimplemented(&refusal) => {1870                 return ArtifactResult::Skip("not implemented by this binding");1871             }1872             Some(Ok(Some(Item::Reject(refusal)))) => {1873                 return ArtifactResult::Fail(format!("refused: {refusal:?}"));1874             }1875             Some(Ok(Some(Item::Done(done, fds)))) => {1876                 if !matches!(done.outcome, Outcome::Completed) {1877                     return ArtifactResult::Fail(format!("the job ended {:?}", done.outcome));1878                 }1879                 if done.artifacts.is_empty() {1880                     return ArtifactResult::Missing;1881                 }1882                 let mut descriptors = 0;1883                 for artifact in &done.artifacts {1884                     let body::Hold::Fd(index) = artifact.hold else {1885                         continue;1886                     };1887                     descriptors += 1;1888                     let Ok(index) = usize::try_from(index) else {1889                         return ArtifactResult::Fail("the descriptor index does not fit".into());1890                     };1891                     let Some(descriptor) = fds.get(index) else {1892                         return ArtifactResult::Fail(format!(1893                             "the artifact names descriptor {index}, which is absent"1894                         ));1895                     };1896                     let Ok(cloned) = descriptor.try_clone() else {1897                         return ArtifactResult::Fail(1898                             "the descriptor cannot be cloned for a check".into(),1899                         );1900                     };1901                     let file = fs::File::from(cloned);1902                     let Ok(metadata) = file.metadata() else {1903                         return ArtifactResult::Fail("the descriptor cannot be measured".into());1904                     };1905                     if metadata.len() != artifact.len {1906                         return ArtifactResult::Fail(format!(1907                             "the artifact declares {} bytes and the descriptor has {}",1908                             artifact.len,1909                             metadata.len()1910                         ));1911                     }1912                 }1913                 return if descriptors == 0 {1914                     ArtifactResult::Inline1915                 } else {1916                     ArtifactResult::Descriptor(descriptors)1917                 };1918             }1919         }1920     }1921 }1922 1923 fn check_extension(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> Check {1924     let open = open_body(model, name, &job_parts(name), JOB_CREDIT, deadline);1925     let job = match peer.open(open, &[]) {1926         Ok(job) => job,1927         Err(why) => return fail("extension", why.to_string()),1928     };1929     let id = job.id();1930     let handle = job.handle();1931     let (_, rx) = read(job);1932     // A type in the extension range is read and dropped. It must not end a1933     // job, and a peer that ignores every extension still has to answer.1934     if let Err(why) = handle.extension(id, b"verify") {1935         return fail("extension", why.to_string());1936     }1937     match terminal(&rx, deadline) {1938         End::Done(done) if done.outcome == Outcome::Completed => {1939             pass("extension", "the job completed across an extension frame")1940         }1941         End::Done(done) if unimplemented_done(&done) => {1942             skip("extension", "not implemented by this binding")1943         }1944         End::Done(done) => fail(1945             "extension",1946             format!("the job ended {:?} after an extension", done.outcome),1947         ),1948         End::Reject(refusal) if unimplemented(&refusal) => {1949             skip("extension", "not implemented by this binding")1950         }1951         End::Reject(refusal) => fail("extension", format!("refused: {refusal:?}")),1952         End::Closed => fail("extension", "the stream closed before a terminal frame"),1953         End::Timeout => fail("extension", "no terminal frame before the budget"),1954         End::Error(why) => fail("extension", why),1955     }1956 }1957 1958 fn check_cancel(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> Check {1959     if let Some(capability) = model.capabilities.get(name)1960         && capability.cancel != Cancel::Token1961     {1962         return skip(1963             "cancel",1964             format!(1965                 "declared cancel {}; the engine stops at that boundary",1966                 capability.cancel.as_str()1967             ),1968         );1969     }1970     // Zero initial credit gives the worker no way to finish before the cancel1971     // is read. The job therefore proves that a cancel is a control frame, not1972     // a race with the first event.1973     let open = open_body(model, name, &cancel_parts(name), 0, deadline);1974     let job = match peer.open(open, &[]) {1975         Ok(job) => job,1976         Err(why) => return fail("cancel", why.to_string()),1977     };1978     let id = job.id();1979     let handle = job.handle();1980     let (_, rx) = read(job);1981     let _ = handle.cancel(id);1982     loop {1983         match recv(&rx, deadline) {1984             None => return fail("cancel", "no terminal frame before the budget"),1985             Some(Err(why)) => return fail("cancel", why.to_string()),1986             Some(Ok(None)) => return fail("cancel", "the stream closed before a terminal frame"),1987             Some(Ok(Some(Item::Accepted(_) | Item::Event { .. }))) => {}1988             Some(Ok(Some(Item::Reject(refusal)))) if refusal.code == ErrorCode::Cancelled => {1989                 return pass("cancel", "the binding refused the job as cancelled");1990             }1991             Some(Ok(Some(Item::Reject(refusal)))) if refusal.code == ErrorCode::Credit => {1992                 return skip("cancel", "the binding refused the zero window");1993             }1994             Some(Ok(Some(Item::Reject(refusal)))) if unimplemented(&refusal) => {1995                 return skip("cancel", "not implemented by this binding");1996             }1997             Some(Ok(Some(Item::Reject(refusal)))) => {1998                 return fail("cancel", format!("refused: {refusal:?}"));1999             }2000             Some(Ok(Some(Item::Done(done, _)))) => {2001                 return match done.outcome {2002                     Outcome::Cancelled => pass("cancel", "the job ended cancelled"),2003                     Outcome::Completed => {2004                         pass("cancel", "the job completed before the cancel took effect")2005                     }2006                     other => fail("cancel", format!("the job ended {other:?}")),2007                 };2008             }2009         }2010     }2011 }2012 2013 fn check_credit(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> Check {2014     // A binding with one slot can send the terminal frame of the previous2015     // check before its worker releases the slot. The next open then sees a2016     // transient Busy; retry the whole check within the same deadline instead2017     // of reporting a credit failure that the next attempt disproves.2018     for attempt in 0..20 {2019         let check = check_credit_once(peer, model, name, deadline);2020         if check.state != State::Fail || !check.detail.contains("Busy") {2021             return check;2022         }2023         if attempt == 19 || Instant::now() >= deadline {2024             return check;2025         }2026         thread::sleep(POLL);2027     }2028     unreachable!("the retry loop returns on every path")2029 }2030 2031 fn check_credit_once(peer: &Peer, model: &Model, name: &str, deadline: Instant) -> Check {2032     if let Some(capability) = model.capabilities.get(name)2033         && capability.queue == Queue::Internal2034     {2035         return skip(2036             "credit",2037             "declared queue internal; the engine queues inside itself",2038         );2039     }2040     let open = open_body(model, name, &job_parts(name), CREDIT_WINDOW, deadline);2041     let job = match peer.open(open, &[]) {2042         Ok(job) => job,2043         Err(why) => return fail("credit", why.to_string()),2044     };2045     let id = job.id();2046     let handle = job.handle();2047     let (_, rx) = read(job);2048     // The initial window is one byte. A pause lets a binding that ignores the2049     // watermark cross it, which the client reports as a credit fault. A2050     // binding that waits is then released by one absolute window and must2051     // finish the job.2052     thread::sleep(CREDIT_PAUSE.min(remaining(deadline)));2053     let opened = handle.grant(id, JOB_CREDIT).is_ok();2054     match terminal(&rx, deadline) {2055         End::Done(done) if done.outcome == Outcome::Completed => {2056             if opened {2057                 pass("credit", "the job completed after the window opened")2058             } else {2059                 pass("credit", "the job completed before it needed more credit")2060             }2061         }2062         End::Done(done) if unimplemented_done(&done) => {2063             skip("credit", "not implemented by this binding")2064         }2065         End::Done(done) => fail("credit", format!("the job ended {:?}", done.outcome)),2066         End::Reject(refusal) if unimplemented(&refusal) => {2067             skip("credit", "not implemented by this binding")2068         }2069         // Refusing is the honest answer to a window that the job would overrun.2070         // The check is that the binding did not send past the watermark, not2071         // that it chose to serve the job.2072         End::Reject(refusal) if refusal.code == ErrorCode::Credit => pass(2073             "credit",2074             "the binding refused rather than overran the window",2075         ),2076         End::Reject(refusal) => fail("credit", format!("refused: {refusal:?}")),2077         End::Closed => fail("credit", "the stream closed before a terminal frame"),2078         End::Timeout => fail("credit", "no terminal frame before the budget"),2079         End::Error(why) => fail("credit", why),2080     }2081 }2082 2083 fn check_crash(2084     peer: &Peer,2085     model: &Model,2086     name: &str,2087     child: &mut Option<Runner>,2088     deadline: Instant,2089 ) -> Check {2090     let open = crash_open_body(model, name, deadline);2091     let job = match peer.open(open, &[]) {2092         Ok(job) => job,2093         Err(why) => return fail("crash", why.to_string()),2094     };2095     let (_, rx) = read(job);2096     // The kill lands as soon as the job exists. A binding that answers before2097     // the kill is as correct as one that dies in the middle: the property is2098     // that the caller does not hang, not that the child was slow.2099     kill(child);2100     loop {2101         match recv(&rx, deadline) {2102             None => return fail("crash", "the caller hung after the child was killed"),2103             Some(Err(_)) | Some(Ok(None)) => {2104                 return pass("crash", "the caller saw the end of the stream");2105             }2106             Some(Ok(Some(Item::Event { .. }))) => {}2107             Some(Ok(Some(Item::Accepted(_)))) => {}2108             Some(Ok(Some(Item::Reject(refusal)))) => {2109                 return pass("crash", format!("the caller saw a refusal: {refusal:?}"));2110             }2111             Some(Ok(Some(Item::Done(done, _)))) => {2112                 return pass(2113                     "crash",2114                     format!(2115                         "the job finished {:?} before the kill arrived",2116                         done.outcome2117                     ),2118                 );2119             }2120         }2121     }2122 }2123 2124 fn cancel_parts(name: &str) -> Vec<body::Part> {2125     if name == "chat" {2126         return vec![text(Some("user"), &"slow ".repeat(CANCEL_WORDS))];2127     }2128     job_parts(name)2129 }2130 2131 fn crash_open_body(model: &Model, name: &str, deadline: Instant) -> Open {2132     let mut parts = job_parts(name);2133     if name == "chat" {2134         let prompt = "slow ".repeat(CRASH_WORDS);2135         parts = vec![text(Some("user"), &prompt)];2136     }2137     open_body(model, name, &parts, JOB_CREDIT, deadline)2138 }2139 2140 fn open_body(2141     model: &Model,2142     name: &str,2143     parts: &[body::Part],2144     credit: u64,2145     deadline: Instant,2146 ) -> Open {2147     static NEXT: AtomicU64 = AtomicU64::new(1);2148     Open {2149         request_id: format!("verify-{}", NEXT.fetch_add(1, Ordering::Relaxed)),2150         model: model.serve.clone(),2151         capability: name.to_string(),2152         credit,2153         budget_ms: u32::try_from(remaining(deadline).as_millis()).unwrap_or(u32::MAX),2154         parts: parts.to_vec(),2155         params: Value::Map(Vec::new()),2156     }2157 }2158 2159 fn job_parts(name: &str) -> Vec<body::Part> {2160     match name {2161         "chat" => vec![text(Some("user"), "one two three")],2162         "embed" => vec![text(None, "one")],2163         "rerank" => vec![2164             text(Some("query"), "one"),2165             json(Some("documents"), r#"{"documents":["one","two"]}"#),2166         ],2167         "decide" => vec![2168             text(Some("question"), "which?"),2169             json(2170                 Some("options"),2171                 r#"{"options":[{"id":"a","label":"A","description":"first"},{"id":"b","label":"B","description":"second"}]}"#,2172             ),2173         ],2174         "extract" => vec![2175             text(Some("source"), "one"),2176             json(Some("fields"), r#"{"fields":[{"name":"who"}]}"#),2177         ],2178         "tts" => vec![text(Some("any"), "one")],2179         "stt" => vec![part(PartKind::Audio, Some("any"), AUDIO_MIME, AUDIO_SAMPLE)],2180         "music" => vec![text(Some("prompt"), "one")],2181         "image-gen" => vec![text(Some("prompt"), "one")],2182         "image-edit" => vec![2183             part(PartKind::Image, Some("source"), IMAGE_MIME, IMAGE_SAMPLE),2184             text(Some("instruction"), "one"),2185         ],2186         "t2v-gen" => vec![text(Some("prompt"), "one")],2187         "i2v-gen" => vec![2188             part(2189                 PartKind::Image,2190                 Some("first_frame"),2191                 IMAGE_MIME,2192                 IMAGE_SAMPLE,2193             ),2194             text(Some("prompt"), "one"),2195         ],2196         _ => vec![text(None, "one")],2197     }2198 }2199 2200 fn part(kind: PartKind, role: Option<&str>, mime: &str, bytes: &[u8]) -> body::Part {2201     body::Part {2202         kind,2203         mime: mime.to_string(),2204         role: role.map(str::to_string),2205         len: bytes.len() as u64,2206         hold: body::Hold::Inline(bytes.to_vec()),2207     }2208 }2209 2210 fn text(role: Option<&str>, value: &str) -> body::Part {2211     part(PartKind::Text, role, TEXT_MIME, value.as_bytes())2212 }2213 2214 fn json(role: Option<&str>, value: &str) -> body::Part {2215     part(PartKind::Json, role, JSON_MIME, value.as_bytes())2216 }2217 2218 fn terminal(rx: &Receiver<io::Result<Option<Item>>>, deadline: Instant) -> End {2219     terminal_count(rx, deadline).02220 }2221 2222 fn terminal_count(rx: &Receiver<io::Result<Option<Item>>>, deadline: Instant) -> (End, usize) {2223     let mut events = 0;2224     loop {2225         match recv(rx, deadline) {2226             None => return (End::Timeout, events),2227             Some(Err(why)) => return (End::Error(why.to_string()), events),2228             Some(Ok(None)) => return (End::Closed, events),2229             Some(Ok(Some(Item::Done(done, _)))) => return (End::Done(done), events),2230             Some(Ok(Some(Item::Reject(refusal)))) => return (End::Reject(refusal), events),2231             Some(Ok(Some(Item::Event { .. }))) => events += 1,2232             Some(Ok(Some(Item::Accepted(_)))) => {}2233         }2234     }2235 }2236 2237 fn read(mut job: Job) -> (u16, Receiver<io::Result<Option<Item>>>) {2238     let id = job.id();2239     let (tx, rx) = mpsc::channel();2240     thread::spawn(move || {2241         loop {2242             let item = job.next();2243             let terminal = matches!(2244                 &item,2245                 Ok(Some(Item::Done(_, _) | Item::Reject(_))) | Ok(None) | Err(_)2246             );2247             if tx.send(item).is_err() || terminal {2248                 break;2249             }2250         }2251     });2252     (id, rx)2253 }2254 2255 fn recv(2256     rx: &Receiver<io::Result<Option<Item>>>,2257     deadline: Instant,2258 ) -> Option<io::Result<Option<Item>>> {2259     rx.recv_timeout(remaining(deadline)).ok()2260 }2261 2262 /// The end of a job budget, counted from now and capped by the whole run.2263 fn job_deadline(budget: Duration, overall: Instant) -> Instant {2264     (Instant::now() + budget).min(overall)2265 }2266 2267 fn remaining(deadline: Instant) -> Duration {2268     deadline.saturating_duration_since(Instant::now())2269 }2270 2271 fn chosen(catalogue: &Catalogue) -> Option<(&Model, &str)> {2272     let mut first = None;2273     for model in &catalogue.models {2274         for name in model.capabilities.keys() {2275             if name == "chat" {2276                 return Some((model, name.as_str()));2277             }2278             if first.is_none() {2279                 first = Some((model, name.as_str()));2280             }2281         }2282     }2283     first2284 }2285 2286 fn unimplemented(refusal: &Refusal) -> bool {2287     refusal.code == ErrorCode::Capability2288 }2289 2290 fn unimplemented_done(done: &Done) -> bool {2291     done.outcome == Outcome::Failed2292         && done2293             .meta2294             .as_ref()2295             .and_then(|meta| meta.get("error"))2296             .is_some_and(|value| matches!(value, Value::Text(text) if text == "capability"))2297 }2298 2299 fn skip_unimplemented(name: &str) -> Check {2300     skip(name, "not implemented by this binding")2301 }2302 2303 fn pass(name: impl Into<String>, detail: impl Into<String>) -> Check {2304     Check {2305         name: name.into(),2306         state: State::Pass,2307         detail: detail.into(),2308     }2309 }2310 2311 fn fail(name: impl Into<String>, detail: impl Into<String>) -> Check {2312     Check {2313         name: name.into(),2314         state: State::Fail,2315         detail: detail.into(),2316     }2317 }2318 2319 fn skip(name: impl Into<String>, detail: impl Into<String>) -> Check {2320     Check {2321         name: name.into(),2322         state: State::Skip,2323         detail: detail.into(),2324     }2325 }2326 2327 /// A unique path under the system temporary directory. The caller removes it.2328 fn temporary(kind: &str) -> PathBuf {2329     static NEXT: AtomicU64 = AtomicU64::new(1);2330     let serial = NEXT.fetch_add(1, Ordering::Relaxed);2331     std::env::temp_dir().join(format!(2332         "inf3r-verify-{kind}-{}-{serial}",2333         std::process::id()2334     ))2335 }2336 2337 fn start_command(recipe: &Recipe, deadline: Instant) -> io::Result<Connected> {2338     let socket_dir = SocketDir::new("socket")?;2339     let path = socket_dir.join("socket");2340     let listener = UnixListener::bind(&path)?;2341     fs::set_permissions(&path, fs::Permissions::from_mode(0o666))?;2342     listener.set_nonblocking(true)?;2343 2344     let mut command = recipe.command();2345     command.arg("--socket").arg(&path);2346     let mut child = command.spawn()?;2347 2348     loop {2349         // A child that failed to start must not spin the accept loop until2350         // the whole budget expires. Its exit status is the useful answer.2351         match child.try_wait() {2352             Ok(Some(status)) => {2353                 return Err(io::Error::other(format!(2354                     "the command exited before it connected: {status}"2355                 )));2356             }2357             Ok(None) => {}2358             Err(why) => {2359                 kill_process(&mut Some(child));2360                 return Err(why);2361             }2362         }2363         if remaining(deadline).is_zero() {2364             kill_process(&mut Some(child));2365             return Err(io::Error::new(2366                 io::ErrorKind::TimedOut,2367                 "the command did not connect in the budget",2368             ));2369         }2370         match listener.accept() {2371             Ok((stream, _)) => {2372                 stream.set_nonblocking(false)?;2373                 match Peer::connect(stream, "verify", remaining(deadline)) {2374                     Ok(peer) => {2375                         return Ok(Connected {2376                             peer,2377                             child: Some(Runner::Process(child)),2378                             _socket_dir: Some(socket_dir),2379                             trace: None,2380                         });2381                     }2382                     Err(why) => {2383                         kill_process(&mut Some(child));2384                         return Err(why);2385                     }2386                 }2387             }2388             Err(why) if why.kind() == io::ErrorKind::WouldBlock => thread::sleep(POLL),2389             Err(why) => {2390                 kill_process(&mut Some(child));2391                 return Err(why);2392             }2393         }2394     }2395 }2396 2397 fn kill_process(child: &mut Option<Child>) {2398     if let Some(child) = child {2399         let _ = child.kill();2400         let _ = child.wait();2401     }2402 }2403 2404 fn kill(child: &mut Option<Runner>) {2405     let Some(child) = child.take() else {2406         return;2407     };2408     match child {2409         Runner::Process(mut child) => {2410             let _ = child.kill();2411             let _ = child.wait();2412         }2413         Runner::Container(mut child) => {2414             let _ = child.stop(Duration::from_secs(5));2415         }2416     }2417 }