crates/edge/sdk/src/cache/driver.rs 22.6 KiB 655 lines Raw
1 //! The engine-neutral cache driver.2 //!3 //! A bundle implements [`CacheSlot`] for its local engine operations and gets4 //! the whole Wire 2 policy for free: canonical ordering, longest-first lookup,5 //! lineage tips, shared anchors, descriptor verification, save reservation,6 //! and bounded flush. The driver never knows an HTTP route, a CLI flag, or a7 //! staging directory.8 9 use std::io;10 use std::sync::atomic::{AtomicBool, Ordering};11 use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};12 use std::time::{Duration, Instant};13 14 use inf3r_proto::body;15 16 use super::chain::{AnchorSet, Chain, TipTable, key_after, lineage_key};17 use super::{CacheCodec, CacheFile, CacheTransport, CacheWrite, FlushReport, Reserve, descriptor};18 use crate::capability::Request;19 20 /// The result of asking an engine to materialize a prompt-only prefix.21 #[derive(Clone, Copy, PartialEq, Eq, Debug)]22 pub enum PrefixOutcome {23     /// The engine prefilled the prefix and the slot is ready to extend.24     Prepared(PrefixReply),25     /// The engine refused because the supplied prefix is not a prefix of the26     /// full prompt. The slot must be erased before the job continues.27     NotAPrefix,28     /// The engine does not implement prefix checkpointing.29     Unsupported,30 }31 32 /// What a prefix prepare actually did.33 #[derive(Clone, Copy, PartialEq, Eq, Debug)]34 pub struct PrefixReply {35     /// Tokens that the engine prefilled.36     pub tokens: u64,37     /// Time the engine spent prefilling, in milliseconds.38     pub prefill_ms: u32,39 }40 41 /// The engine-specific half of the cache.42 ///43 /// The direct FFI bundle implements this over its engine context; the HTTP44 /// compatibility binder implements it over `CacheTransport` plus its private45 /// sidecar. Neither implementation chooses a key, a tier, a TTL, or an entry46 /// quota.47 pub trait CacheSlot: Send + Sync {48     /// Whether this engine can use the cache at all. The HTTP binder returns49     /// `false` when the runtime did not advertise the bridge.50     fn available(&self, _timeout: Duration) -> io::Result<bool> {51         Ok(true)52     }53 54     /// Whether this engine can materialize a prompt-only prefix. The driver55     /// calls [`CacheSlot::prepare_prefix`] only when this is true.56     fn prefix_checkpoint(&self, _timeout: Duration) -> io::Result<bool> {57         Ok(false)58     }59 60     /// Restores one verified descriptor into the engine's local slot.61     fn restore(&self, slot: u32, file: &CacheFile, timeout: Duration) -> io::Result<()>;62 63     /// Writes one engine slot into a granted descriptor.64     fn save(&self, slot: u32, file: &CacheWrite, timeout: Duration) -> io::Result<()>;65 66     /// Whether this engine can write a prompt-boundary checkpoint while the67     /// job still owns the context. The default is `false`; only an engine that68     /// can serialize its state in place implements it.69     fn prompt_checkpoint(&self, _timeout: Duration) -> io::Result<bool> {70         Ok(false)71     }72 73     /// Writes the prompt-boundary state captured by [`CacheSlot::save`]'s74     /// sibling capture step. The driver calls this while the job holds the75     /// engine, so an implementation must not take its own job lock.76     fn save_prompt(&self, _slot: u32, _file: &CacheWrite, _timeout: Duration) -> io::Result<()> {77         Err(io::Error::other("the engine has no prompt checkpoint"))78     }79 80     /// Erases one local slot. This is correctness even when the cache is off.81     fn erase(&self, slot: u32, timeout: Duration) -> io::Result<()>;82 83     /// Optionally prefills the stable prefix without saving it.84     fn prepare_prefix(85         &self,86         _req: &Request<'_>,87         _chain: &Chain<'_>,88         _timeout: Duration,89     ) -> io::Result<PrefixOutcome> {90         Ok(PrefixOutcome::Unsupported)91     }92 }93 94 #[derive(Default)]95 struct State {96     keys: Vec<[u8; 32]>,97     anchor: Option<[u8; 32]>,98     tips: TipTable,99 }100 101 /// The generic cache codec. One per plugin process.102 pub struct CacheDriver<S> {103     spec: body::CacheSpec,104     fingerprint: [u8; 32],105     kv_bytes_per_token: u64,106     slot: S,107     transport: OnceLock<Arc<dyn CacheTransport>>,108     state: Mutex<State>,109     anchors: Mutex<AnchorSet>,110     /// One engine slot is one writer. A background save and the next restore111     /// must not act on it at the same time.112     slot_io: Mutex<()>,113     cached_tokens: Mutex<u64>,114     enabled: AtomicBool,115     tainted: AtomicBool,116     pending_saves: Mutex<u32>,117     save_done: Condvar,118 }119 120 enum AnchorOutcome {121     Kept,122     Cold,123 }124 125 impl<S: CacheSlot + 'static> CacheDriver<S> {126     /// Builds a driver around one local engine.127     ///128     /// `fingerprint` is the bundle half of the composite identity. The core129     /// combines it with the model and runtime facts it already owns.130     pub fn new(131         spec: body::CacheSpec,132         fingerprint: [u8; 32],133         kv_bytes_per_token: u64,134         slot: S,135     ) -> CacheDriver<S> {136         CacheDriver {137             spec,138             fingerprint,139             kv_bytes_per_token: kv_bytes_per_token.max(1),140             slot,141             transport: OnceLock::new(),142             state: Mutex::new(State::default()),143             anchors: Mutex::new(AnchorSet::default()),144             slot_io: Mutex::new(()),145             cached_tokens: Mutex::new(0),146             enabled: AtomicBool::new(false),147             tainted: AtomicBool::new(false),148             pending_saves: Mutex::new(0),149             save_done: Condvar::new(),150         }151     }152 153     /// Restores the deepest matching prefix before a job reaches the engine.154     ///155     /// Every non-hit path erases the slot. If the cache or the engine cannot156     /// complete that erase, the job must not reuse a stale slot; the caller157     /// sees an error rather than a wrong answer.158     ///159     /// `clean_timeout` bounds lookup, restore, reserve, and erase.160     /// `prepare_timeout` bounds the optional prefix checkpoint; it may be161     /// larger than `clean_timeout` because it does real prefill.162     pub fn restore(163         &self,164         req: &Request<'_>,165         clean_timeout: Duration,166         prepare_timeout: Duration,167     ) -> io::Result<()> {168         *lock(&self.cached_tokens) = 0;169         self.wait_for_saves();170         let _slot = lock(&self.slot_io);171         let chain = match Chain::new(req) {172             Ok(chain) => chain,173             Err(why) => {174                 self.cold(&why, clean_timeout)?;175                 return Err(why);176             }177         };178         {179             let mut state = lock(&self.state);180             state.keys = chain.keys.clone();181             state.anchor = chain.anchor;182         }183         let Some(transport) = self.transport.get().cloned() else {184             self.enabled.store(false, Ordering::SeqCst);185             self.slot.erase(0, clean_timeout)?;186             self.clear_anchor();187             return Ok(());188         };189         if self.tainted.swap(false, Ordering::SeqCst) {190             // A cancelled or failed turn leaves bytes that are not a prefix of191             // anything. Erase before the lookup, even if a hit exists.192             self.slot.erase(0, clean_timeout)?;193         }194         if chain.keys.is_empty() {195             self.enabled.store(false, Ordering::SeqCst);196             self.slot.erase(0, clean_timeout)?;197             self.clear_anchor();198             return Ok(());199         }200         let available = match self.slot.available(clean_timeout) {201             Ok(available) => available,202             Err(why) => {203                 self.enabled.store(false, Ordering::SeqCst);204                 return self.cold(&why, clean_timeout);205             }206         };207         self.enabled.store(available, Ordering::SeqCst);208         if !available {209             self.slot.erase(0, clean_timeout)?;210             self.clear_anchor();211             return Ok(());212         }213         let lookup = chain.lookup_keys();214         let mut hit = match transport.lookup(&lookup, Some(chain.lineage), clean_timeout) {215             Ok(hit) => hit,216             Err(why) => {217                 return self.cold(&why, clean_timeout);218             }219         };220         if hit.is_none()221             && let Some(anchor) = chain.anchor222             && !lookup.contains(&anchor)223         {224             hit = match transport.lookup(&[anchor], Some(chain.lineage), clean_timeout) {225                 Ok(hit) => hit,226                 Err(why) => {227                     return self.cold(&why, clean_timeout);228                 }229             };230         }231         let Some(hit) = hit else {232             let can_prefix = match self.slot.prefix_checkpoint(clean_timeout) {233                 Ok(can) => can,234                 Err(why) => {235                     eprintln!("cache prefix probe skipped: {why}");236                     false237                 }238             };239             if let Some(anchor) = chain.anchor240                 && can_prefix241                 && lock(&self.anchors).claim(anchor)242             {243                 match self.prepare_anchor(244                     req,245                     &chain,246                     anchor,247                     transport.as_ref(),248                     prepare_timeout,249                     clean_timeout,250                 ) {251                     Ok(AnchorOutcome::Kept) => {252                         lock(&self.state).anchor = Some(anchor);253                         return Ok(());254                     }255                     Ok(AnchorOutcome::Cold) => {256                         self.clear_anchor();257                         return Ok(());258                     }259                     Err(why) => {260                         let _ = self.slot.erase(0, clean_timeout);261                         return Err(why);262                     }263                 }264             }265             self.slot.erase(0, clean_timeout)?;266             self.clear_anchor();267             return Ok(());268         };269         let started = Instant::now();270         let result =271             descriptor::verify_file(&hit).and_then(|()| self.slot.restore(0, &hit, clean_timeout));272         let ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);273         match result {274             Ok(()) => {275                 transport.release(hit.lease_id, true, ms)?;276                 *lock(&self.cached_tokens) = hit.token_count;277                 let mut state = lock(&self.state);278                 state.keys = chain.keys;279                 state.anchor = chain.anchor;280                 // A restored entry is a reader, not a new writer. The tip281                 // table tracks saves made by this process; claiming a hit as282                 // the next write's predecessor would retire the very prompt283                 // entry that made the hit possible.284                 Ok(())285             }286             Err(why) => {287                 let _ = transport.release(hit.lease_id, false, ms);288                 self.cold(&why, clean_timeout)289             }290         }291     }292 293     fn prepare_anchor(294         &self,295         req: &Request<'_>,296         chain: &Chain<'_>,297         anchor: [u8; 32],298         transport: &dyn CacheTransport,299         prepare_timeout: Duration,300         clean_timeout: Duration,301     ) -> io::Result<AnchorOutcome> {302         let reply = match self.slot.prepare_prefix(req, chain, prepare_timeout) {303             Ok(PrefixOutcome::Prepared(reply)) => reply,304             Ok(PrefixOutcome::NotAPrefix | PrefixOutcome::Unsupported) => {305                 self.slot.erase(0, clean_timeout)?;306                 return Ok(AnchorOutcome::Cold);307             }308             Err(why) => {309                 self.slot.erase(0, clean_timeout)?;310                 eprintln!("cache anchor skipped: {why}");311                 return Ok(AnchorOutcome::Cold);312             }313         };314         if reply.tokens == 0 || reply.prefill_ms == 0 {315             self.slot.erase(0, clean_timeout)?;316             return Ok(AnchorOutcome::Cold);317         }318         let est_bytes = self.estimate(reply.tokens);319         let request = Reserve {320             key: anchor,321             lineage: Some(chain.lineage),322             supersedes: None,323             kind: body::CacheEntryKind::Anchor,324             est_bytes,325             prefill_ms: reply.prefill_ms,326             token_count: reply.tokens,327             pin: false,328         };329         let write = match transport.reserve(request, clean_timeout) {330             Ok(Some(write)) => write,331             Ok(None) => {332                 // A clean refusal: the slot still holds the prefix, and the333                 // job may use it even though no entry exists.334                 return Ok(AnchorOutcome::Kept);335             }336             Err(why) => {337                 self.slot.erase(0, clean_timeout)?;338                 eprintln!("cache anchor skipped: {why}");339                 return Ok(AnchorOutcome::Cold);340             }341         };342         let started = Instant::now();343         let saved = self344             .slot345             .save(0, &write, prepare_timeout)346             .and_then(|()| descriptor::measure_write(&write));347         let save_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);348         match saved {349             Ok((bytes, crc)) => {350                 if let Err(why) =351                     transport.commit(write.lease_id, true, bytes, crc, reply.tokens, save_ms)352                 {353                     let _ = transport.commit(write.lease_id, false, 0, 0, 0, save_ms);354                     eprintln!("cache anchor not committed: {why}");355                 }356                 Ok(AnchorOutcome::Kept)357             }358             Err(why) => {359                 let _ = transport.commit(write.lease_id, false, 0, 0, 0, save_ms);360                 self.slot.erase(0, clean_timeout)?;361                 eprintln!("cache anchor skipped: {why}");362                 Ok(AnchorOutcome::Cold)363             }364         }365     }366 367     /// Saves a prompt-boundary checkpoint while the job still owns the368     /// context, so the entry contains exactly the prompt and no generated369     /// tokens. The caller captures the state in the slot first; the descriptor370     /// write happens here, before generation.371     ///372     /// A failure is a cache miss for the next job, never a job failure. The373     /// post-turn tip is still saved separately.374     pub fn after_prefill(375         &self,376         req: &Request<'_>,377         prefill_ms: u32,378         token_count: u64,379         timeout: Duration,380     ) -> io::Result<()> {381         if !self.enabled.load(Ordering::SeqCst) || token_count == 0 {382             return Ok(());383         }384         let Some(transport) = self.transport.get().cloned() else {385             return Ok(());386         };387         if !self.slot.prompt_checkpoint(timeout).unwrap_or(false) {388             return Ok(());389         }390         let keys = {391             let state = lock(&self.state);392             state.keys.clone()393         };394         let keys = if keys.is_empty() {395             Chain::new(req)?.keys396         } else {397             keys398         };399         let Some(key) = keys.last().copied() else {400             return Ok(());401         };402         if Some(key) == lock(&self.state).anchor {403             return Ok(());404         }405         let lineage = lineage_key(req)?;406         let request = Reserve {407             key,408             lineage: Some(lineage),409             supersedes: None,410             kind: body::CacheEntryKind::Tip,411             est_bytes: self.estimate(token_count),412             prefill_ms,413             token_count,414             pin: false,415         };416         let write = match transport.reserve(request, timeout) {417             Ok(Some(write)) => write,418             Ok(None) => return Ok(()),419             Err(why) => {420                 eprintln!("cache prompt checkpoint skipped: {why}");421                 return Ok(());422             }423         };424         let started = Instant::now();425         let saved = self426             .slot427             .save_prompt(0, &write, timeout)428             .and_then(|()| descriptor::measure_write(&write));429         let save_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);430         match saved {431             Ok((bytes, crc)) => {432                 if let Err(why) =433                     transport.commit(write.lease_id, true, bytes, crc, token_count, save_ms)434                 {435                     let _ = transport.commit(write.lease_id, false, 0, 0, 0, save_ms);436                     eprintln!("cache prompt checkpoint not committed: {why}");437                 }438             }439             Err(why) => {440                 let _ = transport.commit(write.lease_id, false, 0, 0, 0, save_ms);441                 eprintln!("cache prompt checkpoint skipped: {why}");442             }443         }444         Ok(())445     }446 447     /// Schedules the post-turn slot dump.448     ///449     /// The dump runs on a worker after the done frame. The next restore waits450     /// for it, so the one engine slot is never used by two writers at once.451     pub fn after_turn(452         self: &Arc<Self>,453         req: &Request<'_>,454         output: &str,455         prefill_ms: u32,456         token_count: u64,457         timeout: Duration,458     ) -> io::Result<()> {459         if !self.enabled.load(Ordering::SeqCst) {460             return Ok(());461         }462         let Some(transport) = self.transport.get().cloned() else {463             return Ok(());464         };465         let keys = {466             let state = lock(&self.state);467             state.keys.clone()468         };469         let keys = if keys.is_empty() {470             Chain::new(req)?.keys471         } else {472             keys473         };474         if keys.is_empty() {475             return Ok(());476         }477         let after = key_after(keys.last().copied().unwrap_or([0; 32]), output);478         let lineage = lineage_key(req)?;479         let (supersedes, kind) = {480             let mut state = lock(&self.state);481             // Claim the tip at schedule time: the next turn must supersede482             // this key even if the worker has not committed it yet.483             let previous = state.tips.note(lineage, after);484             let kind = if previous.is_none() && state.anchor.is_none() {485                 body::CacheEntryKind::Anchor486             } else {487                 body::CacheEntryKind::Tip488             };489             (previous, kind)490         };491         *lock(&self.pending_saves) += 1;492         let this = Arc::clone(self);493         let timeout = timeout.max(Duration::from_millis(1));494         std::thread::spawn(move || {495             let _slot = lock(&this.slot_io);496             let result = this.save_one(497                 transport,498                 after,499                 lineage,500                 supersedes,501                 kind,502                 prefill_ms,503                 token_count,504                 timeout,505             );506             if result.is_err() {507                 lock(&this.state).tips.rollback(lineage, after, supersedes);508             }509             let mut pending = lock(&this.pending_saves);510             *pending = pending.saturating_sub(1);511             this.save_done.notify_all();512         });513         Ok(())514     }515 516     #[allow(clippy::too_many_arguments)]517     fn save_one(518         &self,519         transport: Arc<dyn CacheTransport>,520         after: [u8; 32],521         lineage: [u8; 32],522         supersedes: Option<[u8; 32]>,523         kind: body::CacheEntryKind,524         prefill_ms: u32,525         token_count: u64,526         timeout: Duration,527     ) -> io::Result<()> {528         let est_bytes = self.estimate(token_count);529         let request = Reserve {530             key: after,531             lineage: Some(lineage),532             supersedes,533             kind,534             est_bytes,535             prefill_ms,536             token_count,537             pin: false,538         };539         let Some(write) = transport.reserve(request, timeout)? else {540             return Err(io::Error::other("the core refused the reservation"));541         };542         let started = Instant::now();543         let saved = self544             .slot545             .save(0, &write, timeout)546             .and_then(|()| descriptor::measure_write(&write));547         let ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);548         match saved {549             Ok((bytes, crc)) => {550                 transport.commit(write.lease_id, true, bytes, crc, token_count, ms)?;551                 Ok(())552             }553             Err(why) => {554                 let _ = transport.commit(write.lease_id, false, 0, 0, 0, ms);555                 Err(why)556             }557         }558     }559 560     /// Marks the local slot as no longer a prefix of any request.561     ///562     /// A cancelled or failed turn calls this. The next restore erases before563     /// it looks up a hit, so stale bytes never become a wrong answer.564     pub fn taint(&self) {565         self.tainted.store(true, Ordering::SeqCst);566     }567 568     /// The token count restored by the last job, or zero after a cold start.569     pub fn cached_tokens(&self) -> u64 {570         *lock(&self.cached_tokens)571     }572 573     /// Waits for every background save that was scheduled before this call.574     pub fn wait_for_saves(&self) {575         let mut pending = lock(&self.pending_saves);576         while *pending > 0 {577             pending = self578                 .save_done579                 .wait(pending)580                 .unwrap_or_else(|poisoned| poisoned.into_inner());581         }582     }583 584     fn estimate(&self, token_count: u64) -> u64 {585         if token_count == 0 {586             self.spec.max_entry_bytes587         } else {588             token_count589                 .saturating_mul(self.kv_bytes_per_token)590                 .clamp(1, self.spec.max_entry_bytes)591         }592     }593 594     fn clear_anchor(&self) {595         lock(&self.state).anchor = None;596     }597 598     fn cold(&self, why: &dyn std::fmt::Display, timeout: Duration) -> io::Result<()> {599         match self.slot.erase(0, timeout) {600             Ok(()) => {601                 self.clear_anchor();602                 eprintln!("cache restore skipped: {why}");603                 Ok(())604             }605             Err(erase) => Err(io::Error::other(format!(606                 "the cache entry failed ({why}) and the slot could not be erased: {erase}"607             ))),608         }609     }610 }611 612 impl<S: CacheSlot + 'static> CacheCodec for CacheDriver<S> {613     fn spec(&self) -> body::CacheSpec {614         self.spec.clone()615     }616 617     fn fingerprint(&self) -> [u8; 32] {618         self.fingerprint619     }620 621     fn attach(&self, transport: Arc<dyn CacheTransport>) {622         let _ = self.transport.set(transport);623     }624 625     fn flush(&self, budget: Duration) -> FlushReport {626         let deadline = Instant::now() + budget;627         let mut pending = lock(&self.pending_saves);628         while *pending > 0 {629             let left = deadline.saturating_duration_since(Instant::now());630             if left.is_zero() {631                 break;632             }633             let (next, _) = self634                 .save_done635                 .wait_timeout(pending, left)636                 .unwrap_or_else(|poisoned| poisoned.into_inner());637             pending = next;638         }639         FlushReport {640             saved: 0,641             skipped: 0,642             dirty_remaining: *pending,643         }644     }645 646     fn erase(&self, slot: u32) -> io::Result<()> {647         self.slot.erase(slot, Duration::from_secs(2))648     }649 }650 651 fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {652     mutex653         .lock()654         .unwrap_or_else(|poisoned| poisoned.into_inner())655 }