The pieces / weirdnet-semcache

weirdnet-semcache

The answer cache for inference nodes: the AnswerCache seam, a store trait, an exact-match cache for deterministic requests, similarity lookup by embedding, and pool mode: one cache shared across a pool’s inference nodes.

v0.2.3 GitHub crates.io docs.rs weirdnet-semcache = "0.2.3"

What it brings

Use weirdnet-semcache on an inference node to answer repeated deterministic prompts without running a model again, and, since 0.2.2, to answer prompts close enough in meaning to one it has already answered. Since 0.2.3 several inference nodes can share one cache, so an answer one node computed is a hit on all of them.

What it is

Before an inference node routes a prompt it asks the cache; afterwards it offers the finished answer. Requests and answers are weirdnet-agent 0.5.1 infer/2 types, and the store is a trait, so answers can live in memory, on disk or be shared between nodes.

How it works

Exact matches

Only deterministic requests are cached: temperature exactly 0, no tools, messages inline (not a context reference). The key is SHA-256 over the CBOR of a version, the model, the input, sampling, seed, response format and the raw flag, so two requests share an answer only when everything that could change it is equal. Image and audio parts (weirdnet-agent 0.5) are part of the input, so a different image is a different request. Only answers that finished with stop or length are kept; an unreadable stored entry is dropped. A hit should be marked with infer/2 Meta::cache_hit, which weirdnet-openai shows as x-weirdnet-cache: hit.

Bypass, refresh and revisions (0.2.1)

may_read(&request) and may_store(&request) follow the request's weirdnet-agent 0.5.1 CacheMode: ExactCache never reads for bypass or refresh and never stores for bypass. The mode is not part of the key, so a refresh overwrites the entry a later use reads. AnswerCache::get_rev and put_rev take the model's revision (its weights) as well as its id, so a fine-tune served under the same id doesn't replay the old weights' answers; exact_key_rev is the key. With no revision the key is the 0.2.0 one, so stored answers still hit. Their default methods miss and keep nothing when a revision is given, so a cache that doesn't know revisions never crosses weights.

Stores

AnswerStore keeps opaque bytes under 32-byte keys; MemoryStore::new(max) evicts the least recently used. ExactCache::with_store takes any store.

Similarity lookup (0.2.2)

SemanticCache doesn't embed anything itself: the caller embeds the prompt with its own embedding model and passes the vector (&[f32]). lookup(scope, embedding) finds the most similar live entry in that scope by cosine similarity and returns Lookup::Hit { value, score, id } when the score reaches the threshold (SemanticConfig::with_threshold, 0.95 by default), or Lookup::Miss { best } with the best score below it. insert(scope, embedding, value) stores an entry and returns its id; an entry pointing the same way is replaced rather than duplicated.

