1use std::collections::HashMap;
15use std::fmt;
16use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
17use std::sync::{Arc, Mutex, RwLock};
18use std::time::{Duration, Instant};
19
20use async_trait::async_trait;
21use serde::Serialize;
22use serde::de::DeserializeOwned;
23use tokio::sync::Notify;
24use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError};
25
26use crate::semantic::{Lookup, SemanticCache, SemanticConfig, SemanticError, normalize};
27use crate::shard::{ShardPlan, ShardRing};
28use crate::shared::{PROTOCOL, SharedCacheHost, SharedCacheReq, SharedCacheResp};
29use crate::{AnswerStore, CachedAnswer, Key};
30
31#[async_trait]
37pub trait CacheTransport<V = CachedAnswer>: Send + Sync {
38 async fn call(&self, node: &str, req: SharedCacheReq<V>) -> Result<SharedCacheResp<V>, RemoteError>;
39}
40
41pub struct DialerTransport<D> {
44 dialer: D,
45}
46
47impl<D> DialerTransport<D> {
48 pub fn new(dialer: D) -> Self {
49 Self { dialer }
50 }
51
52 pub fn dialer(&self) -> &D {
53 &self.dialer
54 }
55}
56
57#[async_trait]
58impl<D, V> CacheTransport<V> for DialerTransport<D>
59where
60 D: Dialer,
61 V: Serialize + DeserializeOwned + Send + Sync + 'static,
62{
63 async fn call(&self, node: &str, req: SharedCacheReq<V>) -> Result<SharedCacheResp<V>, RemoteError> {
64 let mut ch = self.dialer.open(node, PROTOCOL).await?;
65 ch.tx.send(req.encode()?).await?;
66 match ch.rx.recv().await? {
67 Some(bytes) => SharedCacheResp::decode(&bytes),
68 None => Err(RemoteError::Closed),
69 }
70 }
71}
72
73pub async fn serve<V>(mut ch: Channel, caller: &Caller, auth: &dyn Authorize, host: &SharedCacheHost<V>) -> Result<(), RemoteError>
77where
78 V: Clone + Serialize + DeserializeOwned + Send + Sync,
79{
80 if let Err(e) = auth.authorize(caller) {
81 let _ = ch.tx.send(SharedCacheResp::<V>::error(e.to_string()).encode()?).await;
82 return Err(e);
83 }
84 while let Some(bytes) = ch.rx.recv().await? {
85 ch.tx.send(host.handle_bytes(&bytes)?).await?;
86 }
87 Ok(())
88}
89
90#[derive(Debug, Clone, PartialEq)]
92#[non_exhaustive]
93pub struct PoolConfig {
94 pub lookup_timeout: Duration,
96 pub write_timeout: Duration,
98 pub down_for: Duration,
100 pub l1_entries: usize,
102 pub l1_ttl: Option<Duration>,
104 pub ask_replica_on_miss: bool,
107}
108
109impl PoolConfig {
110 pub fn new() -> Self {
112 Self {
113 lookup_timeout: Duration::from_millis(150),
114 write_timeout: Duration::from_secs(2),
115 down_for: Duration::from_secs(10),
116 l1_entries: 256,
117 l1_ttl: Some(Duration::from_secs(300)),
118 ask_replica_on_miss: false,
119 }
120 }
121
122 pub fn with_lookup_timeout(mut self, t: Duration) -> Self {
123 self.lookup_timeout = t;
124 self
125 }
126
127 pub fn with_write_timeout(mut self, t: Duration) -> Self {
128 self.write_timeout = t;
129 self
130 }
131
132 pub fn with_down_for(mut self, t: Duration) -> Self {
133 self.down_for = t;
134 self
135 }
136
137 pub fn with_l1(mut self, entries: usize, ttl: Option<Duration>) -> Self {
139 self.l1_entries = entries;
140 self.l1_ttl = ttl;
141 self
142 }
143
144 pub fn with_ask_replica_on_miss(mut self, ask: bool) -> Self {
145 self.ask_replica_on_miss = ask;
146 self
147 }
148}
149
150impl Default for PoolConfig {
151 fn default() -> Self {
152 Self::new()
153 }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum HitFrom {
160 L1,
162 Shard,
164 Peer { node: String, replica: bool },
166}
167
168#[derive(Debug, Clone, PartialEq)]
170#[non_exhaustive]
171pub enum PoolLookup<V> {
172 Hit {
173 value: V,
174 score: f32,
175 from: HitFrom,
176 },
177 Miss {
178 best: Option<f32>,
180 degraded: bool,
183 },
184}
185
186impl<V> PoolLookup<V> {
187 pub fn is_hit(&self) -> bool {
188 matches!(self, Self::Hit { .. })
189 }
190
191 pub fn score(&self) -> Option<f32> {
193 match self {
194 Self::Hit { score, .. } => Some(*score),
195 Self::Miss { best, .. } => *best,
196 }
197 }
198
199 pub fn into_value(self) -> Option<V> {
200 match self {
201 Self::Hit { value, .. } => Some(value),
202 Self::Miss { .. } => None,
203 }
204 }
205}
206
207#[derive(Debug, Clone, Default, PartialEq, Eq)]
209#[non_exhaustive]
210pub struct PoolWrite {
211 pub acked: Vec<String>,
213 pub queued: Vec<String>,
215 pub failed: Vec<String>,
217}
218
219#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
221#[non_exhaustive]
222pub struct PoolStats {
223 pub l1_hits: u64,
224 pub shard_hits: u64,
225 pub peer_hits: u64,
226 pub misses: u64,
227 pub degraded: u64,
229 pub peer_errors: u64,
231 pub timeouts: u64,
233 pub skipped: u64,
235}
236
237#[derive(Default)]
238struct Counters {
239 l1_hits: AtomicU64,
240 shard_hits: AtomicU64,
241 peer_hits: AtomicU64,
242 misses: AtomicU64,
243 degraded: AtomicU64,
244 peer_errors: AtomicU64,
245 timeouts: AtomicU64,
246 skipped: AtomicU64,
247}
248
249fn better(a: Option<f32>, b: Option<f32>) -> Option<f32> {
250 match (a, b) {
251 (Some(x), Some(y)) => Some(x.max(y)),
252 (x, None) => x,
253 (None, y) => y,
254 }
255}
256
257fn bump(c: &AtomicU64) {
258 c.fetch_add(1, Ordering::Relaxed);
259}
260
261struct Peers<V> {
263 transport: Arc<dyn CacheTransport<V>>,
264 down: Mutex<HashMap<String, Instant>>,
265 counters: Counters,
266 in_flight: AtomicUsize,
267 settled: Notify,
268 down_for: Duration,
269}
270
271enum CallFailure {
273 Unreachable,
275 Refused,
277}
278
279impl<V: Send + 'static> Peers<V> {
280 fn is_down(&self, node: &str) -> bool {
281 let mut down = self.down.lock().unwrap_or_else(|e| e.into_inner());
282 match down.get(node) {
283 Some(until) if *until > Instant::now() => true,
284 Some(_) => {
285 down.remove(node);
286 false
287 }
288 None => false,
289 }
290 }
291
292 fn mark_down(&self, node: &str) {
293 if !self.down_for.is_zero() {
294 self.down.lock().unwrap_or_else(|e| e.into_inner()).insert(node.to_owned(), Instant::now() + self.down_for);
295 }
296 }
297
298 fn mark_up(&self, node: &str) {
299 self.down.lock().unwrap_or_else(|e| e.into_inner()).remove(node);
300 }
301
302 async fn call(&self, node: &str, req: SharedCacheReq<V>, timeout: Duration) -> Result<SharedCacheResp<V>, CallFailure> {
303 if self.is_down(node) {
304 bump(&self.counters.skipped);
305 return Err(CallFailure::Unreachable);
306 }
307 match tokio::time::timeout(timeout, self.transport.call(node, req)).await {
308 Ok(Ok(SharedCacheResp::Error { .. })) => {
309 self.mark_up(node);
310 bump(&self.counters.peer_errors);
311 Err(CallFailure::Refused)
312 }
313 Ok(Ok(resp)) => {
314 self.mark_up(node);
315 Ok(resp)
316 }
317 Ok(Err(e)) => {
318 bump(&self.counters.peer_errors);
319 if !e.is_request_error() {
320 self.mark_down(node);
321 }
322 Err(CallFailure::Unreachable)
323 }
324 Err(_) => {
325 bump(&self.counters.timeouts);
326 self.mark_down(node);
327 Err(CallFailure::Unreachable)
328 }
329 }
330 }
331
332 fn spawn(self: &Arc<Self>, node: String, req: SharedCacheReq<V>, timeout: Duration)
334 where
335 V: Sync,
336 {
337 self.in_flight.fetch_add(1, Ordering::SeqCst);
338 let peers = self.clone();
339 tokio::spawn(async move {
340 let _ = peers.call(&node, req, timeout).await;
341 if peers.in_flight.fetch_sub(1, Ordering::SeqCst) == 1 {
342 peers.settled.notify_waiters();
343 }
344 });
345 }
346}
347
348pub struct PooledSemanticCache<V = CachedAnswer> {
363 node: String,
364 ring: RwLock<ShardRing>,
365 shard: Arc<SemanticCache<V>>,
366 l1: Option<SemanticCache<V>>,
367 exact: Option<Arc<dyn AnswerStore>>,
368 peers: Arc<Peers<V>>,
369 config: PoolConfig,
370}
371
372impl<V> fmt::Debug for PooledSemanticCache<V> {
373 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374 f.debug_struct("PooledSemanticCache")
375 .field("node", &self.node)
376 .field("ring", &*self.ring.read().unwrap_or_else(|e| e.into_inner()))
377 .field("config", &self.config)
378 .finish_non_exhaustive()
379 }
380}
381
382impl<V> PooledSemanticCache<V>
383where
384 V: Clone + Serialize + DeserializeOwned + Send + Sync + 'static,
385{
386 pub fn new(node: impl Into<String>, shard: Arc<SemanticCache<V>>, transport: Arc<dyn CacheTransport<V>>, config: PoolConfig) -> Self {
389 let node = node.into();
390 let l1 = (config.l1_entries > 0).then(|| {
391 let mut c = SemanticConfig::new(config.l1_entries).with_threshold(shard.config().threshold);
392 c.ttl = config.l1_ttl;
393 c.dimension = shard.config().dimension;
394 SemanticCache::with_config(c)
395 });
396 let peers = Arc::new(Peers {
397 transport,
398 down: Mutex::new(HashMap::new()),
399 counters: Counters::default(),
400 in_flight: AtomicUsize::new(0),
401 settled: Notify::new(),
402 down_for: config.down_for,
403 });
404 Self { ring: RwLock::new(ShardRing::new([node.clone()])), node, shard, l1, exact: None, peers, config }
405 }
406
407 pub fn with_exact(mut self, store: Arc<dyn AnswerStore>) -> Self {
409 self.exact = Some(store);
410 self
411 }
412
413 pub fn node(&self) -> &str {
415 &self.node
416 }
417
418 pub fn config(&self) -> &PoolConfig {
419 &self.config
420 }
421
422 pub fn shard(&self) -> &Arc<SemanticCache<V>> {
424 &self.shard
425 }
426
427 pub fn host(&self) -> SharedCacheHost<V> {
429 let host = SharedCacheHost::new(self.shard.clone());
430 match &self.exact {
431 Some(store) => host.with_exact(store.clone()),
432 None => host,
433 }
434 }
435
436 pub fn ring(&self) -> ShardRing {
438 self.ring.read().unwrap_or_else(|e| e.into_inner()).clone()
439 }
440
441 pub fn set_nodes<I, S>(&self, nodes: I)
444 where
445 I: IntoIterator<Item = S>,
446 S: Into<String>,
447 {
448 *self.ring.write().unwrap_or_else(|e| e.into_inner()) = ShardRing::new(nodes);
449 }
450
451 pub fn join(&self, node: impl Into<String>) -> bool {
453 self.ring.write().unwrap_or_else(|e| e.into_inner()).insert(node)
454 }
455
456 pub fn leave(&self, node: &str) -> bool {
458 self.ring.write().unwrap_or_else(|e| e.into_inner()).remove(node)
459 }
460
461 pub fn plan(&self, shard: impl AsRef<[u8]>) -> Option<ShardPlan> {
463 self.ring.read().unwrap_or_else(|e| e.into_inner()).plan(shard)
464 }
465
466 pub fn is_down(&self, node: &str) -> bool {
468 self.peers.is_down(node)
469 }
470
471 pub fn stats(&self) -> PoolStats {
472 let c = &self.peers.counters;
473 let get = |a: &AtomicU64| a.load(Ordering::Relaxed);
474 PoolStats {
475 l1_hits: get(&c.l1_hits),
476 shard_hits: get(&c.shard_hits),
477 peer_hits: get(&c.peer_hits),
478 misses: get(&c.misses),
479 degraded: get(&c.degraded),
480 peer_errors: get(&c.peer_errors),
481 timeouts: get(&c.timeouts),
482 skipped: get(&c.skipped),
483 }
484 }
485
486 pub async fn settle(&self) {
488 loop {
489 let notified = self.peers.settled.notified();
490 if self.peers.in_flight.load(Ordering::SeqCst) == 0 {
491 return;
492 }
493 notified.await;
494 }
495 }
496
497 fn miss(&self, best: Option<f32>, degraded: bool) -> PoolLookup<V> {
498 bump(&self.peers.counters.misses);
499 if degraded {
500 bump(&self.peers.counters.degraded);
501 }
502 PoolLookup::Miss { best, degraded }
503 }
504
505 pub async fn lookup(&self, scope: &str, embedding: &[f32]) -> Result<PoolLookup<V>, SemanticError> {
509 let query = normalize(embedding)?;
510 if let Some(l1) = &self.l1
511 && let Ok(Lookup::Hit { value, score, .. }) = l1.lookup(scope, &query)
512 {
513 bump(&self.peers.counters.l1_hits);
514 return Ok(PoolLookup::Hit { value, score, from: HitFrom::L1 });
515 }
516 let Some(plan) = self.plan(scope) else {
517 return Ok(self.miss(None, false));
518 };
519 let mut best: Option<f32> = None;
520 let mut degraded = false;
521 let mut home_missed = false;
522 for (i, owner) in plan.owners().enumerate() {
523 let replica = i > 0;
524 if replica && home_missed && !self.config.ask_replica_on_miss {
525 break;
526 }
527 if owner == self.node {
528 match self.shard.lookup(scope, &query)? {
529 Lookup::Hit { value, score, .. } => {
530 bump(&self.peers.counters.shard_hits);
531 if replica && home_missed {
532 self.repair(&plan.home, scope, &query, &value);
533 }
534 return Ok(PoolLookup::Hit { value, score, from: HitFrom::Shard });
535 }
536 Lookup::Miss { best: b } => {
537 best = better(best, b);
538 home_missed = true;
539 continue;
540 }
541 }
542 }
543 let req = SharedCacheReq::Lookup { scope: scope.to_owned(), embedding: query.clone() };
544 match self.peers.call(owner, req, self.config.lookup_timeout).await {
545 Ok(SharedCacheResp::Hit { value, score, embedding }) => {
546 bump(&self.peers.counters.peer_hits);
547 if let Some(l1) = &self.l1 {
548 let at = if embedding.len() == query.len() { &embedding } else { &query };
549 let _ = l1.insert(scope, at, value.clone());
550 }
551 if replica && home_missed {
552 self.repair(&plan.home, scope, &query, &value);
553 }
554 return Ok(PoolLookup::Hit { value, score, from: HitFrom::Peer { node: owner.to_owned(), replica } });
555 }
556 Ok(SharedCacheResp::Miss { best: b }) => {
557 best = better(best, b);
558 home_missed = true;
559 }
560 Ok(_) | Err(_) => degraded = true,
561 }
562 }
563 Ok(self.miss(best, degraded))
564 }
565
566 fn repair(&self, home: &str, scope: &str, embedding: &[f32], value: &V) {
568 if home == self.node {
569 let _ = self.shard.insert(scope, embedding, value.clone());
570 } else {
571 let req = SharedCacheReq::Insert { scope: scope.to_owned(), embedding: embedding.to_vec(), value: value.clone(), age_ms: 0 };
572 self.peers.spawn(home.to_owned(), req, self.config.write_timeout);
573 }
574 }
575
576 pub async fn insert(&self, scope: &str, embedding: &[f32], value: V) -> Result<PoolWrite, SemanticError> {
579 let vector = normalize(embedding)?;
580 let mut out = PoolWrite::default();
581 let Some(plan) = self.plan(scope) else {
582 return Ok(out);
583 };
584 if plan.owns(&self.node) {
585 self.shard.insert(scope, &vector, value.clone())?;
586 out.acked.push(self.node.clone());
587 } else if let Some(l1) = &self.l1 {
588 let _ = l1.insert(scope, &vector, value.clone());
589 }
590 let req = |value: V| SharedCacheReq::Insert { scope: scope.to_owned(), embedding: vector.clone(), value, age_ms: 0 };
591 if plan.home != self.node {
592 match self.peers.call(&plan.home, req(value.clone()), self.config.write_timeout).await {
593 Ok(SharedCacheResp::Stored) => out.acked.push(plan.home.clone()),
594 _ => out.failed.push(plan.home.clone()),
595 }
596 }
597 if let Some(replica) = plan.replica.filter(|r| *r != self.node) {
598 if self.peers.is_down(&replica) {
599 bump(&self.peers.counters.skipped);
600 out.failed.push(replica);
601 } else {
602 self.peers.spawn(replica.clone(), req(value), self.config.write_timeout);
603 out.queued.push(replica);
604 }
605 }
606 Ok(out)
607 }
608
609 pub async fn remove_scope(&self, scope: &str) -> PoolWrite {
611 if let Some(l1) = &self.l1 {
612 l1.remove_scope(scope);
613 }
614 self.shard.remove_scope(scope);
615 let mut out = PoolWrite::default();
616 let ring = self.ring();
617 if ring.contains(&self.node) {
618 out.acked.push(self.node.clone());
619 }
620 let mut tasks = tokio::task::JoinSet::new();
621 for node in ring.nodes().filter(|n| *n != self.node) {
622 let (peers, node, scope, timeout) = (self.peers.clone(), node.to_owned(), scope.to_owned(), self.config.write_timeout);
623 tasks.spawn(async move {
624 let ok = matches!(peers.call(&node, SharedCacheReq::RemoveScope { scope }, timeout).await, Ok(SharedCacheResp::Removed { .. }));
625 (node, ok)
626 });
627 }
628 while let Some(done) = tasks.join_next().await {
629 match done {
630 Ok((node, true)) => out.acked.push(node),
631 Ok((node, false)) => out.failed.push(node),
632 Err(_) => {}
633 }
634 }
635 out.acked.sort();
636 out.failed.sort();
637 out
638 }
639
640 pub async fn exact_get(&self, key: &Key) -> Option<Vec<u8>> {
643 let exact = self.exact.as_ref()?;
644 let plan = self.plan(key)?;
645 for owner in plan.owners() {
646 if owner == self.node {
647 match exact.get(key) {
648 Some(v) => {
649 bump(&self.peers.counters.shard_hits);
650 return Some(v);
651 }
652 None => break,
653 }
654 }
655 match self.peers.call(owner, SharedCacheReq::ExactGet { key: *key }, self.config.lookup_timeout).await {
656 Ok(SharedCacheResp::Exact { value: Some(v) }) => {
657 bump(&self.peers.counters.peer_hits);
658 return Some(v);
659 }
660 Ok(SharedCacheResp::Exact { value: None }) => break,
661 _ => {}
662 }
663 }
664 bump(&self.peers.counters.misses);
665 None
666 }
667
668 pub async fn exact_put(&self, key: &Key, value: Vec<u8>) -> PoolWrite {
671 let mut out = PoolWrite::default();
672 let (Some(exact), Some(plan)) = (self.exact.as_ref(), self.plan(key)) else {
673 return out;
674 };
675 if plan.owns(&self.node) {
676 exact.put(key, value.clone());
677 out.acked.push(self.node.clone());
678 }
679 if plan.home != self.node {
680 match self.peers.call(&plan.home, SharedCacheReq::ExactPut { key: *key, value: value.clone() }, self.config.write_timeout).await {
681 Ok(SharedCacheResp::Stored) => out.acked.push(plan.home.clone()),
682 _ => out.failed.push(plan.home.clone()),
683 }
684 }
685 if let Some(replica) = plan.replica.filter(|r| *r != self.node) {
686 self.peers.spawn(replica.clone(), SharedCacheReq::ExactPut { key: *key, value }, self.config.write_timeout);
687 out.queued.push(replica);
688 }
689 out
690 }
691}