crates/edge/bind/src/cache.rs 37.2 KiB 1097 lines Raw
1 //! The HTTP compatibility cache adapter.2 //!3 //! The binder does not implement cache policy. It gives the SDK driver one4 //! engine-local slot: save and restore through the runtime's HTTP surface,5 //! erase the slot, and optionally prepare a prompt-only prefix. Keys, lineages,6 //! anchors, descriptors, and commits are the SDK's business.7 //!8 //! One engine API is understood here: the optional, engine-neutral cache bridge9 //! at `GET /inf3r/cache`. A runtime that does not advertise it runs without10 //! cache; the binder never falls back to a vendor route or a vendor flag.11 12 use std::fs::{self, File};13 use std::io::{self, Read};14 use std::os::unix::fs::PermissionsExt;15 use std::path::{Path, PathBuf};16 use std::sync::{Arc, Mutex, MutexGuard};17 use std::time::Duration;18 19 use inf3r_bundle::{Bundle, EngineKind};20 use inf3r_json::Value;21 use inf3r_plugin_sdk::cache::{22     CacheCodec, CacheDriver, CacheFile, CacheSlot, CacheTransport, CacheWrite, Chain, FlushReport,23     PrefixOutcome, PrefixReply, copy_in as descriptor_copy_in, copy_out as descriptor_copy_out,24 };25 use inf3r_plugin_sdk::capability::Request;26 use inf3r_sha256::Sha256;27 28 use crate::http;29 use crate::manifest::{ModelSpec, TargetProfile};30 31 /// The one slot that a `-np 1` engine exposes.32 const SLOT: u32 = 0;33 34 /// The file names inside the private exchange directory.35 const BRIDGE_SAVE: &str = "bridge-save.bin";36 const BRIDGE_RESTORE: &str = "bridge-restore.bin";37 38 /// The longest prefix prepare the binder will wait for, even when the job has39 /// more time. A long system prompt is paid once; it must not become an40 /// unbounded stall.41 pub(crate) const PREFIX_BUDGET: Duration = Duration::from_secs(30);42 43 /// The largest bridge control reply the binder will read.44 const BRIDGE_REPLY_LIMIT: usize = 64 * 1024;45 46 /// One engine cache API selected by the probe.47 #[derive(Clone, Copy, PartialEq, Eq, Debug)]48 enum Api {49     /// The engine cache bridge. `prefix` says whether it can prepare one.50     Bridge { prefix: bool },51     /// The runtime answered, but did not advertise the bridge. The process52     /// runs without cache from then on.53     Missing,54 }55 56 /// The HTTP cache codec exposed to the plugin runtime.57 pub struct BoundCache {58     driver: Arc<CacheDriver<HttpSlot>>,59 }60 61 /// The engine-local half: HTTP save/restore/erase and prefix prepare.62 struct HttpSlot {63     endpoint: Arc<Mutex<Option<String>>>,64     staging: PathBuf,65     /// The selected engine API, once the probe has answered.66     api: Mutex<Option<Api>>,67 }68 69 impl BoundCache {70     pub fn new(71         bundle: &Bundle,72         model: &ModelSpec,73         target: &TargetProfile,74         dir: &Path,75         staging: PathBuf,76         endpoint: Arc<Mutex<Option<String>>>,77     ) -> io::Result<BoundCache> {78         let context = model.context.unwrap_or(0);79         let per_token = model.kv_bytes_per_token.unwrap_or(0);80         let max_entry_bytes = context.saturating_mul(per_token).max(1);81         let fingerprint = fingerprint(bundle, model, target, dir)?;82         let spec = inf3r_proto::body::CacheSpec {83             codec_version: 1,84             slots: 1,85             state_kind: inf3r_proto::body::CacheStateKind::CheckpointExact,86             max_entry_bytes,87             local_ram_bytes: 0,88             supports_save: true,89             supports_restore: true,90             supports_erase: true,91         };92         let slot = HttpSlot {93             endpoint,94             staging,95             api: Mutex::new(None),96         };97         Ok(BoundCache {98             driver: Arc::new(CacheDriver::new(spec, fingerprint, per_token, slot)),99         })100     }101 102     /// Restores the deepest matching prefix before a job reaches the engine.103     pub fn restore(104         &self,105         req: &Request<'_>,106         clean_timeout: Duration,107         prepare_timeout: Duration,108     ) -> io::Result<()> {109         self.driver.restore(req, clean_timeout, prepare_timeout)110     }111 112     /// Schedules the post-turn slot dump.113     pub fn after_turn(114         self: &Arc<Self>,115         req: &Request<'_>,116         output: &str,117         prefill_ms: u32,118         token_count: u64,119         timeout: Duration,120     ) -> io::Result<()> {121         self.driver122             .after_turn(req, output, prefill_ms, token_count, timeout)123     }124 125     /// Marks the HTTP slot as tainted after a cancelled or failed turn.126     pub fn taint(&self) {127         self.driver.taint();128     }129 130     pub fn cached_tokens(&self) -> u64 {131         self.driver.cached_tokens()132     }133 134     #[cfg(test)]135     pub(crate) fn wait_for_saves(&self) {136         self.driver.wait_for_saves();137     }138 }139 140 impl CacheCodec for BoundCache {141     fn spec(&self) -> inf3r_proto::body::CacheSpec {142         self.driver.spec()143     }144 145     fn fingerprint(&self) -> [u8; 32] {146         self.driver.fingerprint()147     }148 149     fn attach(&self, transport: Arc<dyn CacheTransport>) {150         self.driver.attach(transport);151     }152 153     fn flush(&self, budget: Duration) -> FlushReport {154         self.driver.flush(budget)155     }156 157     fn erase(&self, slot: u32) -> io::Result<()> {158         self.driver.erase(slot)159     }160 }161 162 impl CacheSlot for HttpSlot {163     fn available(&self, timeout: Duration) -> io::Result<bool> {164         match self.api(timeout) {165             Ok(Api::Bridge { .. }) => Ok(true),166             Ok(Api::Missing) | Err(_) => Ok(false),167         }168     }169 170     fn prefix_checkpoint(&self, timeout: Duration) -> io::Result<bool> {171         match self.api(timeout) {172             Ok(Api::Bridge { prefix }) => Ok(prefix),173             Ok(Api::Missing) | Err(_) => Ok(false),174         }175     }176 177     fn restore(&self, _slot: u32, hit: &CacheFile, timeout: Duration) -> io::Result<()> {178         match self.api(timeout)? {179             Api::Bridge { .. } => bridge_restore(&self.base()?, hit, &self.staging, timeout),180             Api::Missing => Err(io::Error::other(181                 "the engine did not advertise the cache bridge",182             )),183         }184     }185 186     fn save(&self, _slot: u32, write: &CacheWrite, timeout: Duration) -> io::Result<()> {187         match self.api(timeout)? {188             Api::Bridge { .. } => {189                 bridge_save(&self.base()?, write, &self.staging, BRIDGE_SAVE, timeout)190             }191             Api::Missing => Err(io::Error::other(192                 "the engine did not advertise the cache bridge",193             )),194         }195     }196 197     fn erase(&self, _slot: u32, timeout: Duration) -> io::Result<()> {198         // Without a bridge there is no engine cache to erase. A process that199         // did advertise one gets exactly one bridge erase.200         match *lock(&self.api) {201             Some(Api::Bridge { .. }) => bridge_call(&self.base()?, "erase", SLOT_BODY, timeout),202             Some(Api::Missing) | None => Ok(()),203         }204     }205 206     fn prepare_prefix(207         &self,208         req: &Request<'_>,209         chain: &Chain<'_>,210         timeout: Duration,211     ) -> io::Result<PrefixOutcome> {212         if !matches!(self.api(timeout)?, Api::Bridge { prefix: true }) {213             return Ok(PrefixOutcome::Unsupported);214         }215         let base = self.base()?;216         let body = prefix_body(req, chain);217         let url = format!("{base}/inf3r/cache/prefix");218         let mut reply = http::post_raw(219             &url,220             "application/json",221             "application/json",222             body.as_bytes(),223             timeout,224         )?;225         if reply.status == 409 {226             return Ok(PrefixOutcome::NotAPrefix);227         }228         if reply.status != 200 {229             return Err(io::Error::other(format!(230                 "the engine replied {} to prefix prepare",231                 reply.status232             )));233         }234         let body = read_capped(&mut reply.reader, BRIDGE_REPLY_LIMIT)?;235         let value = inf3r_json::parse_bytes(&body)236             .map_err(|why| io::Error::other(format!("prefix reply is not JSON: {why}")))?;237         let tokens = value238             .get("tokens")239             .and_then(Value::as_u64)240             .ok_or_else(|| io::Error::other("prefix reply has no tokens"))?;241         let prefill_ms = value242             .get("prefill_ms")243             .and_then(Value::as_u64)244             .and_then(|ms| u32::try_from(ms).ok())245             .ok_or_else(|| io::Error::other("prefix reply has no prefill_ms"))?;246         Ok(PrefixOutcome::Prepared(PrefixReply { tokens, prefill_ms }))247     }248 }249 250 impl HttpSlot {251     fn endpoint(&self) -> Option<String> {252         lock(&self.endpoint).clone().map(|url| base_url(&url))253     }254 255     fn base(&self) -> io::Result<String> {256         self.endpoint()257             .ok_or_else(|| io::Error::other("the engine endpoint is not loaded"))258     }259 260     /// Probes the engine once. A network error is not cached: the next cache261     /// operation retries. A non-200 or malformed answer caches `Missing`, so a262     /// runtime that does not advertise the bridge runs without cache.263     fn api(&self, timeout: Duration) -> io::Result<Api> {264         if let Some(api) = *lock(&self.api) {265             return Ok(api);266         }267         let base = self.base()?;268         let url = format!("{base}/inf3r/cache");269         let mut reply = http::get(&url, "application/json", timeout)?;270         let api = if reply.status == 200 {271             let body = read_capped(&mut reply.reader, BRIDGE_REPLY_LIMIT).ok();272             let parsed = body.and_then(|body| inf3r_json::parse_bytes(&body).ok());273             match parsed {274                 Some(value) if value.get("version").and_then(Value::as_u64) == Some(1) => {275                     Api::Bridge {276                         prefix: value277                             .get("prefix_checkpoint")278                             .and_then(Value::as_bool)279                             .unwrap_or(false),280                     }281                 }282                 _ => Api::Missing,283             }284         } else {285             Api::Missing286         };287         *lock(&self.api) = Some(api);288         Ok(api)289     }290 }291 292 /// The body shared by the bridge `erase` and `restore` operations.293 const SLOT_BODY: &str = r#"{"slot":0}"#;294 295 fn bridge_call(base: &str, operation: &str, body: &str, timeout: Duration) -> io::Result<()> {296     let url = format!("{base}/inf3r/cache/{operation}");297     let reply = http::post_raw(&url, "application/json", "*/*", body.as_bytes(), timeout)?;298     if !(200..300).contains(&reply.status) {299         return Err(io::Error::other(format!(300             "the engine replied {} to {operation}",301             reply.status302         )));303     }304     Ok(())305 }306 307 fn bridge_save(308     base: &str,309     write: &CacheWrite,310     staging: &Path,311     filename: &str,312     timeout: Duration,313 ) -> io::Result<()> {314     let path = staging.join(filename);315     let _ = fs::remove_file(&path);316     let body = format!("{{\"slot\":0,\"filename\":\"{filename}\"}}");317     bridge_call(base, "save", &body, timeout)?;318     let result = copy_out(write, &path).map(|_| ());319     let _ = fs::remove_file(&path);320     result321 }322 323 fn bridge_restore(324     base: &str,325     hit: &CacheFile,326     staging: &Path,327     timeout: Duration,328 ) -> io::Result<()> {329     let path = staging.join(BRIDGE_RESTORE);330     let _ = fs::remove_file(&path);331     copy_in(hit, &path)?;332     let body = format!("{{\"slot\":0,\"filename\":\"{BRIDGE_RESTORE}\"}}");333     let result = bridge_call(base, "restore", &body, timeout);334     let _ = fs::remove_file(&path);335     result336 }337 338 /// Opens one staging path without following a symlink.339 fn open_regular(path: &Path) -> io::Result<File> {340     let fd = rustix::fs::open(341         path,342         rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::CLOEXEC,343         rustix::fs::Mode::empty(),344     )345     .map_err(io_err)?;346     let file = File::from(fd);347     if !file.metadata()?.is_file() {348         return Err(io::Error::other(format!(349             "{} is not a regular file",350             path.display()351         )));352     }353     Ok(file)354 }355 356 /// Creates one staging path without following a symlink.357 fn create_regular(path: &Path) -> io::Result<File> {358     let fd = rustix::fs::open(359         path,360         rustix::fs::OFlags::WRONLY361             | rustix::fs::OFlags::CREATE362             | rustix::fs::OFlags::TRUNC363             | rustix::fs::OFlags::NOFOLLOW364             | rustix::fs::OFlags::CLOEXEC,365         rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,366     )367     .map_err(io_err)?;368     Ok(File::from(fd))369 }370 371 fn io_err(why: rustix::io::Errno) -> io::Error {372     io::Error::from_raw_os_error(why.raw_os_error())373 }374 375 fn copy_in(hit: &CacheFile, path: &Path) -> io::Result<()> {376     let mut target = create_regular(path)?;377     descriptor_copy_in(hit, &mut target)?;378     target.sync_all()?;379     Ok(())380 }381 382 fn copy_out(write: &CacheWrite, path: &Path) -> io::Result<(u64, u32)> {383     let mut source = open_regular(path)?;384     descriptor_copy_out(write, &mut source)385 }386 387 fn read_capped(reader: &mut dyn Read, limit: usize) -> io::Result<Vec<u8>> {388     let mut out = Vec::new();389     let mut limited = reader.take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1));390     limited.read_to_end(&mut out)?;391     if out.len() > limit {392         return Err(io::Error::other("the engine reply is too large"));393     }394     Ok(out)395 }396 397 fn base_url(endpoint: &str) -> String {398     let trimmed = endpoint.trim_end_matches('/');399     let versioned = ["/v1", "chat", "completions"].join("/");400     for suffix in [versioned.as_str(), "/chat/completions", "/v1"] {401         if let Some(base) = trimmed.strip_suffix(suffix) {402             return base.to_string();403         }404     }405     trimmed.to_string()406 }407 408 fn prefix_body(req: &Request<'_>, chain: &Chain<'_>) -> String {409     let (prefix_messages, prefix_tools) = crate::chat_messages(&chain.stable);410     let (full_messages, full_tools) = crate::chat_messages(&chain.all);411     let mut prefix = inf3r_json::Object::new().put("messages", Value::Array(prefix_messages));412     if let Some(tools) = prefix_tools {413         prefix = prefix.put("tools", tools);414     }415     let mut full = inf3r_json::Object::new().put("messages", Value::Array(full_messages));416     if let Some(tools) = full_tools {417         full = full.put("tools", tools);418     }419     let body = inf3r_json::Object::new()420         .put("slot", Value::Int(i64::from(SLOT)))421         .put("params", inf3r_proto::mirror::to_json(req.params))422         .put("prefix", prefix.build())423         .put("full", full.build())424         .build();425     inf3r_json::to_string(&body)426 }427 428 fn fingerprint(429     bundle: &Bundle,430     model: &ModelSpec,431     target: &TargetProfile,432     dir: &Path,433 ) -> io::Result<[u8; 32]> {434     let mut digest = Sha256::new();435     digest.update(b"inf3r-cache-bundle-v3");436     digest.update(bundle.id.as_bytes());437     digest.update(bundle.sha256.as_bytes());438     digest.update(bundle.target.as_bytes());439     digest.update(model.serve.as_bytes());440     digest.update(model.vocab.as_bytes());441     digest.update(model.template.as_deref().unwrap_or("").as_bytes());442     for stop in &model.stops {443         digest.update(stop.as_bytes());444         digest.update(b"\0");445     }446     digest.update(&model.bytes.to_le_bytes());447     digest.update(&model.context.unwrap_or(0).to_le_bytes());448     digest.update(&model.kv_bytes_per_token.unwrap_or(0).to_le_bytes());449     digest.update(target.id.as_bytes());450     digest.update(target.backend.as_bytes());451     for arch in &target.arch {452         digest.update(arch.as_bytes());453         digest.update(b"\0");454     }455     digest.update(&target.devices.to_le_bytes());456     for arg in &bundle.args {457         digest.update(arg.as_bytes());458         digest.update(b"\0");459     }460     if let Some(entry) = &bundle.entry {461         if bundle.engine == EngineKind::Http {462             // An HTTP entry is the sidecar's URL, not a file. Its identity is463             // the URL the operator bound, not bytes on disk.464             digest.update(entry.to_string_lossy().as_bytes());465         } else {466             let path = if entry.is_absolute() {467                 entry.clone()468             } else {469                 dir.join(entry)470             };471             let mut file = File::open(&path)?;472             let mut buffer = [0u8; 1024 * 1024];473             loop {474                 let read = file.read(&mut buffer)?;475                 if read == 0 {476                     break;477                 }478                 digest.update(&buffer[..read]);479             }480         }481     }482     Ok(digest.finish())483 }484 485 fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {486     mutex487         .lock()488         .unwrap_or_else(|poisoned| poisoned.into_inner())489 }490 491 /// Creates the private exchange directory for one HTTP runtime.492 pub fn staging_dir(bundle: &Bundle) -> io::Result<PathBuf> {493     let path = std::env::temp_dir().join(format!(494         "inf3r-cache-{}-{}",495         std::process::id(),496         bundle.id.replace('/', "-")497     ));498     let _ = fs::remove_dir_all(&path);499     fs::create_dir_all(&path)?;500     fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?;501     Ok(path)502 }503 504 #[cfg(test)]505 mod tests {506     use super::*;507     use inf3r_plugin_sdk::cache::{CacheCodec, CacheFile, CacheTransport, CacheWrite, Reserve};508     use inf3r_plugin_sdk::capability::{Part, PartBody};509     use std::collections::BTreeMap;510     use std::io::Write;511     use std::net::{TcpListener, TcpStream};512     use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};513 514     static NEXT: AtomicU64 = AtomicU64::new(0);515 516     struct TempDir(PathBuf);517 518     impl TempDir {519         fn new(name: &str) -> TempDir {520             let path = std::env::temp_dir().join(format!(521                 "inf3r-bind-cache-{name}-{}-{}",522                 std::process::id(),523                 NEXT.fetch_add(1, Ordering::SeqCst)524             ));525             std::fs::create_dir_all(&path).unwrap();526             TempDir(path)527         }528     }529 530     impl Drop for TempDir {531         fn drop(&mut self) {532             let _ = std::fs::remove_dir_all(&self.0);533         }534     }535 536     fn text<'a>(role: &'a str, body: &'a str) -> Part<'a> {537         Part {538             kind: inf3r_proto::body::PartKind::Text,539             mime: "text/plain",540             role: Some(role),541             len: body.len() as u64,542             body: PartBody::Inline(body.as_bytes()),543         }544     }545 546     fn tools<'a>(body: &'a str) -> Part<'a> {547         Part {548             kind: inf3r_proto::body::PartKind::Json,549             mime: "application/json",550             role: Some("tools"),551             len: body.len() as u64,552             body: PartBody::Inline(body.as_bytes()),553         }554     }555 556     fn request<'a>(parts: &'a [Part<'a>], params: &'a inf3r_proto::Value) -> Request<'a> {557         Request {558             request_id: "test",559             model: "mock",560             capability: "chat",561             parts,562             params,563         }564     }565 566     fn fake_lineage(request: &Request<'_>) -> [u8; 32] {567         inf3r_plugin_sdk::cache::lineage_key(request).unwrap()568     }569 570     fn cache_key_param(key: &str) -> inf3r_proto::Value {571         inf3r_proto::Value::map([(572             inf3r_proto::Value::Text("cache_key".into()),573             inf3r_proto::Value::Text(key.into()),574         )])575     }576 577     struct FakeState {578         anchor: Option<[u8; 32]>,579         anchor_path: Option<PathBuf>,580         anchor_bytes: u64,581         anchor_crc: u32,582         write_path: Option<PathBuf>,583         lookups: Vec<Vec<[u8; 32]>>,584         reserves: Vec<Reserve>,585         commits: Vec<(bool, u64, u32, u64, u32)>,586         releases: Vec<(u64, bool)>,587         next_lease: u64,588     }589 590     struct Fake {591         dir: PathBuf,592         state: Mutex<FakeState>,593     }594 595     impl Fake {596         fn new(dir: &Path) -> Fake {597             Fake {598                 dir: dir.to_path_buf(),599                 state: Mutex::new(FakeState {600                     anchor: None,601                     anchor_path: None,602                     anchor_bytes: 0,603                     anchor_crc: 0,604                     write_path: None,605                     lookups: Vec::new(),606                     reserves: Vec::new(),607                     commits: Vec::new(),608                     releases: Vec::new(),609                     next_lease: 1,610                 }),611             }612         }613     }614 615     impl CacheTransport for Fake {616         fn lookup(617             &self,618             keys: &[[u8; 32]],619             _lineage: Option<[u8; 32]>,620             _timeout: Duration,621         ) -> io::Result<Option<CacheFile>> {622             let mut state = lock(&self.state);623             state.lookups.push(keys.to_vec());624             let Some(anchor) = state.anchor else {625                 return Ok(None);626             };627             if !keys.contains(&anchor) {628                 return Ok(None);629             }630             let Some(path) = &state.anchor_path else {631                 return Ok(None);632             };633             let file = File::open(path)?;634             Ok(Some(CacheFile {635                 key: anchor,636                 lease_id: 1,637                 bytes: state.anchor_bytes,638                 crc32c: state.anchor_crc,639                 token_count: 100,640                 tier: "nvme".into(),641                 file: file.into(),642             }))643         }644 645         fn reserve(&self, request: Reserve, _timeout: Duration) -> io::Result<Option<CacheWrite>> {646             let mut state = lock(&self.state);647             let lease_id = state.next_lease;648             state.next_lease += 1;649             let path = self.dir.join(format!("lease-{lease_id}.bin"));650             let file = std::fs::OpenOptions::new()651                 .read(true)652                 .write(true)653                 .create(true)654                 .truncate(true)655                 .open(&path)?;656             state.reserves.push(request.clone());657             state.anchor = Some(request.key);658             state.write_path = Some(path);659             Ok(Some(CacheWrite {660                 lease_id,661                 max_bytes: 1024 * 1024,662                 tier: "nvme".into(),663                 file: file.into(),664             }))665         }666 667         fn release(&self, lease_id: u64, ok: bool, _restore_ms: u32) -> io::Result<()> {668             lock(&self.state).releases.push((lease_id, ok));669             Ok(())670         }671 672         fn commit(673             &self,674             _lease_id: u64,675             ok: bool,676             bytes: u64,677             crc32c: u32,678             token_count: u64,679             save_ms: u32,680         ) -> io::Result<()> {681             let mut state = lock(&self.state);682             state683                 .commits684                 .push((ok, bytes, crc32c, token_count, save_ms));685             if ok && let Some(path) = state.write_path.clone() {686                 state.anchor_path = Some(path);687                 state.anchor_bytes = bytes;688                 state.anchor_crc = crc32c;689             }690             Ok(())691         }692     }693 694     fn read_request(stream: &mut TcpStream) -> Vec<u8> {695         let mut request = Vec::new();696         let mut chunk = [0u8; 4096];697         loop {698             let read = stream.read(&mut chunk).unwrap();699             if read == 0 {700                 return request;701             }702             request.extend_from_slice(&chunk[..read]);703             let Some(head) = request.windows(4).position(|window| window == b"\r\n\r\n") else {704                 continue;705             };706             let head_text = String::from_utf8_lossy(&request[..head]).to_ascii_lowercase();707             let length = head_text708                 .lines()709                 .find_map(|line| line.strip_prefix("content-length:"))710                 .and_then(|value| value.trim().parse::<usize>().ok())711                 .unwrap_or(0);712             if request.len() >= head + 4 + length {713                 return request;714             }715         }716     }717 718     fn reply(stream: &mut TcpStream, status: &str, body: &[u8]) {719         let head = format!(720             "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",721             body.len()722         );723         stream.write_all(head.as_bytes()).unwrap();724         stream.write_all(body).unwrap();725     }726 727     fn request_body(request: &[u8]) -> Vec<u8> {728         let Some(head) = request.windows(4).position(|window| window == b"\r\n\r\n") else {729             return Vec::new();730         };731         request[head + 4..].to_vec()732     }733 734     #[derive(Clone, Copy, PartialEq, Eq)]735     enum Mode {736         BridgeOk,737         PrefixNotPrefix,738         NoBridge,739     }740 741     struct Counts {742         prefix: u32,743         save: u32,744         restore: u32,745         erase: u32,746     }747 748     fn bridge_server(749         staging: PathBuf,750         mode: Mode,751     ) -> (752         String,753         Arc<Mutex<Counts>>,754         Arc<AtomicBool>,755         std::thread::JoinHandle<()>,756     ) {757         let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();758         let port = listener.local_addr().unwrap().port();759         let stop = Arc::new(AtomicBool::new(false));760         let counts = Arc::new(Mutex::new(Counts {761             prefix: 0,762             save: 0,763             restore: 0,764             erase: 0,765         }));766         let thread_stop = Arc::clone(&stop);767         let thread_counts = Arc::clone(&counts);768         let handle = std::thread::spawn(move || {769             listener.set_nonblocking(true).unwrap();770             while !thread_stop.load(Ordering::SeqCst) {771                 let (mut stream, _) = match listener.accept() {772                     Ok(pair) => pair,773                     Err(why) if why.kind() == io::ErrorKind::WouldBlock => {774                         std::thread::sleep(Duration::from_millis(1));775                         continue;776                     }777                     Err(_) => break,778                 };779                 let request = read_request(&mut stream);780                 let line = String::from_utf8_lossy(&request)781                     .lines()782                     .next()783                     .unwrap_or_default()784                     .to_string();785                 let body = request_body(&request);786                 if line.starts_with("GET /inf3r/cache ") {787                     if mode == Mode::NoBridge {788                         reply(&mut stream, "404 Not Found", b"");789                     } else {790                         reply(791                             &mut stream,792                             "200 OK",793                             br#"{"version":1,"prefix_checkpoint":true}"#,794                         );795                     }796                 } else if line.starts_with("POST /inf3r/cache/prefix ") {797                     if mode == Mode::PrefixNotPrefix {798                         lock(&thread_counts).prefix += 1;799                         reply(&mut stream, "409 Conflict", b"");800                         continue;801                     }802                     let value = inf3r_json::parse_bytes(&body).unwrap();803                     let prefix = value.get("prefix").unwrap();804                     let full = value.get("full").unwrap();805                     assert_eq!(806                         prefix807                             .get("messages")808                             .and_then(Value::as_array)809                             .map(|m| m.len()),810                         Some(1)811                     );812                     assert_eq!(813                         full.get("messages")814                             .and_then(Value::as_array)815                             .map(|m| m.len()),816                         Some(2)817                     );818                     assert!(prefix.get("tools").is_some());819                     assert!(full.get("tools").is_some());820                     assert_eq!(821                         value822                             .get("params")823                             .and_then(|params| params.get("cache_key"))824                             .and_then(Value::as_str),825                         Some("conversation-a")826                     );827                     lock(&thread_counts).prefix += 1;828                     reply(&mut stream, "200 OK", br#"{"tokens":100,"prefill_ms":50}"#);829                 } else if line.starts_with("POST /inf3r/cache/save ") {830                     let value = inf3r_json::parse_bytes(&body).unwrap();831                     let name = value.get("filename").and_then(Value::as_str).unwrap();832                     std::fs::write(staging.join(name), b"engine-slot").unwrap();833                     lock(&thread_counts).save += 1;834                     reply(&mut stream, "204 No Content", b"");835                 } else if line.starts_with("POST /inf3r/cache/restore ") {836                     lock(&thread_counts).restore += 1;837                     reply(&mut stream, "204 No Content", b"");838                 } else if line.starts_with("POST /inf3r/cache/erase ") {839                     lock(&thread_counts).erase += 1;840                     reply(&mut stream, "204 No Content", b"");841                 } else {842                     reply(&mut stream, "404 Not Found", b"");843                 }844             }845         });846         (format!("http://127.0.0.1:{port}/v1"), counts, stop, handle)847     }848 849     fn cache_for(staging: &Path, endpoint: &str) -> BoundCache {850         let bundle = Bundle {851             id: "test/1x0".into(),852             model: "test".into(),853             target: "1x0".into(),854             summary: "test".into(),855             engine: EngineKind::Http,856             entry: Some(PathBuf::from(endpoint)),857             args: Vec::new(),858             worker: None,859             binary: PathBuf::from("bin"),860             files: Vec::new(),861             sha256: "0".repeat(64),862         };863         let model = ModelSpec {864             serve: "test".into(),865             alias_of: None,866             files: Vec::new(),867             bytes: 0,868             vocab: "chat.v1".into(),869             context: Some(4096),870             kv_bytes_per_token: Some(1024),871             template: Some("chatml".into()),872             stops: vec!["<|end|>".into()],873             cancel: None,874             stops_owner: None,875             queue: None,876             capabilities: BTreeMap::new(),877         };878         let target = TargetProfile {879             id: "1x0".into(),880             backend: "cuda".into(),881             arch: vec!["x86_64".into()],882             devices: 1,883             vram_mb: vec![8192],884             max_inflight: Some(1),885             start_ms: None,886         };887         BoundCache::new(888             &bundle,889             &model,890             &target,891             staging,892             staging.to_path_buf(),893             Arc::new(Mutex::new(Some(endpoint.to_string()))),894         )895         .unwrap()896     }897 898     #[test]899     fn the_bridge_creates_a_shared_anchor_and_the_next_conversation_restores_it() {900         let temp = TempDir::new("bridge");901         let staging = temp.0.join("staging");902         std::fs::create_dir_all(&staging).unwrap();903         std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o700)).unwrap();904         let (endpoint, counts, stop, server) = bridge_server(staging.clone(), Mode::BridgeOk);905         let cache = Arc::new(cache_for(&staging, &endpoint));906         let fake = Arc::new(Fake::new(&temp.0));907         cache.attach(fake.clone());908 909         let system = text("system", "be brief");910         let user_a = text("user", "alpha");911         let tool = tools(r#"{"tools":[{"type":"function"}]}"#);912         let params_a = cache_key_param("conversation-a");913         let parts_a = [system, user_a, tool];914         let first = request(&parts_a, &params_a);915         cache916             .restore(&first, Duration::from_secs(2), Duration::from_secs(2))917             .unwrap();918         assert_eq!(cache.cached_tokens(), 0);919         {920             let state = lock(&fake.state);921             assert_eq!(state.reserves.len(), 1);922             assert_eq!(923                 state.reserves[0].kind,924                 inf3r_proto::body::CacheEntryKind::Anchor925             );926             assert_eq!(state.reserves[0].supersedes, None);927             assert!(state.reserves[0].lineage.is_some());928             assert_eq!(state.commits.len(), 1);929             assert!(state.commits[0].0);930         }931         assert_eq!(lock(&counts).prefix, 1);932         assert_eq!(lock(&counts).save, 1);933 934         let user_b = text("user", "beta");935         let params_b = cache_key_param("conversation-b");936         let parts_b = [system, user_b, tool];937         let second = request(&parts_b, &params_b);938         cache939             .restore(&second, Duration::from_secs(2), Duration::from_secs(2))940             .unwrap();941         assert_eq!(cache.cached_tokens(), 100);942         assert_eq!(lock(&counts).prefix, 1);943         assert_eq!(lock(&counts).restore, 1);944         {945             let state = lock(&fake.state);946             assert_eq!(state.reserves.len(), 1);947             assert_eq!(state.releases, vec![(1, true)]);948         }949 950         cache951             .after_turn(&second, "answer-b", 10, 120, Duration::from_secs(2))952             .unwrap();953         cache.wait_for_saves();954         let first_tip = {955             let state = lock(&fake.state);956             let tip = state.reserves.last().unwrap();957             assert_eq!(tip.kind, inf3r_proto::body::CacheEntryKind::Tip);958             assert_eq!(tip.supersedes, None);959             assert_eq!(tip.lineage, Some(fake_lineage(&second)));960             tip.key961         };962         cache963             .after_turn(&second, "answer-b2", 10, 120, Duration::from_secs(2))964             .unwrap();965         cache.wait_for_saves();966         {967             let state = lock(&fake.state);968             let tip = state.reserves.last().unwrap();969             assert_eq!(tip.kind, inf3r_proto::body::CacheEntryKind::Tip);970             assert_eq!(tip.supersedes, Some(first_tip));971             assert_eq!(tip.lineage, Some(fake_lineage(&second)));972         }973 974         cache.erase(0).unwrap();975         assert_eq!(lock(&counts).erase, 1);976 977         stop.store(true, Ordering::SeqCst);978         server.join().unwrap();979     }980 981     #[test]982     fn a_prefix_that_is_not_a_prefix_erases_and_never_reserves() {983         let temp = TempDir::new("not-prefix");984         let staging = temp.0.join("staging");985         std::fs::create_dir_all(&staging).unwrap();986         std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o700)).unwrap();987         let (endpoint, counts, stop, server) =988             bridge_server(staging.clone(), Mode::PrefixNotPrefix);989         let cache = Arc::new(cache_for(&staging, &endpoint));990         let fake = Arc::new(Fake::new(&temp.0));991         cache.attach(fake.clone());992 993         let system = text("system", "be brief");994         let user = text("user", "alpha");995         let params = inf3r_proto::Value::Null;996         let parts = [system, user];997         let request = request(&parts, &params);998         cache999             .restore(&request, Duration::from_secs(2), Duration::from_secs(2))1000             .unwrap();1001         assert_eq!(cache.cached_tokens(), 0);1002         assert!(lock(&fake.state).reserves.is_empty());1003         assert_eq!(lock(&counts).prefix, 1);1004         assert_eq!(lock(&counts).erase, 1);1005 1006         stop.store(true, Ordering::SeqCst);1007         server.join().unwrap();1008     }1009 1010     #[test]1011     fn an_engine_without_the_bridge_runs_uncached_and_touches_no_route() {1012         let temp = TempDir::new("no-bridge");1013         let staging = temp.0.join("staging");1014         std::fs::create_dir_all(&staging).unwrap();1015         std::fs::set_permissions(&staging, std::fs::Permissions::from_mode(0o700)).unwrap();1016         let (endpoint, counts, stop, server) = bridge_server(staging.clone(), Mode::NoBridge);1017         let cache = Arc::new(cache_for(&staging, &endpoint));1018         let fake = Arc::new(Fake::new(&temp.0));1019         cache.attach(fake.clone());1020 1021         let system = text("system", "be brief");1022         let user = text("user", "alpha");1023         let params = inf3r_proto::Value::Null;1024         let parts = [system, user];1025         let request = request(&parts, &params);1026         cache1027             .restore(&request, Duration::from_secs(2), Duration::from_secs(2))1028             .unwrap();1029         assert_eq!(cache.cached_tokens(), 0);1030         assert_eq!(lock(&counts).prefix, 0);1031         assert_eq!(lock(&counts).save, 0);1032         assert_eq!(lock(&counts).restore, 0);1033         assert_eq!(lock(&counts).erase, 0);1034 1035         // A runtime without the bridge must not cause a reservation or a save1036         // attempt after the turn. The cache is simply off for this process.1037         cache1038             .after_turn(&request, "answer", 10, 120, Duration::from_secs(2))1039             .unwrap();1040         cache.wait_for_saves();1041         assert!(lock(&fake.state).reserves.is_empty());1042 1043         stop.store(true, Ordering::SeqCst);1044         server.join().unwrap();1045     }1046 1047     #[test]1048     fn the_fingerprint_covers_the_template_and_the_target() {1049         let dir = std::env::temp_dir();1050         let bundle = Bundle {1051             id: "test/1x0".into(),1052             model: "test".into(),1053             target: "1x0".into(),1054             summary: "test".into(),1055             engine: EngineKind::Http,1056             entry: Some(PathBuf::from("http://127.0.0.1:1/v1")),1057             args: Vec::new(),1058             worker: None,1059             binary: PathBuf::from("bin"),1060             files: Vec::new(),1061             sha256: "0".repeat(64),1062         };1063         let model = ModelSpec {1064             serve: "test".into(),1065             alias_of: None,1066             files: Vec::new(),1067             bytes: 0,1068             vocab: "chat.v1".into(),1069             context: Some(4096),1070             kv_bytes_per_token: Some(1024),1071             template: Some("a".into()),1072             stops: vec!["stop".into()],1073             cancel: None,1074             stops_owner: None,1075             queue: None,1076             capabilities: BTreeMap::new(),1077         };1078         let target = TargetProfile {1079             id: "1x0".into(),1080             backend: "cuda".into(),1081             arch: vec!["x86_64".into()],1082             devices: 1,1083             vram_mb: vec![8192],1084             max_inflight: Some(1),1085             start_ms: None,1086         };1087         let a = fingerprint(&bundle, &model, &target, &dir).unwrap();1088         let mut changed = model.clone();1089         changed.template = Some("b".into());1090         let b = fingerprint(&bundle, &changed, &target, &dir).unwrap();1091         assert_ne!(a, b);1092         let mut target_changed = target.clone();1093         target_changed.backend = "rocm".into();1094         let c = fingerprint(&bundle, &model, &target_changed, &dir).unwrap();1095         assert_ne!(a, c);1096     }1097 }