Skip to main content

weirdnet_semcache/
pool.rs

1//! Pool mode: inference nodes sharing one cache ([`PooledSemanticCache`]), over any
2//! [`CacheTransport`] ([`DialerTransport`] for `weirdnet-agent` channels, served by [`serve`]).
3//!
4//! Each entry lives on its shard's home node and one replica ([`ShardRing`]), so a lookup is one
5//! call. A node keeps the shards it holds in its own [`SemanticCache`] (served to the others by
6//! a [`SharedCacheHost`]) and, optionally, a small local copy (L1) of entries it fetched or wrote
7//! for shards it doesn't hold.
8//!
9//! **A cache outage never blocks inference.** Every remote call has a timeout; a node that fails
10//! or times out is skipped for a while ([`PoolConfig::down_for`]) and its replica asked instead;
11//! when nothing answers, a lookup is a miss ([`PoolLookup::Miss`] with `degraded: true`). Writes
12//! to the replica run in the background.
13
14use 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/// Sends one shared-cache request to a node and returns its answer.
32///
33/// [`DialerTransport`] does it over `weirdnet-agent` channels; tests and apps with their own
34/// links implement it directly. Implementations need not time out: [`PooledSemanticCache`]
35/// bounds every call.
36#[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
41/// A [`CacheTransport`] over a `weirdnet-agent` [`Dialer`]: one channel on [`PROTOCOL`] per call,
42/// one CBOR request, one CBOR response.
43pub 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
73/// Serves [`PROTOCOL`] on one channel: authorizes `caller` with `auth` first (for Weirdnet, the
74/// pool's roster: `weirdnet_agent::serve::RosterAuth`), then answers requests from `host` until
75/// the asker closes. A refused caller gets one [`SharedCacheResp::Error`] and the refusal.
76pub 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/// How a [`PooledSemanticCache`] waits, retries and copies.
91#[derive(Debug, Clone, PartialEq)]
92#[non_exhaustive]
93pub struct PoolConfig {
94    /// Longest wait for one remote lookup (a lookup asks at most the home and the replica).
95    pub lookup_timeout: Duration,
96    /// Longest wait for one remote write or removal.
97    pub write_timeout: Duration,
98    /// A node that failed or timed out is skipped this long. Zero never skips.
99    pub down_for: Duration,
100    /// Local copies (L1) of entries for shards this node doesn't hold; 0 keeps none.
101    pub l1_entries: usize,
102    /// L1 copies expire after this; `None` keeps them until evicted.
103    pub l1_ttl: Option<Duration>,
104    /// When the home misses, ask the replica too (and copy a hit back to the home). Costs a
105    /// second call per miss; finds entries right after a node joined and took over a shard.
106    pub ask_replica_on_miss: bool,
107}
108
109impl PoolConfig {
110    /// 150 ms lookups, 2 s writes, 10 s down time, 256 L1 entries for 5 minutes, home-only misses.
111    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    /// L1 with at most `entries` (0 turns it off) expiring after `ttl`.
138    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/// Where a [`PoolLookup::Hit`] came from.
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum HitFrom {
160    /// This node's L1 copy.
161    L1,
162    /// This node's own shard (it is the home or the replica).
163    Shard,
164    /// Another node: the shard's home, or its replica.
165    Peer { node: String, replica: bool },
166}
167
168/// The result of [`PooledSemanticCache::lookup`].
169#[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        /// The best score below the threshold, when an owner reported one.
179        best: Option<f32>,
180        /// An owner failed, timed out or was skipped as down, so this may be a miss only because
181        /// of the outage.
182        degraded: bool,
183    },
184}
185
186impl<V> PoolLookup<V> {
187    pub fn is_hit(&self) -> bool {
188        matches!(self, Self::Hit { .. })
189    }
190
191    /// The hit's score, or the best score of a miss.
192    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/// Which owners took a write or removal.
208#[derive(Debug, Clone, Default, PartialEq, Eq)]
209#[non_exhaustive]
210pub struct PoolWrite {
211    /// Nodes that confirmed it (this node included when it holds the shard).
212    pub acked: Vec<String>,
213    /// Nodes it was sent to in the background (the replica); see [`PooledSemanticCache::settle`].
214    pub queued: Vec<String>,
215    /// Nodes that refused, failed, timed out or were skipped as down.
216    pub failed: Vec<String>,
217}
218
219/// Counters since the cache was made.
220#[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    /// Misses with an owner unreachable.
228    pub degraded: u64,
229    /// Remote calls that failed or were refused.
230    pub peer_errors: u64,
231    /// Remote calls that timed out.
232    pub timeouts: u64,
233    /// Owners skipped because they were marked down.
234    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
261/// The calling side's shared state, cloned into background writes.
262struct 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
271/// Why a remote call didn't give an answer.
272enum CallFailure {
273    /// Down, failed or timed out: the node is marked down.
274    Unreachable,
275    /// The node answered with an error (refused, bad input): not marked down.
276    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    /// Sends `req` to `node` in the background.
333    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
348/// One inference node's view of the pool's shared semantic cache (and, with
349/// [`with_exact`](Self::with_exact), of its exact entries).
350///
351/// - [`lookup`](Self::lookup): L1, then the shard's home (this node's own cache when it is the
352///   home), then the replica if the home is unreachable. Never fails because of a peer.
353/// - [`insert`](Self::insert): this node's own cache when it holds the shard, the home (waited
354///   for, bounded), the replica in the background, and L1.
355/// - [`remove_scope`](Self::remove_scope): everywhere, every member (so entries left behind by a
356///   membership change go too).
357///
358/// Members come from the app ([`set_nodes`](Self::set_nodes), [`join`](Self::join),
359/// [`leave`](Self::leave)), for example the pool's inference nodes from the roster; every node
360/// must use the same ids, and must use the same embedding model and revision. Serve
361/// [`host`](Self::host) on [`PROTOCOL`] so the others can reach this node's shards.
362pub 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    /// This node is `node` (its id in the ring), keeps the shards it holds in `shard`, and
387    /// reaches the others over `transport`. The ring starts with this node alone.
388    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    /// Shares exact entries too, keeping this node's in `store`.
408    pub fn with_exact(mut self, store: Arc<dyn AnswerStore>) -> Self {
409        self.exact = Some(store);
410        self
411    }
412
413    /// This node's id.
414    pub fn node(&self) -> &str {
415        &self.node
416    }
417
418    pub fn config(&self) -> &PoolConfig {
419        &self.config
420    }
421
422    /// The shards this node holds.
423    pub fn shard(&self) -> &Arc<SemanticCache<V>> {
424        &self.shard
425    }
426
427    /// Serves this node's shards to the others (see [`serve`]).
428    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    /// The current members.
437    pub fn ring(&self) -> ShardRing {
438        self.ring.read().unwrap_or_else(|e| e.into_inner()).clone()
439    }
440
441    /// Replaces the members (usually including this node; without it, this node holds no
442    /// shards and only asks).
443    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    /// Adds a member; `false` when it already was one.
452    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    /// Removes a member; `false` when it wasn't one.
457    pub fn leave(&self, node: &str) -> bool {
458        self.ring.write().unwrap_or_else(|e| e.into_inner()).remove(node)
459    }
460
461    /// The home and replica for `scope` (or an exact key) now.
462    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    /// `node` was marked down after a failure and is being skipped.
467    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    /// Waits until background writes have finished (each is bounded by the write timeout).
487    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    /// The most similar entry for `embedding` in `scope`, wherever in the pool it lives. Errors
506    /// only for an embedding no cache would take (empty, not finite, zero, wrong dimension for
507    /// this node's own cache); peer failures are misses.
508    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    /// Copies a replica's hit back to the home that missed it (read repair).
567    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    /// Stores `value` under `embedding` in `scope` on the shard's owners. Errors only for an
577    /// embedding no cache would take; peer failures show in the [`PoolWrite`].
578    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    /// Drops every entry in `scope` here and on every member (waited for, bounded).
610    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    /// The exact entry under `key` (see [`exact_key_rev`](crate::exact_key_rev)) from its home,
641    /// or its replica when the home is unreachable. `None` without [`with_exact`](Self::with_exact).
642    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    /// Stores an exact entry on its home (waited for, bounded) and replica (in the background).
669    /// Nothing is stored without [`with_exact`](Self::with_exact).
670    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}