use std::hash::{BuildHasher, Hash, Hasher};
use ahash::RandomState;
const CACHE_KEY_SEED_0: u64 = 0x6c69_7465_725f_6c6c; const CACHE_KEY_SEED_1: u64 = 0x6d5f_6361_6368_655f; const CACHE_KEY_SEED_2: u64 = 0x6b65_795f_7374_7261; const CACHE_KEY_SEED_3: u64 = 0x7465_6779_5f76_3100;
fn cache_random_state() -> &'static RandomState {
use std::sync::OnceLock;
static STATE: OnceLock<RandomState> = OnceLock::new();
STATE.get_or_init(|| {
RandomState::generate_with(CACHE_KEY_SEED_0, CACHE_KEY_SEED_1, CACHE_KEY_SEED_2, CACHE_KEY_SEED_3)
})
}
#[inline]
fn seeded_hasher() -> impl Hasher {
cache_random_state().build_hasher()
}
pub struct CacheKeyInput<'a> {
pub model: &'a str,
pub messages_json: &'a str,
pub params_json: &'a str,
pub tenant_id: Option<&'a str>,
pub system_prompt: Option<&'a str>,
}
#[cfg_attr(alef, alef(skip))]
pub trait CacheKeyStrategy: Send + Sync + 'static {
fn key_for(&self, input: &CacheKeyInput<'_>) -> (u64, String);
}
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Default)]
pub struct ExactHashStrategy;
impl CacheKeyStrategy for ExactHashStrategy {
fn key_for(&self, input: &CacheKeyInput<'_>) -> (u64, String) {
let body = format!(
"{}|{}|{}|{}|{}",
input.model,
input.messages_json,
input.params_json,
input.tenant_id.unwrap_or(""),
input.system_prompt.unwrap_or(""),
);
let mut hasher = seeded_hasher();
body.hash(&mut hasher);
(hasher.finish(), body)
}
}
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Default)]
pub struct SystemPromptAwareStrategy;
impl CacheKeyStrategy for SystemPromptAwareStrategy {
fn key_for(&self, input: &CacheKeyInput<'_>) -> (u64, String) {
let body = format!(
"{}|{}|{}|{}",
input.model,
input.messages_json,
input.params_json,
input.system_prompt.unwrap_or(""),
);
let mut hasher = seeded_hasher();
body.hash(&mut hasher);
(hasher.finish(), body)
}
}
#[cfg_attr(alef, alef(skip))]
#[derive(Debug, Clone, Default)]
pub struct TenantScopedStrategy;
impl CacheKeyStrategy for TenantScopedStrategy {
fn key_for(&self, input: &CacheKeyInput<'_>) -> (u64, String) {
let body = format!(
"tenant:{}|{}|{}|{}|{}",
input.tenant_id.unwrap_or("__global__"),
input.model,
input.messages_json,
input.params_json,
input.system_prompt.unwrap_or(""),
);
let mut hasher = seeded_hasher();
body.hash(&mut hasher);
(hasher.finish(), body)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn input<'a>(
model: &'a str,
messages_json: &'a str,
params_json: &'a str,
tenant_id: Option<&'a str>,
system_prompt: Option<&'a str>,
) -> CacheKeyInput<'a> {
CacheKeyInput {
model,
messages_json,
params_json,
tenant_id,
system_prompt,
}
}
#[test]
fn exact_hash_strategy_is_deterministic() {
let s = ExactHashStrategy;
let i = input("gpt-4", r#"[{"role":"user","content":"hi"}]"#, "{}", None, None);
let (k1, b1) = s.key_for(&i);
let (k2, b2) = s.key_for(&i);
assert_eq!(k1, k2, "key must be deterministic");
assert_eq!(b1, b2, "body must be deterministic");
}
#[test]
fn exact_hash_strategy_distinct_inputs_produce_distinct_keys() {
let s = ExactHashStrategy;
let i1 = input("gpt-4", r#"[{"role":"user","content":"hello"}]"#, "{}", None, None);
let i2 = input("gpt-4", r#"[{"role":"user","content":"world"}]"#, "{}", None, None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_ne!(k1, k2, "distinct prompts must produce distinct keys");
}
#[test]
fn exact_hash_strategy_different_models_produce_distinct_keys() {
let s = ExactHashStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", None, None);
let i2 = input("gpt-4o", msgs, "{}", None, None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_ne!(k1, k2);
}
#[test]
fn exact_hash_strategy_different_tenants_produce_distinct_keys() {
let s = ExactHashStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", Some("tenant-a"), None);
let i2 = input("gpt-4", msgs, "{}", Some("tenant-b"), None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_ne!(k1, k2, "exact hash must differentiate tenants");
}
#[test]
fn system_prompt_aware_strategy_is_deterministic() {
let s = SystemPromptAwareStrategy;
let i = input(
"gpt-4",
r#"[{"role":"user","content":"hi"}]"#,
"{}",
None,
Some("be helpful"),
);
let (k1, b1) = s.key_for(&i);
let (k2, b2) = s.key_for(&i);
assert_eq!(k1, k2);
assert_eq!(b1, b2);
}
#[test]
fn system_prompt_aware_strategy_different_system_prompts_produce_distinct_keys() {
let s = SystemPromptAwareStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", None, Some("be helpful"));
let i2 = input("gpt-4", msgs, "{}", None, Some("be concise"));
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_ne!(k1, k2);
}
#[test]
fn system_prompt_aware_strategy_ignores_tenant_id() {
let s = SystemPromptAwareStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", Some("tenant-a"), None);
let i2 = input("gpt-4", msgs, "{}", Some("tenant-b"), None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_eq!(k1, k2, "system-prompt-aware strategy should ignore tenant_id");
}
#[test]
fn tenant_scoped_strategy_is_deterministic() {
let s = TenantScopedStrategy;
let i = input("gpt-4", r#"[{"role":"user","content":"hi"}]"#, "{}", Some("acme"), None);
let (k1, b1) = s.key_for(&i);
let (k2, b2) = s.key_for(&i);
assert_eq!(k1, k2);
assert_eq!(b1, b2);
}
#[test]
fn tenant_scoped_strategy_different_tenants_same_prompt_produce_distinct_keys() {
let s = TenantScopedStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", Some("acme"), None);
let i2 = input("gpt-4", msgs, "{}", Some("globex"), None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_ne!(k1, k2, "different tenants must produce different keys");
}
#[test]
fn tenant_scoped_strategy_no_tenant_uses_global_prefix() {
let s = TenantScopedStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i1 = input("gpt-4", msgs, "{}", None, None);
let i2 = input("gpt-4", msgs, "{}", None, None);
let (k1, _) = s.key_for(&i1);
let (k2, _) = s.key_for(&i2);
assert_eq!(
k1, k2,
"two requests without tenant_id should share a key under tenant-scoped strategy"
);
}
#[test]
fn cache_key_deterministic_across_invocations() {
let reference_input = input(
"openai/gpt-4o",
r#"[{"role":"user","content":"hello world"}]"#,
r#"{"temperature":0.7}"#,
Some("tenant-x"),
Some("You are helpful."),
);
let (expected_key, expected_body) = ExactHashStrategy.key_for(&reference_input);
for _ in 0..10 {
let s = ExactHashStrategy;
let (k, b) = s.key_for(&reference_input);
assert_eq!(k, expected_key, "key must be stable across ExactHashStrategy instances");
assert_eq!(
b, expected_body,
"body must be stable across ExactHashStrategy instances"
);
}
}
#[test]
fn strategies_can_produce_different_keys_for_same_input() {
let exact = ExactHashStrategy;
let tenant = TenantScopedStrategy;
let msgs = r#"[{"role":"user","content":"hi"}]"#;
let i = input("gpt-4", msgs, "{}", Some("acme"), None);
let (ke, _) = exact.key_for(&i);
let (kt, _) = tenant.key_for(&i);
let (_, be) = exact.key_for(&i);
let (_, bt) = tenant.key_for(&i);
assert_ne!(be, bt, "bodies produced by different strategies must differ");
let _ = (ke, kt); }
}