1use std::fmt;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use weirdnet_agent::remote::{RemoteError, from_cbor, to_cbor};
18
19use crate::semantic::{Lookup, SemanticCache};
20use crate::{AnswerStore, CachedAnswer, Key};
21
22pub const PROTOCOL: &str = "/weirdnet-semcache/shared/1";
24
25pub const WIRE_VERSION: u8 = 1;
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31#[non_exhaustive]
32pub enum SharedCacheReq<V = CachedAnswer> {
33 Lookup { scope: String, embedding: Vec<f32> },
35 Insert {
38 scope: String,
39 embedding: Vec<f32>,
40 value: V,
41 #[serde(default)]
42 age_ms: u64,
43 },
44 RemoveScope { scope: String },
46 ExactGet {
48 #[serde(with = "wire_bytes::key")]
49 key: Key,
50 },
51 ExactPut {
53 #[serde(with = "wire_bytes::key")]
54 key: Key,
55 #[serde(with = "wire_bytes::vec")]
56 value: Vec<u8>,
57 },
58 ExactRemove {
60 #[serde(with = "wire_bytes::key")]
61 key: Key,
62 },
63 Ping,
65}
66
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69#[serde(rename_all = "snake_case")]
70#[non_exhaustive]
71pub enum SharedCacheResp<V = CachedAnswer> {
72 Hit {
75 value: V,
76 score: f32,
77 #[serde(default)]
78 embedding: Vec<f32>,
79 },
80 Miss { best: Option<f32> },
83 Stored,
85 Removed { count: u64 },
87 Exact {
89 #[serde(with = "wire_bytes::opt")]
90 value: Option<Vec<u8>>,
91 },
92 Pong { entries: u64 },
94 Error { message: String },
97}
98
99impl<V> SharedCacheResp<V> {
100 pub fn error(message: impl Into<String>) -> Self {
101 Self::Error { message: message.into() }
102 }
103}
104
105#[derive(Serialize)]
106struct WireOut<'a, T> {
107 v: u8,
108 body: &'a T,
109}
110
111#[derive(Deserialize)]
112struct WireIn<T> {
113 body: T,
114}
115
116#[derive(Deserialize)]
117struct Head {
118 v: u8,
119}
120
121fn encode<T: Serialize>(body: &T) -> Result<Vec<u8>, RemoteError> {
122 to_cbor(&WireOut { v: WIRE_VERSION, body })
123}
124
125fn decode<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, RemoteError> {
126 let head: Head = from_cbor(bytes)?;
127 if head.v != WIRE_VERSION {
128 return Err(RemoteError::Unsupported { message: format!("shared cache message version {}", head.v) });
129 }
130 Ok(from_cbor::<WireIn<T>>(bytes)?.body)
131}
132
133impl<V: Serialize> SharedCacheReq<V> {
134 pub fn encode(&self) -> Result<Vec<u8>, RemoteError> {
136 encode(self)
137 }
138}
139
140impl<V: DeserializeOwned> SharedCacheReq<V> {
141 pub fn decode(bytes: &[u8]) -> Result<Self, RemoteError> {
144 decode(bytes)
145 }
146}
147
148impl<V: Serialize> SharedCacheResp<V> {
149 pub fn encode(&self) -> Result<Vec<u8>, RemoteError> {
151 encode(self)
152 }
153}
154
155impl<V: DeserializeOwned> SharedCacheResp<V> {
156 pub fn decode(bytes: &[u8]) -> Result<Self, RemoteError> {
158 decode(bytes)
159 }
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
164#[non_exhaustive]
165pub struct HostLimits {
166 pub max_scope_len: usize,
168 pub max_dimension: usize,
170 pub max_exact_value: usize,
172}
173
174impl HostLimits {
175 pub fn new() -> Self {
177 Self { max_scope_len: 512, max_dimension: 16384, max_exact_value: 8 << 20 }
178 }
179
180 pub fn with_max_scope_len(mut self, n: usize) -> Self {
181 self.max_scope_len = n;
182 self
183 }
184
185 pub fn with_max_dimension(mut self, n: usize) -> Self {
186 self.max_dimension = n;
187 self
188 }
189
190 pub fn with_max_exact_value(mut self, n: usize) -> Self {
191 self.max_exact_value = n;
192 self
193 }
194}
195
196impl Default for HostLimits {
197 fn default() -> Self {
198 Self::new()
199 }
200}
201
202pub struct SharedCacheHost<V = CachedAnswer> {
207 semantic: Arc<SemanticCache<V>>,
208 exact: Option<Arc<dyn AnswerStore>>,
209 limits: HostLimits,
210}
211
212impl<V> Clone for SharedCacheHost<V> {
213 fn clone(&self) -> Self {
214 Self { semantic: self.semantic.clone(), exact: self.exact.clone(), limits: self.limits.clone() }
215 }
216}
217
218impl<V> fmt::Debug for SharedCacheHost<V> {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 f.debug_struct("SharedCacheHost").field("exact", &self.exact.is_some()).field("limits", &self.limits).finish_non_exhaustive()
221 }
222}
223
224impl<V: Clone> SharedCacheHost<V> {
225 pub fn new(semantic: Arc<SemanticCache<V>>) -> Self {
227 Self { semantic, exact: None, limits: HostLimits::new() }
228 }
229
230 pub fn with_exact(mut self, store: Arc<dyn AnswerStore>) -> Self {
232 self.exact = Some(store);
233 self
234 }
235
236 pub fn with_limits(mut self, limits: HostLimits) -> Self {
237 self.limits = limits;
238 self
239 }
240
241 pub fn semantic(&self) -> &Arc<SemanticCache<V>> {
242 &self.semantic
243 }
244
245 pub fn exact(&self) -> Option<&Arc<dyn AnswerStore>> {
246 self.exact.as_ref()
247 }
248
249 pub fn limits(&self) -> &HostLimits {
250 &self.limits
251 }
252
253 fn check_scope(&self, scope: &str) -> Result<(), String> {
254 if scope.len() > self.limits.max_scope_len {
255 return Err(format!("scope is {} bytes, at most {}", scope.len(), self.limits.max_scope_len));
256 }
257 Ok(())
258 }
259
260 fn check_embedding(&self, embedding: &[f32]) -> Result<(), String> {
261 if embedding.len() > self.limits.max_dimension {
262 return Err(format!("embedding has {} dimensions, at most {}", embedding.len(), self.limits.max_dimension));
263 }
264 Ok(())
265 }
266
267 pub fn handle(&self, req: SharedCacheReq<V>) -> SharedCacheResp<V> {
269 match self.try_handle(req) {
270 Ok(resp) => resp,
271 Err(message) => SharedCacheResp::Error { message },
272 }
273 }
274
275 fn try_handle(&self, req: SharedCacheReq<V>) -> Result<SharedCacheResp<V>, String> {
276 let exact = || self.exact.as_ref().ok_or_else(|| "this node keeps no exact entries".to_string());
277 Ok(match req {
278 SharedCacheReq::Lookup { scope, embedding } => {
279 self.check_scope(&scope)?;
280 self.check_embedding(&embedding)?;
281 match self.semantic.lookup_with_vector(&scope, &embedding, Instant::now()).map_err(|e| e.to_string())? {
282 (Lookup::Hit { value, score, .. }, vector) => SharedCacheResp::Hit { value, score, embedding: vector.unwrap_or_default() },
283 (Lookup::Miss { best }, _) => SharedCacheResp::Miss { best },
284 }
285 }
286 SharedCacheReq::Insert { scope, embedding, value, age_ms } => {
287 self.check_scope(&scope)?;
288 self.check_embedding(&embedding)?;
289 let now = Instant::now();
290 let age = Duration::from_millis(age_ms);
291 if self.semantic.config().ttl.is_some_and(|ttl| age >= ttl) {
292 return Ok(SharedCacheResp::Stored);
294 }
295 let stored = now.checked_sub(age).unwrap_or(now);
296 self.semantic.insert_at(&scope, &embedding, value, stored).map_err(|e| e.to_string())?;
297 SharedCacheResp::Stored
298 }
299 SharedCacheReq::RemoveScope { scope } => SharedCacheResp::Removed { count: self.semantic.remove_scope(&scope) as u64 },
300 SharedCacheReq::ExactGet { key } => SharedCacheResp::Exact { value: exact()?.get(&key) },
301 SharedCacheReq::ExactPut { key, value } => {
302 if value.len() > self.limits.max_exact_value {
303 return Err(format!("exact value is {} bytes, at most {}", value.len(), self.limits.max_exact_value));
304 }
305 exact()?.put(&key, value);
306 SharedCacheResp::Stored
307 }
308 SharedCacheReq::ExactRemove { key } => {
309 let store = exact()?;
310 let had = store.get(&key).is_some();
311 store.remove(&key);
312 SharedCacheResp::Removed { count: u64::from(had) }
313 }
314 SharedCacheReq::Ping => SharedCacheResp::Pong { entries: self.semantic.len() as u64 },
315 })
316 }
317}
318
319impl<V: Clone + Serialize + DeserializeOwned> SharedCacheHost<V> {
320 pub fn handle_bytes(&self, bytes: &[u8]) -> Result<Vec<u8>, RemoteError> {
323 let resp = match SharedCacheReq::<V>::decode(bytes) {
324 Ok(req) => self.handle(req),
325 Err(e) => SharedCacheResp::Error { message: e.to_string() },
326 };
327 resp.encode()
328 }
329}
330
331mod wire_bytes {
333 use serde::de::{self, SeqAccess, Visitor};
334 use serde::{Deserializer, Serializer};
335
336 struct BytesVisitor;
337
338 impl<'de> Visitor<'de> for BytesVisitor {
339 type Value = Vec<u8>;
340
341 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
342 f.write_str("a byte string")
343 }
344
345 fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Vec<u8>, E> {
346 Ok(v.to_vec())
347 }
348
349 fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Vec<u8>, E> {
350 Ok(v)
351 }
352
353 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
354 let mut out = Vec::new();
355 while let Some(b) = seq.next_element::<u8>()? {
356 out.push(b);
357 }
358 Ok(out)
359 }
360 }
361
362 pub mod vec {
363 use super::*;
364
365 pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
366 s.serialize_bytes(v)
367 }
368
369 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
370 d.deserialize_byte_buf(BytesVisitor)
371 }
372 }
373
374 pub mod key {
375 use super::*;
376 use crate::Key;
377
378 pub fn serialize<S: Serializer>(v: &Key, s: S) -> Result<S::Ok, S::Error> {
379 s.serialize_bytes(v)
380 }
381
382 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Key, D::Error> {
383 let v = d.deserialize_byte_buf(BytesVisitor)?;
384 let n = v.len();
385 v.try_into().map_err(|_| de::Error::invalid_length(n, &"32 bytes"))
386 }
387 }
388
389 pub mod opt {
390 use serde::{Deserialize, Deserializer, Serializer};
391
392 struct Wrap<'a>(&'a [u8]);
393
394 impl serde::Serialize for Wrap<'_> {
395 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
396 s.serialize_bytes(self.0)
397 }
398 }
399
400 #[derive(Deserialize)]
401 struct Owned(#[serde(with = "super::vec")] Vec<u8>);
402
403 pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
404 match v {
405 Some(b) => s.serialize_some(&Wrap(b)),
406 None => s.serialize_none(),
407 }
408 }
409
410 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
411 Ok(Option::<Owned>::deserialize(d)?.map(|o| o.0))
412 }
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use crate::{MemoryStore, SemanticConfig};
420
421 fn host() -> SharedCacheHost<String> {
422 let semantic = Arc::new(SemanticCache::with_config(SemanticConfig::new(8).with_threshold(0.9)));
423 SharedCacheHost::new(semantic).with_exact(Arc::new(MemoryStore::new(8)))
424 }
425
426 fn round_trip_req(req: SharedCacheReq<String>) {
427 let bytes = req.encode().unwrap();
428 assert_eq!(SharedCacheReq::<String>::decode(&bytes).unwrap(), req);
429 }
430
431 fn round_trip_resp(resp: SharedCacheResp<String>) {
432 let bytes = resp.encode().unwrap();
433 assert_eq!(SharedCacheResp::<String>::decode(&bytes).unwrap(), resp);
434 }
435
436 #[test]
437 fn every_message_round_trips() {
438 let key = [7u8; 32];
439 round_trip_req(SharedCacheReq::Lookup { scope: "s".into(), embedding: vec![1.0, -0.5] });
440 round_trip_req(SharedCacheReq::Insert { scope: "s".into(), embedding: vec![1.0], value: "v".into(), age_ms: 12 });
441 round_trip_req(SharedCacheReq::RemoveScope { scope: "s".into() });
442 round_trip_req(SharedCacheReq::ExactGet { key });
443 round_trip_req(SharedCacheReq::ExactPut { key, value: vec![1, 2, 3] });
444 round_trip_req(SharedCacheReq::ExactRemove { key });
445 round_trip_req(SharedCacheReq::Ping);
446 round_trip_resp(SharedCacheResp::Hit { value: "v".into(), score: 0.97, embedding: vec![0.6, 0.8] });
447 round_trip_resp(SharedCacheResp::Miss { best: Some(0.5) });
448 round_trip_resp(SharedCacheResp::Miss { best: None });
449 round_trip_resp(SharedCacheResp::Stored);
450 round_trip_resp(SharedCacheResp::Removed { count: 3 });
451 round_trip_resp(SharedCacheResp::Exact { value: Some(vec![9; 40]) });
452 round_trip_resp(SharedCacheResp::Exact { value: None });
453 round_trip_resp(SharedCacheResp::Pong { entries: 4 });
454 round_trip_resp(SharedCacheResp::error("no"));
455 }
456
457 #[test]
458 fn answers_round_trip_as_the_default_value() {
459 let resp: SharedCacheResp = SharedCacheResp::Hit { value: CachedAnswer::new("m", "hello", "stop"), score: 1.0, embedding: vec![1.0] };
460 assert_eq!(SharedCacheResp::<CachedAnswer>::decode(&resp.encode().unwrap()).unwrap(), resp);
461 }
462
463 #[test]
464 fn bytes_are_byte_strings() {
465 let req: SharedCacheReq<String> = SharedCacheReq::ExactPut { key: [0xab; 32], value: vec![0xcd; 64] };
466 let bytes = req.encode().unwrap();
467 assert!(bytes.len() < 140, "{}", bytes.len());
469 }
470
471 #[test]
472 fn other_versions_and_garbage_are_refused() {
473 #[derive(Serialize)]
474 struct Future {
475 v: u8,
476 body: SharedCacheReq<String>,
477 }
478 let bytes = to_cbor(&Future { v: 2, body: SharedCacheReq::Ping }).unwrap();
479 assert!(matches!(SharedCacheReq::<String>::decode(&bytes), Err(RemoteError::Unsupported { .. })));
480 assert!(matches!(SharedCacheReq::<String>::decode(&[0xff, 0x00]), Err(RemoteError::Protocol { .. })));
481 #[derive(Serialize)]
482 struct Unknown {
483 v: u8,
484 body: &'static str,
485 }
486 let newer = to_cbor(&Unknown { v: 1, body: "compact" }).unwrap();
487 assert!(matches!(SharedCacheReq::<String>::decode(&newer), Err(RemoteError::Protocol { .. })));
488 let resp = SharedCacheResp::<String>::decode(&host().handle_bytes(&newer).unwrap()).unwrap();
490 assert!(matches!(resp, SharedCacheResp::Error { .. }));
491 }
492
493 #[test]
494 fn the_host_serves_its_cache() {
495 let h = host();
496 let insert =
497 |scope: &str, e: Vec<f32>, v: &str| h.handle(SharedCacheReq::Insert { scope: scope.into(), embedding: e, value: v.into(), age_ms: 0 });
498 assert_eq!(insert("s", vec![2.0, 0.0], "a"), SharedCacheResp::Stored);
499 assert_eq!(insert("t", vec![0.0, 1.0], "b"), SharedCacheResp::Stored);
500 match h.handle(SharedCacheReq::Lookup { scope: "s".into(), embedding: vec![1.0, 0.05] }) {
501 SharedCacheResp::Hit { value, score, embedding } => {
502 assert_eq!(value, "a");
503 assert!(score > 0.99);
504 assert_eq!(embedding, vec![1.0, 0.0], "the stored entry's normalized embedding");
505 }
506 other => panic!("{other:?}"),
507 }
508 assert!(matches!(h.handle(SharedCacheReq::Lookup { scope: "t".into(), embedding: vec![1.0, 0.0] }), SharedCacheResp::Miss { best: Some(_) }));
509 assert_eq!(h.handle(SharedCacheReq::Lookup { scope: "u".into(), embedding: vec![1.0, 0.0] }), SharedCacheResp::Miss { best: None });
510 assert_eq!(h.handle(SharedCacheReq::Ping), SharedCacheResp::Pong { entries: 2 });
511 assert_eq!(h.handle(SharedCacheReq::RemoveScope { scope: "s".into() }), SharedCacheResp::Removed { count: 1 });
512 assert_eq!(h.semantic().len(), 1);
513 assert!(matches!(insert("t", vec![1.0, 0.0, 0.0], "c"), SharedCacheResp::Error { .. }));
515 assert!(matches!(insert("t", vec![f32::NAN, 1.0], "c"), SharedCacheResp::Error { .. }));
516 }
517
518 #[test]
519 fn the_host_serves_exact_entries() {
520 let h = host();
521 let key = [1u8; 32];
522 assert_eq!(h.handle(SharedCacheReq::ExactGet { key }), SharedCacheResp::Exact { value: None });
523 assert_eq!(h.handle(SharedCacheReq::ExactPut { key, value: vec![5] }), SharedCacheResp::Stored);
524 assert_eq!(h.handle(SharedCacheReq::ExactGet { key }), SharedCacheResp::Exact { value: Some(vec![5]) });
525 assert_eq!(h.handle(SharedCacheReq::ExactRemove { key }), SharedCacheResp::Removed { count: 1 });
526 assert_eq!(h.handle(SharedCacheReq::ExactRemove { key }), SharedCacheResp::Removed { count: 0 });
527 let plain: SharedCacheHost<String> = SharedCacheHost::new(Arc::new(SemanticCache::new(1)));
528 assert!(matches!(plain.handle(SharedCacheReq::ExactGet { key }), SharedCacheResp::Error { .. }));
529 }
530
531 #[test]
532 fn the_host_enforces_its_limits() {
533 let h = host().with_limits(HostLimits::new().with_max_scope_len(4).with_max_dimension(2).with_max_exact_value(2));
534 let long = SharedCacheReq::Lookup { scope: "scope".into(), embedding: vec![1.0] };
535 assert!(matches!(h.handle(long), SharedCacheResp::Error { .. }));
536 let wide = SharedCacheReq::Insert { scope: "s".into(), embedding: vec![1.0; 3], value: "v".into(), age_ms: 0 };
537 assert!(matches!(h.handle(wide), SharedCacheResp::Error { .. }));
538 assert!(matches!(h.handle(SharedCacheReq::ExactPut { key: [0; 32], value: vec![0; 3] }), SharedCacheResp::Error { .. }));
539 assert!(h.semantic().is_empty() && h.exact().unwrap().is_empty());
540 assert_eq!(h.limits().max_dimension, 2);
541 }
542
543 #[test]
544 fn copied_entries_keep_their_age() {
545 let semantic = Arc::new(SemanticCache::with_config(SemanticConfig::new(8).with_ttl(Duration::from_secs(60))));
546 let h: SharedCacheHost<String> = SharedCacheHost::new(semantic);
547 let old = SharedCacheReq::Insert { scope: "s".into(), embedding: vec![1.0], value: "v".into(), age_ms: 60_000 };
548 assert_eq!(h.handle(old), SharedCacheResp::Stored);
549 assert!(h.semantic().is_empty(), "already past the TTL");
550 let young = SharedCacheReq::Insert { scope: "s".into(), embedding: vec![1.0], value: "v".into(), age_ms: 1_000 };
551 assert_eq!(h.handle(young), SharedCacheResp::Stored);
552 assert_eq!(h.semantic().len(), 1);
553 }
554}