open-standards/eoc/eoc-rs/crates/eoc-embeddings/src/cache.rs
Transaction Science 01d4ad9c7b Ingest batch 2: 9 new crates across openpay / smart-byte / eoc
openpay/ (+3 crates, ~8400 LOC, 162 tests)
  op-iso8583/         ISO 8583 messages for direct acquirer / card-network
                      connectivity. MTIs, primary+secondary bitmaps, full
                      DE catalogue, BCD/ASCII/EBCDIC/LLVAR/LLLVAR codecs,
                      five dialects (Visa Base I, Mastercard MDS, Amex GNS,
                      Discover, JCB), network-management messages
                      (sign-on/echo/cutover), DE 55 EMV TLV.
  op-mobile-wallets/  Apple Pay (ECDH-P256 + AES-256-GCM), Google Pay ECv2
                      (ECDH + HKDF + AES-256-CTR + HMAC), Samsung Pay. PAN
                      never leaves the decryption boundary as a String;
                      lands in VaultRef. No-PAN-leakage assertions per
                      wallet.
  op-routing/         Least-cost routing + MCC-aware routing + intelligent
                      retry / soft-decline recovery. 231-MCC catalogue.
                      Real ISO 8583 DE-39 soft/hard decline taxonomies.

smart-byte/smart-byte-rs/ (+3 crates, ~7100 LOC, 96 tests)
  smart-byte-vc/      W3C Verifiable Credentials 2.0: VCDM, presentations,
                      Data Integrity proofs (eddsa-jcs-2022), VC-JWT,
                      SD-JWT (selective disclosure), Bitstring Status
                      List 2021. Cargo-bridge maps VCs to Smart Byte
                      envelopes with SAID stability.
  smart-byte-did/     W3C DID resolution: did:key (Ed25519/P-256/secp256k1),
                      did:web (HTTPS), did:peer (numalgo 2+4), did:jwk,
                      did:ion (feature-gated stub). DID URL dereferencer.
  smart-byte-pq/      Post-quantum signatures: ML-DSA-44/65/87 (FIPS 204),
                      SLH-DSA across 12 parameter sets (FIPS 205), FN-DSA
                      (draft FIPS 206, feature-gated). Hybrid Ed25519 +
                      ML-DSA pattern for the transition. Secret-key
                      zeroize-on-drop.

eoc/eoc-rs/ (+3 crates, ~6450 LOC, 76 tests)
  eoc-vendor-api/     NeuralBackend implementations: Anthropic, OpenAI,
                      Google, Mistral, Cohere, Groq, Together, Fireworks.
                      SSE streaming. Prompt-caching where supported.
                      Joule estimates per published energy coefficient
                      (12-model curated table).
  eoc-embeddings/     21 embedding models behind one Embedder trait:
                      OpenAI v3 (3), Cohere v3 (3), Voyage (5), Mistral,
                      Jina, plus local ONNX (BGE x3, nomic, mxbai, GTE,
                      E5) behind 'local' feature. Matryoshka-style
                      dimension projection. Per-content-hash cache.
  eoc-route-learned/  RouteLLM-style matrix-factorisation router +
                      multinomial-logreg classifier + LinUCB / Thompson
                      bandits for online learning. LearnedCascade wraps
                      the rule-based cascade with a confidence-threshold
                      skip policy. Synthetic-eval accuracy: MF 0.935,
                      LogReg 0.980.

Quality:
- cargo check across all three workspaces: clean
- cargo clippy --all-targets -- -D warnings on every new crate: clean
- 334 new tests total; all passing
- #![forbid(unsafe_code)] across every new crate
- No unwrap/expect outside #[cfg(test)]

Rust 1.95.0 edition 2024 (inherited via root rust-toolchain.toml).
2026-05-23 18:12:24 -04:00

105 lines
3.1 KiB
Rust

//! Optional in-memory embedding cache.
//!
//! Embedders that hit the network (or run expensive local ONNX) benefit
//! from a content-addressed cache so the same string isn't re-embedded.
//! Keys are blake3 hashes of the (model, text) pair; values are the
//! produced vectors.
use std::num::NonZeroUsize;
use std::sync::Mutex;
use lru::LruCache;
/// Content-addressed cache key: blake3 hash of `(model, text)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ContentHash(pub [u8; 32]);
impl ContentHash {
/// Hash a `(model, text)` pair.
pub fn of(model: &str, text: &str) -> Self {
let mut h = blake3::Hasher::new();
h.update(model.as_bytes());
h.update(&[0u8]);
h.update(text.as_bytes());
let mut out = [0u8; 32];
out.copy_from_slice(h.finalize().as_bytes());
Self(out)
}
}
/// Bounded LRU cache of embedding vectors.
pub struct EmbeddingCache {
inner: Mutex<LruCache<ContentHash, Vec<f32>>>,
}
impl EmbeddingCache {
/// Construct with the given capacity. Panics only at construction time
/// if `capacity == 0` (impossible at runtime since the type enforces it).
pub fn new(capacity: usize) -> Self {
// `NonZeroUsize::new(1)` is infallible at construction.
let cap = NonZeroUsize::new(capacity.max(1)).unwrap_or_else(|| {
// Provably unreachable — the above max(1) guarantees ≥ 1.
#[allow(clippy::expect_used)]
NonZeroUsize::new(1).expect("1 is non-zero")
});
Self {
inner: Mutex::new(LruCache::new(cap)),
}
}
/// Look up an embedding by `(model, text)`.
pub fn get(&self, model: &str, text: &str) -> Option<Vec<f32>> {
let key = ContentHash::of(model, text);
let mut guard = self.inner.lock().ok()?;
guard.get(&key).cloned()
}
/// Store an embedding for `(model, text)`.
pub fn put(&self, model: &str, text: &str, vector: Vec<f32>) {
let key = ContentHash::of(model, text);
if let Ok(mut guard) = self.inner.lock() {
guard.put(key, vector);
}
}
/// Current number of entries.
pub fn len(&self) -> usize {
self.inner.lock().map(|g| g.len()).unwrap_or(0)
}
/// Whether the cache is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_is_deterministic() {
let a = ContentHash::of("m", "hello");
let b = ContentHash::of("m", "hello");
let c = ContentHash::of("m", "world");
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn cache_round_trip() {
let c = EmbeddingCache::new(8);
assert!(c.get("m", "hi").is_none());
c.put("m", "hi", vec![0.1, 0.2, 0.3]);
assert_eq!(c.get("m", "hi"), Some(vec![0.1, 0.2, 0.3]));
assert_eq!(c.len(), 1);
}
#[test]
fn cache_zero_capacity_clamps_to_one() {
let c = EmbeddingCache::new(0);
c.put("m", "x", vec![1.0]);
// Size 1: store then retrieve.
assert!(c.get("m", "x").is_some());
}
}