plugins/mock/x64-cpu/src/bin/faulty.rs 12.5 KiB 353 lines Raw
1 //! The mock plugin with one fault, chosen on the command line.2 //!3 //! A conformance suite must prove that the core survives a plugin that lies:4 //! that rejects, that crashes at each point of a job, that stalls, that writes a5 //! frame that is not a frame, that sends beyond its credit, that speaks another6 //! version, and that sends a frame the receiver does not know.7 //!8 //! This binary is the raw protocol, not the SDK: a fault is a thing the SDK9 //! makes impossible, so the tool that injects one must not be the SDK.10 //!11 //! Usage: `inf3r-mock-fault --socket <path> --fault <mode>`. The modes are in12 //! [`Fault`], and `--list` prints them.13 14 use std::os::unix::net::UnixStream;15 use std::process::ExitCode;16 17 use inf3r_proto::body::{self, Body, Catalogue, ErrorCode, Ready, Refusal, Welcome};18 use inf3r_proto::{Header, Kind, recv_frame, send_frame};19 20 /// The version this build speaks when the fault is not a version fault.21 const VERSION: u32 = 1;22 /// The version that no receiver speaks, for the `version` fault.23 const OTHER_VERSION: u32 = 99;24 /// The bytes of a frame header.25 const HEADER: usize = 8;26 27 /// One fault.28 #[derive(Clone, Copy, PartialEq, Eq, Debug)]29 enum Fault {30     /// Refuse every job with this code.31     Reject(ErrorCode),32     /// Accept, then exit 1 before the first event.33     CrashAfterAccept,34     /// Accept, send one event, then exit 1.35     CrashAfterEvent,36     /// Accept and never send anything until the process is killed.37     Stall,38     /// Write twelve bytes that are not a frame, then exit.39     BadFrame,40     /// Say hello with a version that the receiver does not speak.41     Version,42     /// Send events until the credit is spent, then one more than that.43     OverCredit,44     /// Send a frame of a type that this protocol does not define.45     UnknownFrame,46     /// Say hello and nothing else: no welcome, no catalogue.47     Silent,48 }49 50 impl Fault {51     fn parse(text: &str) -> Option<Fault> {52         Some(match text {53             "reject" => Fault::Reject(ErrorCode::Busy),54             "reject-part" => Fault::Reject(ErrorCode::Part),55             "reject-version" => Fault::Reject(ErrorCode::Version),56             "crash-accept" => Fault::CrashAfterAccept,57             "crash-event" => Fault::CrashAfterEvent,58             "stall" => Fault::Stall,59             "bad-frame" => Fault::BadFrame,60             "version" => Fault::Version,61             "credit" => Fault::OverCredit,62             "unknown" => Fault::UnknownFrame,63             "silent" => Fault::Silent,64             _ => return None,65         })66     }67 68     fn name(self) -> &'static str {69         match self {70             Fault::Reject(_) => "reject",71             Fault::CrashAfterAccept => "crash-accept",72             Fault::CrashAfterEvent => "crash-event",73             Fault::Stall => "stall",74             Fault::BadFrame => "bad-frame",75             Fault::Version => "version",76             Fault::OverCredit => "credit",77             Fault::UnknownFrame => "unknown",78             Fault::Silent => "silent",79         }80     }81 82     fn all() -> [Fault; 11] {83         [84             Fault::Reject(ErrorCode::Busy),85             Fault::Reject(ErrorCode::Part),86             Fault::Reject(ErrorCode::Version),87             Fault::CrashAfterAccept,88             Fault::CrashAfterEvent,89             Fault::Stall,90             Fault::BadFrame,91             Fault::Version,92             Fault::OverCredit,93             Fault::UnknownFrame,94             Fault::Silent,95         ]96     }97 }98 99 /// The frame that this mock says it can serve.100 fn catalogue() -> Catalogue {101     Catalogue {102         target: body::Target {103             id: "mock-fault".into(),104             backend: "mock".into(),105             arch: vec![std::env::consts::ARCH.into()],106             devices: 0,107             vram_mb: Vec::new(),108         },109         models: vec![body::Model {110             serve: "faulty".into(),111             alias_of: None,112             weights_bytes: 0,113             load_ms: 0,114             capabilities: std::collections::BTreeMap::from([(115                 "chat".to_string(),116                 body::Capability {117                     vocab: "chat.v1".into(),118                     parts: vec![body::PartKind::Text],119                     channels: vec!["text".into()],120                     limits: std::collections::BTreeMap::new(),121                     cancel: body::Cancel::Token,122                     stops: body::Stops::Plugin,123                     queue: body::Queue::None,124                 },125             )]),126         }],127         runtime: None,128         cache: None,129     }130 }131 132 fn main() -> ExitCode {133     let mut socket = None;134     let mut fault = None;135     let mut args = std::env::args().skip(1);136     while let Some(arg) = args.next() {137         match arg.as_str() {138             "--socket" => socket = args.next(),139             "--fault" => fault = args.next().as_deref().and_then(Fault::parse),140             "--list" => {141                 for fault in Fault::all() {142                     println!("{}", fault.name());143                 }144                 return ExitCode::SUCCESS;145             }146             other => {147                 eprintln!("unknown argument {other}");148                 return ExitCode::from(2);149             }150         }151     }152     let Some(name) = socket else {153         eprintln!("--socket is required");154         return ExitCode::from(2);155     };156     let Some(fault) = fault else {157         eprintln!("--fault is required and must be one of --list");158         return ExitCode::from(2);159     };160 161     let stream = match UnixStream::connect(&name) {162         Ok(stream) => stream,163         Err(why) => {164             eprintln!("connect {name}: {why}");165             return ExitCode::FAILURE;166         }167     };168     match run(&stream, fault) {169         Ok(code) => code,170         Err(why) => {171             eprintln!("{why}");172             ExitCode::FAILURE173         }174     }175 }176 177 fn run(socket: &UnixStream, fault: Fault) -> Result<ExitCode, Box<dyn std::error::Error>> {178     let mut session_stream: u16 = 0;179     loop {180         let Some((frame, _fds)) = recv_frame(socket)? else {181             return Ok(ExitCode::SUCCESS);182         };183         let kind = frame.header.kind;184         let id = frame.header.stream;185         let Ok(body) = Body::decode(kind, &frame.payload) else {186             return Ok(ExitCode::FAILURE);187         };188 189         match body {190             Body::Hello(_) => {191                 if fault == Fault::Silent {192                     // Nothing. The caller's handshake deadline decides.193                     continue;194                 }195                 if fault == Fault::Version {196                     let hello = Body::Welcome(Welcome {197                         v: OTHER_VERSION,198                         max_inflight: 1,199                     });200                     send(socket, Kind::Welcome, 0, &hello)?;201                     continue;202                 }203                 send(204                     socket,205                     Kind::Welcome,206                     0,207                     &Body::Welcome(Welcome {208                         v: VERSION,209                         max_inflight: 1,210                     }),211                 )?;212                 send(socket, Kind::Catalogue, 0, &Body::Catalogue(catalogue()))?;213             }214             Body::Grant(_) => {215                 if fault == Fault::BadFrame {216                     // A frame that is not a frame: two headers' worth of junk.217                     use std::io::Write;218                     let mut out = socket;219                     out.write_all(&[0xff; HEADER + 4])?;220                     return Ok(ExitCode::FAILURE);221                 }222                 send(223                     socket,224                     Kind::Ready,225                     0,226                     &Body::Ready(Ready {227                         load_ms: 1,228                         cache_fingerprint: None,229                     }),230                 )?;231             }232             Body::Open(open) => {233                 session_stream = id;234                 match fault {235                     Fault::Reject(code) => {236                         send(237                             socket,238                             Kind::Reject,239                             id,240                             &Body::Reject(Refusal {241                                 code,242                                 detail: Some(format!("fault {}", fault.name())),243                             }),244                         )?;245                     }246                     Fault::CrashAfterAccept => {247                         send(248                             socket,249                             Kind::Accept,250                             id,251                             &Body::Accept(body::Accepted { est_ms: Some(1) }),252                         )?;253                         return Ok(ExitCode::FAILURE);254                     }255                     Fault::CrashAfterEvent => {256                         send(257                             socket,258                             Kind::Accept,259                             id,260                             &Body::Accept(body::Accepted { est_ms: Some(1) }),261                         )?;262                         send(socket, Kind::Event, id, &text_event("half"))?;263                         return Ok(ExitCode::FAILURE);264                     }265                     Fault::Stall => {266                         send(267                             socket,268                             Kind::Accept,269                             id,270                             &Body::Accept(body::Accepted { est_ms: None }),271                         )?;272                         // The socket stays open and nothing else is written.273                         std::thread::sleep(std::time::Duration::from_secs(600));274                     }275                     Fault::UnknownFrame => {276                         send(277                             socket,278                             Kind::Accept,279                             id,280                             &Body::Accept(body::Accepted { est_ms: None }),281                         )?;282                         // A type in the extension range. A receiver that does283                         // not know it must ignore it and finish the job.284                         let mut payload = Vec::new();285                         inf3r_proto::cbor::encode(286                             &inf3r_proto::Value::Text("ignored".into()),287                             &mut payload,288                         );289                         send_raw(socket, Kind::Extension(0x40), id, &payload)?;290                         send(socket, Kind::Done, id, &done())?;291                     }292                     Fault::OverCredit => {293                         send(294                             socket,295                             Kind::Accept,296                             id,297                             &Body::Accept(body::Accepted { est_ms: None }),298                         )?;299                         // `open.credit` is the window. Two events of 8 KiB300                         // exceed any window that a caller gives this mock.301                         for _ in 0..2 {302                             let big = "x".repeat(8192);303                             send(socket, Kind::Event, id, &text_event(&big))?;304                         }305                         send(socket, Kind::Done, id, &done())?;306                     }307                     _ => {308                         send(309                             socket,310                             Kind::Accept,311                             id,312                             &Body::Accept(body::Accepted { est_ms: None }),313                         )?;314                         send(socket, Kind::Event, id, &text_event("ok"))?;315                         send(socket, Kind::Done, id, &done())?;316                     }317                 }318                 let _ = open.credit;319             }320             Body::Cancel(_) | Body::Window(_) | Body::Ping(_) | Body::Pong(_) => {}321             _ => {}322         }323         let _ = session_stream;324     }325 }326 327 fn send(socket: &UnixStream, kind: Kind, stream: u16, body: &Body) -> std::io::Result<()> {328     let payload = body.encode();329     send_raw(socket, kind, stream, &payload)330 }331 332 fn send_raw(socket: &UnixStream, kind: Kind, stream: u16, payload: &[u8]) -> std::io::Result<()> {333     let length = u32::try_from(payload.len()).unwrap_or(0);334     send_frame(socket, Header::new(kind, stream, length), payload, &[])335         .map_err(|why| std::io::Error::other(why.to_string()))336 }337 338 fn text_event(text: &str) -> Body {339     Body::Event(body::Event {340         ch: "text".into(),341         mime: "text/plain; charset=utf-8".into(),342         data: text.as_bytes().to_vec(),343     })344 }345 346 fn done() -> Body {347     Body::Done(body::Done {348         outcome: body::Outcome::Completed,349         artifacts: Vec::new(),350         usage: std::collections::BTreeMap::new(),351         meta: None,352     })353 }