Skip to main content

weirdnet_semcache/
lib.rs

1//! Answer cache for Weirdnet inference nodes.
2//!
3//! An inference node asks an [`AnswerCache`] before it routes a prompt and offers it the finished
4//! answer afterwards. The cache decides what it keeps and when a stored answer may stand in.
5//!
6//! - [`AnswerCache`]: the seam (`get`, `put`) over `weirdnet-agent` infer/2 [`Request`]s.
7//! - [`AnswerStore`]: where cached answers live, as opaque bytes under 32-byte keys, so a store
8//!   can be in memory, on disk or shared. [`MemoryStore`] is bounded and least-recently-used.
9//! - [`ExactCache`]: answers only requests identical to a stored one that are deterministic
10//!   (temperature 0, no tools, inline messages) for the same model, and keeps only answers that
11//!   finished (`stop` or `length`).
12//! - [`NoCache`]: caches nothing.
13//! - [`may_read`] / [`may_store`]: the request's own [`CacheMode`](weirdnet_agent::remote::infer::v2::CacheMode) (`weirdnet-agent` 0.5.1):
14//!   `bypass` neither reads nor stores, `refresh` skips the read and stores the fresh answer.
15//!   [`ExactCache`] honours both.
16//! - Revisions: [`AnswerCache::get_rev`] / [`AnswerCache::put_rev`] and [`exact_key_rev`] key an
17//!   answer on the model's weights as well as its id, so a fine-tuned model under the same id
18//!   doesn't replay answers from the old weights.
19//!
20//! - [`SemanticCache`]: similarity lookup by embedding. The caller embeds the prompt; the
21//!   nearest stored embedding in the same scope (see [`scope_key`]) stands in when its cosine
22//!   similarity reaches the threshold. Bounded and least-recently-used, with an optional TTL and
23//!   a CBOR [`snapshot`](SemanticCache::snapshot) / [`restore`](SemanticCache::restore).
24//!
25//! Pool mode, several inference nodes sharing one cache (since 0.2.3):
26//!
27//! - [`ShardRing`] / [`ShardPlan`]: rendezvous hashing of a scope (or an exact [`Key`]) to a
28//!   home node and one replica; joins and leaves move only the shards they must.
29//! - [`SharedCacheReq`] / [`SharedCacheResp`]: the CBOR lookup / insert / remove protocol
30//!   ([`PROTOCOL`]), and [`SharedCacheHost`], which answers it from a node's own cache.
31//! - With the `pool` feature, `pool::PooledSemanticCache` (L1, the home, the replica on
32//!   failure, bounded timeouts, background replica writes, a miss whenever peers fail) over a
33//!   `pool::CacheTransport`, and `pool::serve` / `pool::DialerTransport` over `weirdnet-agent`
34//!   channels.
35#![forbid(unsafe_code)]
36#![cfg_attr(docsrs, feature(doc_cfg))]
37
38mod semantic;
39mod shard;
40mod shared;
41
42#[cfg(feature = "pool")]
43#[cfg_attr(docsrs, doc(cfg(feature = "pool")))]
44pub mod pool;
45
46pub use semantic::{DEFAULT_THRESHOLD, Lookup, SemanticCache, SemanticConfig, SemanticError, SemanticStats, cosine_similarity, normalize, scope_key};
47pub use shard::{ShardPlan, ShardRing};
48pub use shared::{HostLimits, PROTOCOL, SharedCacheHost, SharedCacheReq, SharedCacheResp, WIRE_VERSION};
49
50use std::collections::HashMap;
51use std::sync::Mutex;
52
53use serde::{Deserialize, Serialize};
54use sha2::{Digest, Sha256};
55use weirdnet_agent::ToolCall;
56use weirdnet_agent::remote::infer::v2::{Input, Request, Usage};
57use weirdnet_agent::remote::pool::Answer;
58use weirdnet_agent::remote::{from_cbor, to_cbor};
59
60/// A stored answer, replayed instead of running the model.
61#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
62#[non_exhaustive]
63pub struct CachedAnswer {
64    /// The model that produced it.
65    pub model: String,
66    pub text: String,
67    #[serde(default)]
68    pub reasoning: String,
69    #[serde(default)]
70    pub tool_calls: Vec<ToolCall>,
71    pub finish_reason: Option<String>,
72    pub usage: Option<Usage>,
73}
74
75impl CachedAnswer {
76    pub fn new(model: impl Into<String>, text: impl Into<String>, finish_reason: impl Into<String>) -> Self {
77        Self { model: model.into(), text: text.into(), finish_reason: Some(finish_reason.into()), ..Default::default() }
78    }
79
80    /// Finished normally (`stop` or `length`), so it is safe to replay.
81    pub fn complete(&self) -> bool {
82        matches!(self.finish_reason.as_deref(), Some("stop" | "length"))
83    }
84}
85
86impl From<&Answer> for CachedAnswer {
87    fn from(a: &Answer) -> Self {
88        Self {
89            model: a.model.clone(),
90            text: a.text.clone(),
91            reasoning: a.reasoning.clone(),
92            tool_calls: a.tool_calls.clone(),
93            finish_reason: a.finish_reason.clone(),
94            usage: a.usage,
95        }
96    }
97}
98
99/// What an inference node asks before and after routing a prompt.
100pub trait AnswerCache: Send + Sync {
101    /// A stored answer for `request` on `model`.
102    fn get(&self, model: &str, request: &Request) -> Option<CachedAnswer>;
103    /// Offers a finished answer; the cache decides whether to keep it.
104    fn put(&self, model: &str, request: &Request, answer: &CachedAnswer);
105
106    /// A stored answer for `request` on `model` at weights `revision` (a Hugging Face commit, a
107    /// file hash, a fine-tune id). With no revision this is [`get`](Self::get). The default
108    /// misses when a revision is given, so a cache that doesn't key on revisions never replays
109    /// answers from other weights.
110    fn get_rev(&self, model: &str, revision: Option<&str>, request: &Request) -> Option<CachedAnswer> {
111        match revision {
112            None => self.get(model, request),
113            Some(_) => None,
114        }
115    }
116
117    /// Offers a finished answer from `model` at `revision`. The default keeps it only when no
118    /// revision is given (see [`get_rev`](Self::get_rev)).
119    fn put_rev(&self, model: &str, revision: Option<&str>, request: &Request, answer: &CachedAnswer) {
120        if revision.is_none() {
121            self.put(model, request, answer);
122        }
123    }
124}
125
126/// The request lets a cache answer it ([`CacheMode::Use`](weirdnet_agent::remote::infer::v2::CacheMode::Use)).
127pub fn may_read(request: &Request) -> bool {
128    request.cache.may_read()
129}
130
131/// The request lets a cache keep its answer ([`CacheMode::Use`](weirdnet_agent::remote::infer::v2::CacheMode::Use) or [`CacheMode::Refresh`](weirdnet_agent::remote::infer::v2::CacheMode::Refresh)).
132pub fn may_store(request: &Request) -> bool {
133    request.cache.may_store()
134}
135
136/// Caches nothing.
137#[derive(Debug, Clone, Copy, Default)]
138pub struct NoCache;
139
140impl AnswerCache for NoCache {
141    fn get(&self, _: &str, _: &Request) -> Option<CachedAnswer> {
142        None
143    }
144
145    fn put(&self, _: &str, _: &Request, _: &CachedAnswer) {}
146}
147
148/// A cache key: SHA-256 over the model and the parts of the request that shape the answer.
149pub type Key = [u8; 32];
150
151/// Where cached answers live. Values are opaque bytes; a store may drop entries at any time.
152pub trait AnswerStore: Send + Sync {
153    fn get(&self, key: &Key) -> Option<Vec<u8>>;
154    fn put(&self, key: &Key, value: Vec<u8>);
155    fn remove(&self, key: &Key);
156    fn len(&self) -> usize;
157    fn is_empty(&self) -> bool {
158        self.len() == 0
159    }
160}
161
162/// A use counter plus entries, each with its last use.
163type Entries = (u64, HashMap<Key, (u64, Vec<u8>)>);
164
165/// In-memory store holding at most `max_entries`, evicting the least recently used.
166pub struct MemoryStore {
167    max_entries: usize,
168    inner: Mutex<Entries>,
169}
170
171impl MemoryStore {
172    pub fn new(max_entries: usize) -> Self {
173        Self { max_entries: max_entries.max(1), inner: Mutex::new((0, HashMap::new())) }
174    }
175
176    fn lock(&self) -> std::sync::MutexGuard<'_, Entries> {
177        self.inner.lock().unwrap_or_else(|e| e.into_inner())
178    }
179}
180
181impl AnswerStore for MemoryStore {
182    fn get(&self, key: &Key) -> Option<Vec<u8>> {
183        let mut g = self.lock();
184        g.0 += 1;
185        let tick = g.0;
186        let hit = g.1.get_mut(key)?;
187        hit.0 = tick;
188        Some(hit.1.clone())
189    }
190
191    fn put(&self, key: &Key, value: Vec<u8>) {
192        let mut g = self.lock();
193        g.0 += 1;
194        let tick = g.0;
195        if g.1.len() >= self.max_entries
196            && !g.1.contains_key(key)
197            && let Some(oldest) = g.1.iter().min_by_key(|(_, v)| v.0).map(|(k, _)| *k)
198        {
199            g.1.remove(&oldest);
200        }
201        g.1.insert(*key, (tick, value));
202    }
203
204    fn remove(&self, key: &Key) {
205        self.lock().1.remove(key);
206    }
207
208    fn len(&self) -> usize {
209        self.lock().1.len()
210    }
211}
212
213/// Requests an exact cache may answer: temperature 0, no tools, inline messages.
214pub fn deterministic(request: &Request) -> bool {
215    request.sampling.temperature == Some(0.0) && request.tools.is_empty() && matches!(request.input, Input::Messages(_))
216}
217
218/// The key for `request` on `model`, or `None` when it is not [`deterministic`]. The same as
219/// [`exact_key_rev`] with no revision.
220pub fn exact_key(model: &str, request: &Request) -> Option<Key> {
221    exact_key_rev(model, None, request)
222}
223
224/// The key for `request` on `model` at weights `revision`, or `None` when it is not
225/// [`deterministic`]. With no revision the key is the 0.2.0 one (`v: 1`), so stored answers
226/// still hit; with one it is a `v: 2` key that includes it. The request's [`CacheMode`](weirdnet_agent::remote::infer::v2::CacheMode) is not
227/// part of the key, so `refresh` overwrites the entry `use` reads.
228pub fn exact_key_rev(model: &str, revision: Option<&str>, request: &Request) -> Option<Key> {
229    if !deterministic(request) {
230        return None;
231    }
232    #[derive(Serialize)]
233    struct Parts<'a> {
234        v: u8,
235        model: &'a str,
236        #[serde(skip_serializing_if = "Option::is_none")]
237        revision: Option<&'a str>,
238        input: &'a Input,
239        sampling: &'a weirdnet_agent::remote::infer::v2::Sampling,
240        seed: Option<u64>,
241        response_format: &'a Option<weirdnet_agent::remote::infer::v2::ResponseFormat>,
242        raw: bool,
243    }
244    let parts = Parts {
245        v: if revision.is_some() { 2 } else { 1 },
246        model,
247        revision,
248        input: &request.input,
249        sampling: &request.sampling,
250        seed: request.seed,
251        response_format: &request.response_format,
252        raw: request.raw,
253    };
254    let bytes = to_cbor(&parts).ok()?;
255    Some(Sha256::digest(&bytes).into())
256}
257
258/// Exact-match cache for deterministic requests over an [`AnswerStore`].
259pub struct ExactCache<S: AnswerStore = MemoryStore> {
260    store: S,
261}
262
263impl ExactCache<MemoryStore> {
264    /// In memory, at most `max_entries` answers.
265    pub fn new(max_entries: usize) -> Self {
266        Self { store: MemoryStore::new(max_entries) }
267    }
268}
269
270impl<S: AnswerStore> ExactCache<S> {
271    pub fn with_store(store: S) -> Self {
272        Self { store }
273    }
274
275    pub fn store(&self) -> &S {
276        &self.store
277    }
278
279    pub fn len(&self) -> usize {
280        self.store.len()
281    }
282
283    pub fn is_empty(&self) -> bool {
284        self.store.is_empty()
285    }
286}
287
288impl<S: AnswerStore> ExactCache<S> {
289    fn read(&self, key: Option<Key>, request: &Request) -> Option<CachedAnswer> {
290        if !may_read(request) {
291            return None;
292        }
293        let key = key?;
294        let bytes = self.store.get(&key)?;
295        match from_cbor::<CachedAnswer>(&bytes) {
296            Ok(a) => Some(a),
297            Err(_) => {
298                // Written by another version: forget it.
299                self.store.remove(&key);
300                None
301            }
302        }
303    }
304
305    fn write(&self, key: Option<Key>, request: &Request, answer: &CachedAnswer) {
306        if !may_store(request) || !answer.complete() {
307            return;
308        }
309        let Some(key) = key else { return };
310        if let Ok(bytes) = to_cbor(answer) {
311            self.store.put(&key, bytes);
312        }
313    }
314}
315
316/// Honours [`may_read`] and [`may_store`]; `get_rev` / `put_rev` key on the revision too.
317impl<S: AnswerStore> AnswerCache for ExactCache<S> {
318    fn get(&self, model: &str, request: &Request) -> Option<CachedAnswer> {
319        self.read(exact_key(model, request), request)
320    }
321
322    fn put(&self, model: &str, request: &Request, answer: &CachedAnswer) {
323        self.write(exact_key(model, request), request, answer);
324    }
325
326    fn get_rev(&self, model: &str, revision: Option<&str>, request: &Request) -> Option<CachedAnswer> {
327        self.read(exact_key_rev(model, revision, request), request)
328    }
329
330    fn put_rev(&self, model: &str, revision: Option<&str>, request: &Request, answer: &CachedAnswer) {
331        self.write(exact_key_rev(model, revision, request), request, answer);
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use weirdnet_agent::remote::infer::v2::{CacheMode, ContextRef, Sampling};
339    use weirdnet_agent::{ContentPart, Message, ToolSpec};
340
341    fn req(temp: f32, text: &str) -> Request {
342        let mut s = Sampling::default();
343        s.temperature = Some(temp);
344        Request::messages(vec![Message::user(text)]).with_sampling(s)
345    }
346
347    fn answer() -> CachedAnswer {
348        CachedAnswer::new("m", "hi", "stop")
349    }
350
351    #[test]
352    fn only_deterministic_requests_hit() {
353        let c = ExactCache::new(2);
354        c.put("m", &req(0.7, "a"), &answer());
355        assert!(c.is_empty());
356        c.put("m", &req(0.0, "a"), &answer());
357        assert_eq!(c.get("m", &req(0.0, "a")), Some(answer()));
358        assert!(c.get("other", &req(0.0, "a")).is_none());
359        assert!(c.get("m", &req(0.0, "b")).is_none());
360        assert!(c.get("m", &req(0.0, "a").with_seed(7)).is_none(), "the seed is part of the key");
361    }
362
363    #[test]
364    fn tools_and_context_refs_are_never_cached() {
365        let tool = ToolSpec::new("t", "a tool");
366        let with_tools = req(0.0, "a").with_tools(vec![tool]);
367        assert!(!deterministic(&with_tools));
368        let mut ctx = Request::context(ContextRef::new("conv", Some("head".into())));
369        ctx.sampling.temperature = Some(0.0);
370        assert!(!deterministic(&ctx));
371        assert!(exact_key("m", &ctx).is_none());
372    }
373
374    #[test]
375    fn image_parts_are_part_of_the_key() {
376        let with = |url: &str| {
377            let mut s = Sampling::default();
378            s.temperature = Some(0.0);
379            let parts = vec![ContentPart::text("what is this?"), ContentPart::image(url)];
380            Request::messages(vec![Message::user(parts)]).with_sampling(s)
381        };
382        let (a, b) = (with("data:image/png;base64,AAAA"), with("data:image/png;base64,BBBB"));
383        assert!(deterministic(&a));
384        let c = ExactCache::new(2);
385        c.put("m", &a, &answer());
386        assert_eq!(c.get("m", &a), Some(answer()));
387        assert!(c.get("m", &b).is_none(), "a different image is a different request");
388        assert!(c.get("m", &req(0.0, "what is this?")).is_none(), "text alone is a different request");
389    }
390
391    #[test]
392    fn bypass_neither_reads_nor_stores() {
393        let c = ExactCache::new(4);
394        let bypass = req(0.0, "a").with_cache(CacheMode::Bypass);
395        assert!(!may_read(&bypass) && !may_store(&bypass));
396        c.put("m", &bypass, &answer());
397        assert!(c.is_empty(), "bypass is not stored");
398        c.put("m", &req(0.0, "a"), &answer());
399        assert_eq!(c.get("m", &req(0.0, "a")), Some(answer()));
400        assert!(c.get("m", &bypass).is_none(), "bypass never reads");
401        assert_eq!(exact_key("m", &bypass), exact_key("m", &req(0.0, "a")), "the mode is not part of the key");
402    }
403
404    #[test]
405    fn refresh_overwrites_what_use_reads() {
406        let c = ExactCache::new(4);
407        let refresh = req(0.0, "a").with_cache(CacheMode::Refresh);
408        assert!(!may_read(&refresh) && may_store(&refresh));
409        c.put("m", &req(0.0, "a"), &CachedAnswer::new("m", "old", "stop"));
410        assert!(c.get("m", &refresh).is_none(), "refresh skips the read");
411        c.put("m", &refresh, &CachedAnswer::new("m", "new", "stop"));
412        assert_eq!(c.len(), 1);
413        assert_eq!(c.get("m", &req(0.0, "a")).map(|a| a.text), Some("new".into()));
414        // Also through the revision methods.
415        c.put_rev("m", Some("r1"), &refresh, &CachedAnswer::new("m", "r1", "stop"));
416        assert_eq!(c.get_rev("m", Some("r1"), &req(0.0, "a")).map(|a| a.text), Some("r1".into()));
417        assert!(c.get_rev("m", Some("r1"), &refresh).is_none());
418    }
419
420    #[test]
421    fn revisions_key_on_the_weights() {
422        let r = req(0.0, "a");
423        // No revision: the 0.2.0 key, so answers stored before still hit.
424        assert_eq!(exact_key_rev("m", None, &r), exact_key("m", &r));
425        let v1 = exact_key_rev("m", Some("r1"), &r).unwrap();
426        assert_ne!(Some(v1), exact_key("m", &r));
427        assert_ne!(Some(v1), exact_key_rev("m", Some("r2"), &r));
428
429        let c = ExactCache::new(4);
430        c.put_rev("m", Some("r1"), &r, &CachedAnswer::new("m", "from r1", "stop"));
431        assert!(c.get_rev("m", Some("r2"), &r).is_none(), "new weights don't replay old answers");
432        assert!(c.get("m", &r).is_none());
433        assert_eq!(c.get_rev("m", Some("r1"), &r).map(|a| a.text), Some("from r1".into()));
434        c.put_rev("m", None, &r, &answer());
435        assert_eq!(c.get("m", &r), Some(answer()));
436    }
437
438    #[test]
439    fn default_revision_methods_never_cross_weights() {
440        struct Plain(ExactCache);
441        impl AnswerCache for Plain {
442            fn get(&self, model: &str, request: &Request) -> Option<CachedAnswer> {
443                self.0.get(model, request)
444            }
445            fn put(&self, model: &str, request: &Request, answer: &CachedAnswer) {
446                self.0.put(model, request, answer)
447            }
448        }
449        let p = Plain(ExactCache::new(4));
450        let r = req(0.0, "a");
451        p.put_rev("m", Some("r1"), &r, &answer());
452        assert!(p.0.is_empty(), "a revision-blind cache keeps nothing for a revision");
453        p.put_rev("m", None, &r, &answer());
454        assert_eq!(p.get_rev("m", None, &r), Some(answer()));
455        assert!(p.get_rev("m", Some("r1"), &r).is_none());
456        assert!(NoCache.get_rev("m", None, &r).is_none());
457    }
458
459    #[test]
460    fn evicts_least_recently_used() {
461        let c = ExactCache::new(2);
462        c.put("m", &req(0.0, "a"), &answer());
463        c.put("m", &req(0.0, "b"), &answer());
464        c.get("m", &req(0.0, "a"));
465        c.put("m", &req(0.0, "c"), &answer());
466        assert!(c.get("m", &req(0.0, "a")).is_some());
467        assert!(c.get("m", &req(0.0, "b")).is_none());
468        assert_eq!(c.len(), 2);
469    }
470
471    #[test]
472    fn keeps_only_finished_answers() {
473        let c = ExactCache::new(2);
474        c.put("m", &req(0.0, "a"), &CachedAnswer::new("m", "h", "cancelled"));
475        let mut none = answer();
476        none.finish_reason = None;
477        c.put("m", &req(0.0, "a"), &none);
478        assert!(c.is_empty());
479        c.put("m", &req(0.0, "a"), &CachedAnswer::new("m", "h", "length"));
480        assert_eq!(c.len(), 1);
481    }
482
483    #[test]
484    fn unreadable_entries_are_dropped() {
485        let c = ExactCache::new(2);
486        let key = exact_key("m", &req(0.0, "a")).unwrap();
487        c.store().put(&key, vec![0xff, 0x00]);
488        assert!(c.get("m", &req(0.0, "a")).is_none());
489        assert!(c.is_empty());
490    }
491
492    #[test]
493    fn from_a_pool_answer() {
494        let mut a = Answer::default();
495        a.text = "x".into();
496        a.model = "m".into();
497        a.finish_reason = Some("stop".into());
498        let cached = CachedAnswer::from(&a);
499        assert!(cached.complete());
500        assert_eq!((cached.text.as_str(), cached.model.as_str()), ("x", "m"));
501    }
502}