Scopes keep answers apart: build one with scope_key(&[model, revision, system_prompt_hash]) (SHA-256 over the length-prefixed parts) so different models, weights or system prompts never share an answer. Embeddings are refused when empty, not finite (NaN or infinity), all zero, or of the wrong dimension (a fixed with_dimension, or the scope's first entry), and are normalized on the way in. The cache holds at most max_entries across all scopes and evicts the least recently used; with_ttl expires entries by age. remove, remove_scope, clear and stats (entries, hits, misses, evictions, expired) round it out, and snapshot / restore write and read the entries as CBOR, keeping their age. Values default to CachedAnswer but can be any Clone type. As with ExactCache, check may_read and may_store on infer/2 requests first.

Pool mode (0.2.3)

Each entry lives on two of the pool's inference nodes: ShardRing::plan(scope) ranks the members by a SHA-256 score over the node id and the scope (rendezvous hashing) and gives the home and the replica. Every node that agrees on the member list agrees on every plan, so nothing is coordinated and a lookup is one call. Because a whole scope lives on one home, similarity search stays local to that node. When a node leaves, only its shards move, to their replica, which already has them; when one joins, it takes only the shards it now ranks first for, and their old home becomes the replica. All nodes must use the same embedding model and revision; a change should start a new scope.

Nodes talk SharedCacheReq / SharedCacheResp on /weirdnet-semcache/shared/1: CBOR with a version, for lookup, insert (with the entry's age, so a copy keeps its TTL), remove_scope, exact_get / exact_put / exact_remove and ping. A hit carries the stored embedding, so the asker's local copy points the same way. SharedCacheHost answers from the node's own SemanticCache (and an optional AnswerStore for exact entries) within HostLimits; it doesn't decide who may ask.

The pool feature adds the asking side. PooledSemanticCache::lookup tries a small local L1 copy, then the home (its own shard when it is the home), then the replica when the home failed. insert writes its own shard when it holds the scope, waits (bounded) for the home and sends the replica in the background (settle() waits for those). remove_scope reaches every member, so entries left behind by a membership change go too. Every remote call has a timeout (150 ms for lookups by default), a node that fails or times out is skipped for down_for, and when no owner answers the lookup is PoolLookup::Miss { degraded: true }: a cache outage costs a model run, never a stalled prompt. With ask_replica_on_miss a home's miss also asks the replica and copies a hit back (read repair), which finds entries right after a node joined. exact_get / exact_put share ExactCache keys the same way, and stats() counts hits by source, misses, timeouts, errors and skips.

CacheTransport is how a request reaches a node. DialerTransport opens a weirdnet-agent channel per call, and pool::serve(channel, caller, auth, host) answers on the other end once auth (for Weirdnet, the pool's RosterAuth) lets the caller in. Members come from the app (set_nodes, join, leave), for example the pool's inference nodes from the roster.

Key types and modules

  • AnswerCache: get(model, request) and put(model, request, answer); NoCache caches nothing.
  • CachedAnswer: text, reasoning, tool calls, finish reason, usage and model, from a pool Answer.
  • AnswerStore: opaque bytes under 32-byte keys. MemoryStore is bounded and least-recently-used.
  • ExactCache: answers only byte-identical deterministic requests (temperature 0, no tools, inline messages, same model, seed, response format and raw flag) and keeps only answers that finished with stop or length. The key is SHA-256 over their CBOR.
  • may_read and may_store (0.2.1): the request’s CacheMode. ExactCache never reads for bypass or refresh and never stores for bypass.
  • AnswerCache::get_rev / put_rev and exact_key_rev (0.2.1): keys that include the model revision, so new weights under the same id don’t replay old answers. With no revision the key is unchanged.
  • SemanticCache (0.2.2): similarity lookup by embedding. The nearest stored embedding in the same scope stands in when its cosine similarity reaches the threshold (default 0.95); lookup returns Lookup::Hit { value, score, id } or Lookup::Miss { best }. Bounded and least-recently-used, with an optional TTL, stats and a CBOR snapshot / restore.
  • scope_key, cosine_similarity and normalize (0.2.2): a scope over the model, revision and system prompt so answers never cross them, and the vector helpers.
  • ShardRing / ShardPlan (0.2.3): rendezvous hashing of a scope or exact key to a home node and one replica, so a shared lookup is one call; a leaving node’s shards move to their replica, and a joining node takes only the shards it now ranks first for.
  • SharedCacheReq / SharedCacheResp and SharedCacheHost (0.2.3): the versioned CBOR lookup / insert / remove / exact protocol on /weirdnet-semcache/shared/1, answered from a node’s own cache within HostLimits.
  • pool::PooledSemanticCache (0.2.3, pool feature): L1, the home, the replica when the home fails, per-call timeouts, down-node skipping, background replica writes, optional read repair and shared exact entries. A cache outage is a miss, never a stalled prompt. pool::DialerTransport and pool::serve run it over weirdnet-agent channels behind your Authorize.

Feature flags

None: everything is on by default.

Usage

[dependencies]
weirdnet-semcache = "0.2.3"
# Cargo.toml
weirdnet-semcache = "0.2"

// main.rs
use weirdnet_semcache::{AnswerCache, CachedAnswer, ExactCache};

let cache = ExactCache::new(256);
if let Some(hit) = cache.get_rev("qwen3-8b", Some(revision), &request) {
    // replay hit.text and mark the answer as a cache hit (infer/2 Meta::cache_hit)
}
cache.put_rev("qwen3-8b", Some(revision), &request, &CachedAnswer::from(&answer));

// similarity lookup: you embed the prompt
use weirdnet_semcache::{Lookup, SemanticCache, SemanticConfig, scope_key};

let semantic: SemanticCache = SemanticCache::with_config(SemanticConfig::new(1024).with_threshold(0.92));
let scope = scope_key(&["qwen3-8b", revision, &system_prompt_hash]);
if let Lookup::Hit { value, score, .. } = semantic.lookup(&scope, &embedding)? {
    // replay value.text; score is the cosine similarity
}
semantic.insert(&scope, &embedding, CachedAnswer::from(&answer))?;

// pool mode (features = ["pool"]): one cache across the pool's inference nodes
use std::sync::Arc;
use weirdnet_semcache::pool::{DialerTransport, PoolConfig, PoolLookup, PooledSemanticCache};

let shard = Arc::new(SemanticCache::with_config(SemanticConfig::new(4096).with_threshold(0.92)));
let pooled: PooledSemanticCache = PooledSemanticCache::new(my_peer_id, shard, Arc::new(DialerTransport::new(dialer)), PoolConfig::new());
pooled.set_nodes(inference_node_peer_ids); // this node included; serve pooled.host() with pool::serve
if let PoolLookup::Hit { value, .. } = pooled.lookup(&scope, &embedding).await? {
    // replay value.text; peers that fail or time out are a miss, never an error
}
pooled.insert(&scope, &embedding, CachedAnswer::from(&answer)).await?;

Where it fits

Version 0.2.3 is on crates.io (docs.rs). 0.2.3 is additive: ShardRing, ShardPlan, SharedCacheReq, SharedCacheResp, SharedCacheHost, HostLimits, PROTOCOL and WIRE_VERSION in the default build, with no new dependencies, and the opt-in pool feature (PooledSemanticCache, CacheTransport, DialerTransport, serve), whose tokio and async-trait already come with weirdnet-agent. Requested for Ymir’s shared semantic cache. 0.2.2 is additive, with no new dependencies: SemanticCache, SemanticConfig, Lookup, SemanticError, SemanticStats, scope_key, cosine_similarity and normalize. 0.2.1 is additive and needs weirdnet-agent 0.5.1: may_read, may_store, AnswerCache::get_rev / put_rev (default methods) and exact_key_rev. 0.2.0 needs weirdnet-agent 0.5 (content parts), which is breaking because AnswerCache takes agent Requests: move to agent 0.5 with it. Requests with image or audio parts are keyed like text ones, so a different image is a different request. 0.1.1 depends on weirdnet-agent "0.4" instead of =0.4.0, so it builds with agent 0.4.1; raw prompts (agent 0.4.1 Input::Prompt) are not cached. Extracted from Ymir’s ymir-semcache.