plugins/mock/x64-cpu/src/lib.rs 8.5 KiB 252 lines Raw
1 //! The conformance plugin: one binary, twelve capabilities, no model.2 //!3 //! It is a deliverable, not test scaffolding. It makes every rule of the engine4 //! testable on a machine with no GPU: a job that streams, a job that fails, a5 //! job that must wait for credit, and a catalogue that names twelve6 //! capabilities. Its output is a function of its input and its seed, so a golden7 //! that it wrote yesterday still matches today.8 //!9 //! It declares no dependency, so `grant` is empty and a load costs nothing.10 11 pub mod cache;12 pub mod capability;13 pub mod catalogue;14 15 use std::io::Read;16 use std::sync::Arc;17 18 use inf3r_plugin_sdk::Failure;19 use inf3r_plugin_sdk::capability::{Part, Report, Request};20 use inf3r_plugin_sdk::emitter::{EmitError, Emitter};21 use inf3r_plugin_sdk::serve::{Plugin, RuntimeVersion};22 use inf3r_proto::body::{Catalogue, Grant, Ready};23 24 use crate::catalogue::Mock;25 26 /// The plugin.27 #[derive(Default)]28 pub struct MockCpu {29     /// The catalogue that this plugin serves.30     mock: Mock,31     /// The fake slot codec used by the cache conformance path.32     cache: Arc<cache::MockCache>,33 }34 35 impl Plugin for MockCpu {36     fn max_inflight(&self) -> u16 {37         // The mock has no device memory, so the only limit is the number of38         // worker threads that a test can afford.39         440     }41 42     fn runtime(&self) -> Option<RuntimeVersion> {43         None44     }45 46     fn catalogue(&self) -> Catalogue {47         self.mock.catalogue()48     }49 50     fn cache(&self) -> Option<Arc<dyn inf3r_plugin_sdk::cache::CacheCodec>> {51         Some(self.cache.clone())52     }53 54     fn load(&self, _grant: &Grant) -> Result<Ready, Failure> {55         // No weights, no device, no time. A load of zero milliseconds is the56         // honest number and it makes a golden that includes it stable.57         Ok(Ready {58             load_ms: 0,59             cache_fingerprint: None,60         })61     }62 63     fn run(64         &self,65         capability: &str,66         req: Request<'_>,67         out: &mut dyn Emitter,68     ) -> Result<Report, Failure> {69         let prompt = if capability == "chat" {70             chat_text(&req)71         } else {72             None73         };74         if let Some(prompt) = prompt.as_deref() {75             let _ = self.cache.restore(prompt);76         }77         let result = match capability {78             "chat" => capability::chat(req, out),79             "embed" => capability::embed(req, out),80             "rerank" => capability::rerank(req, out),81             "decide" => capability::decide(req, out),82             "extract" => capability::extract(req, out),83             "tts" => capability::tts(req, out),84             "stt" => capability::stt(req, out),85             "music" => capability::music(req, out),86             "image-gen" => capability::image_gen(req, out),87             "image-edit" => capability::image_edit(req, out),88             "t2v-gen" => capability::t2v_gen(req, out),89             "i2v-gen" => capability::i2v_gen(req, out),90             other => return Err(Failure::capability(other)),91         };92         if let Some(prompt) = prompt.as_deref()93             && result.is_ok()94         {95             self.cache.save(prompt);96         }97         match result {98             Ok(report) => Ok(report),99             Err(Silent::Emit(why)) => match why {100                 EmitError::Cancelled => Ok(Report::default()),101                 EmitError::Blocked => Err(Failure::new(102                     inf3r_proto::body::ErrorCode::Timeout,103                     "the window never opened",104                 )),105             },106             Err(Silent::Refused(failure)) => Err(failure),107         }108     }109 }110 111 /// The user text of a chat request, for the fake cache key. The real chat112 /// capability parses the same role and refuses a malformed request; a cache113 /// key is not allowed to change that decision.114 fn chat_text(req: &Request<'_>) -> Option<String> {115     for part in req.parts {116         if part.role == Some("user") {117             if let Some(bytes) = part.bytes() {118                 return String::from_utf8(bytes.to_vec()).ok();119             }120             let mut bytes = Vec::new();121             part.reader().read_to_end(&mut bytes).ok()?;122             return String::from_utf8(bytes).ok();123         }124     }125     None126 }127 128 /// Why a capability stopped before its terminal frame.129 pub enum Silent {130     /// The emitter refused.131     Emit(EmitError),132     /// The request was not one that the capability permits.133     Refused(Failure),134 }135 136 impl From<EmitError> for Silent {137     fn from(why: EmitError) -> Silent {138         Silent::Emit(why)139     }140 }141 142 /// The parts of a request, by role, with the checks that the capability page143 /// gives. Every capability starts here, so a malformed request is refused144 /// before the mock invents any output.145 pub struct Input<'a> {146     /// The parts, in the order that the caller declared them.147     parts: &'a [Part<'a>],148     /// The text of each part, after an inline body or a descriptor is read.149     /// A capability gets the same answer for either hold.150     texts: Vec<Option<String>>,151 }152 153 impl<'a> Input<'a> {154     /// Checks a request against one capability's part table.155     pub fn new(req: &'a Request<'a>) -> Input<'a> {156         let texts = req.parts.iter().map(text_of).collect();157         Input {158             parts: req.parts,159             texts,160         }161     }162 163     /// The text of the part with this role, when there is one.164     pub fn text(&self, role: &str) -> Result<Option<&str>, Silent> {165         let mut found = None;166         for (index, part) in self.parts.iter().enumerate() {167             if part.role == Some(role) {168                 if found.is_some() {169                     return Err(refuse(format!("two parts have the role {role}")));170                 }171                 let text = self.texts[index]172                     .as_deref()173                     .ok_or_else(|| refuse(format!("the part {role} is not UTF-8 text")))?;174                 found = Some(text);175             }176         }177         Ok(found)178     }179 180     /// Every text part, in input order, when every part is text.181     pub fn all_text(&self) -> Option<Vec<&str>> {182         self.texts.iter().map(Option::as_deref).collect()183     }184 185     /// The text of the part with this role, which the capability requires.186     pub fn require_text(&self, role: &str) -> Result<&str, Silent> {187         self.text(role)?188             .ok_or_else(|| refuse(format!("the part {role} is missing")))189     }190 191     /// The bytes of the part with this role, when there is one.192     pub fn bytes(&self, role: &str) -> Result<Option<&'a Part<'a>>, Silent> {193         let mut found = None;194         for part in self.parts {195             if part.role == Some(role) {196                 if found.is_some() {197                     return Err(refuse(format!("two parts have the role {role}")));198                 }199                 found = Some(part);200             }201         }202         Ok(found)203     }204 205     /// The JSON of the part with this role, which the capability requires.206     pub fn require_json(&self, role: &str) -> Result<inf3r_json::Value, Silent> {207         let part = self208             .bytes(role)?209             .ok_or_else(|| refuse(format!("the part {role} is missing")))?;210         if part.kind != inf3r_proto::body::PartKind::Json {211             return Err(refuse(format!("the part {role} is not JSON")));212         }213         let mut bytes = Vec::new();214         part.reader()215             .read_to_end(&mut bytes)216             .map_err(|why| refuse(format!("the part {role}: {why}")))?;217         let text = std::str::from_utf8(&bytes)218             .map_err(|_| refuse(format!("the part {role} is not UTF-8")))?;219         inf3r_json::parse(text).map_err(|why| refuse(format!("the part {role}: {why}")))220     }221 }222 223 /// Reads one text part, from its inline bytes or its descriptor.224 fn text_of(part: &Part<'_>) -> Option<String> {225     if part.kind != inf3r_proto::body::PartKind::Text {226         return None;227     }228     if let Some(bytes) = part.bytes() {229         return std::str::from_utf8(bytes).ok().map(str::to_string);230     }231     let mut bytes = Vec::new();232     part.reader().read_to_end(&mut bytes).ok()?;233     String::from_utf8(bytes).ok()234 }235 236 /// A refusal that names the fault.237 pub fn refuse(why: impl Into<String>) -> Silent {238     Silent::Refused(Failure::part(why))239 }240 241 /// A deterministic number from the request text.242 ///243 /// The mock has no model to sample from, so it derives its values from a hash.244 /// The point is repeatability: two runs of a golden job give the same bytes.245 pub fn digest(text: &str) -> u64 {246     let mut hash: u64 = 0xcbf2_9ce4_8422_2325;247     for byte in text.as_bytes() {248         hash ^= u64::from(*byte);249         hash = hash.wrapping_mul(0x0000_0100_0000_01b3);250     }251     hash252 }