use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use serde_json::Value;
pub const DEFAULT_CAPACITY: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PrefixHash(u64, u64);
struct PrefixHasher {
lo: std::collections::hash_map::DefaultHasher,
hi: std::collections::hash_map::DefaultHasher,
}
impl PrefixHasher {
fn new(salt: &[u8]) -> Self {
let mut lo = std::collections::hash_map::DefaultHasher::new();
let mut hi = std::collections::hash_map::DefaultHasher::new();
salt.hash(&mut lo);
salt.hash(&mut hi);
0xA5A5_5A5A_u64.hash(&mut hi);
Self { lo, hi }
}
fn push(&mut self, msg_bytes: &[u8]) -> PrefixHash {
(msg_bytes.len() as u64).hash(&mut self.lo);
msg_bytes.hash(&mut self.lo);
(msg_bytes.len() as u64).hash(&mut self.hi);
msg_bytes.hash(&mut self.hi);
PrefixHash(self.lo.finish(), self.hi.finish())
}
}
pub struct Memo {
cap: usize,
inner: Mutex<Store>,
}
#[derive(Default)]
struct Store {
live: HashMap<PrefixHash, Value>,
prev: HashMap<PrefixHash, Value>,
}
impl Memo {
pub fn with_capacity(cap: usize) -> Self {
Self {
cap,
inner: Mutex::new(Store::default()),
}
}
fn get(&self, key: PrefixHash) -> Option<Value> {
let mut store = self.inner.lock().ok()?;
if let Some(v) = store.live.get(&key) {
return Some(v.clone());
}
if let Some(v) = store.prev.get(&key).cloned() {
store.live.insert(key, v.clone());
return Some(v);
}
None
}
fn put(&self, key: PrefixHash, content: Value) {
if self.cap == 0 {
return;
}
let Ok(mut store) = self.inner.lock() else {
return;
};
if store.live.len() >= self.cap {
let full = std::mem::take(&mut store.live);
store.prev = full;
}
store.live.insert(key, content);
}
pub fn len(&self) -> usize {
let Ok(store) = self.inner.lock() else {
return 0;
};
let mut n = store.live.len();
for k in store.prev.keys() {
if !store.live.contains_key(k) {
n += 1;
}
}
n
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
fn message_bytes(msg: &Value) -> Vec<u8> {
serde_json::to_vec(msg).unwrap_or_default()
}
fn conversation(req: &Value) -> Option<(&'static str, &Vec<Value>)> {
for key in ["messages", "input", "contents"] {
if let Some(arr) = req.get(key).and_then(Value::as_array) {
return Some((key, arr));
}
}
None
}
struct PrefixPlan {
entries: Vec<(usize, PrefixHash, Value)>,
offset: usize,
key: &'static str,
}
fn plan(salt: &[u8], original: &Value, compressed: &Value) -> Option<PrefixPlan> {
let (_, orig_msgs) = conversation(original)?;
let (key, comp_msgs) = conversation(compressed)?;
let role0 = |arr: &[Value]| -> Option<String> {
arr.first()
.and_then(|m| m.get("role"))
.and_then(Value::as_str)
.map(str::to_string)
};
let offset = match comp_msgs.len().checked_sub(orig_msgs.len()) {
Some(0) => 0usize,
Some(1)
if role0(comp_msgs).as_deref() == Some("system")
&& role0(orig_msgs).as_deref() != Some("system") =>
{
1
}
_ => return None,
};
let mut hasher = PrefixHasher::new(salt);
let mut entries = Vec::with_capacity(orig_msgs.len());
for orig in orig_msgs.iter() {
let i = entries.len();
let h = hasher.push(&message_bytes(orig));
if let Some(content) = comp_msgs.get(i + offset).and_then(|m| m.get("content")) {
entries.push((i, h, content.clone()));
} else {
break;
}
}
Some(PrefixPlan {
entries,
offset,
key,
})
}
pub fn apply(memo: &Memo, salt: &[u8], original: &Value, compressed: &mut Value) -> usize {
if memo.cap == 0 {
return 0;
}
let Some(plan) = plan(salt, original, compressed) else {
return 0;
};
let offset = plan.offset;
let mut reused: Vec<(usize, Value)> = Vec::new();
for (idx, h, _) in &plan.entries {
match memo.get(*h) {
Some(stored) => reused.push((*idx, stored)),
None => break,
}
}
let reused_count = reused.len();
if reused_count > 0
&& let Some(comp_msgs) = compressed.get_mut(plan.key).and_then(Value::as_array_mut)
{
for (idx, stored) in reused {
if let Some(slot) = comp_msgs.get_mut(idx + offset)
&& let Some(obj) = slot.as_object_mut()
{
obj.insert("content".to_string(), stored);
}
}
}
for (idx, h, fresh_content) in plan.entries {
let to_store = compressed
.get(plan.key)
.and_then(Value::as_array)
.and_then(|a| a.get(idx + offset))
.and_then(|m| m.get("content"))
.cloned()
.unwrap_or(fresh_content);
memo.put(h, to_store);
}
reused_count
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn fake_compress(req: &Value) -> Value {
let mut out = req.clone();
let query = req
.get("messages")
.and_then(Value::as_array)
.and_then(|a| a.last())
.and_then(|m| m.get("content"))
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
if let Some(msgs) = out.get_mut("messages").and_then(Value::as_array_mut) {
for m in msgs.iter_mut() {
if let Some(c) = m.get("content").and_then(Value::as_str) {
let first = c.split('.').next().unwrap_or(c).to_string();
let shaped = format!("{first} <q{}>", query.len());
if let Some(obj) = m.as_object_mut() {
obj.insert("content".to_string(), Value::String(shaped));
}
}
}
}
out
}
fn user(content: &str) -> Value {
json!({"role": "user", "content": content})
}
fn prefix_contents(compressed: &Value, n: usize) -> Vec<String> {
compressed
.get("messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.take(n)
.map(|m| m.get("content").unwrap().to_string())
.collect()
}
#[test]
fn different_salt_never_reuses_across_contexts() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let a = json!({"messages": [
user("the revenue report grew across all regions. lots of detail here"),
user("what was the revenue"),
]});
let mut ca = fake_compress(&a);
assert_eq!(apply(&memo, b"ctx-rag", &a, &mut ca), 0); let b = json!({"messages": [
user("the revenue report grew across all regions. lots of detail here"),
user("what was the revenue"),
user("now also tell me about costs"),
]});
let mut cb = fake_compress(&b);
assert_eq!(
apply(&memo, b"ctx-agent", &b, &mut cb),
0,
"a different context salt must not reuse the other context's bytes"
);
let mut cb2 = fake_compress(&b);
assert_eq!(apply(&memo, b"ctx-rag", &b, &mut cb2), 2);
}
#[test]
fn headline_two_turn_prefix_is_byte_identical() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let a = json!({"messages": [
user("the revenue report grew across all regions. lots of detail here"),
user("what was the revenue"),
]});
let mut ca = fake_compress(&a);
assert_eq!(apply(&memo, b"t", &a, &mut ca), 0);
let a_msg0 = prefix_contents(&ca, 1);
let b = json!({"messages": [
user("the revenue report grew across all regions. lots of detail here"),
user("what was the revenue"),
user("now also tell me about costs and the very long winded margin analysis"),
]});
let cb_no_memo = fake_compress(&b);
let b_msg0_fresh = prefix_contents(&cb_no_memo, 1);
assert_ne!(
a_msg0, b_msg0_fresh,
"precondition: the stateless compressor diverges on the old message across turns \
(otherwise the memo would be testing nothing)"
);
let mut cb = fake_compress(&b);
let reused = apply(&memo, b"t", &b, &mut cb);
assert_eq!(reused, 2, "both shared messages frozen from turn A");
assert_eq!(
prefix_contents(&ca, 2),
prefix_contents(&cb, 2),
"frozen prefix must be byte-identical to last turn (provider cache stays warm)"
);
let suffix = cb.get("messages").and_then(Value::as_array).unwrap()[2]
.get("content")
.unwrap()
.to_string();
assert!(
suffix.contains("costs"),
"the new turn carries fresh content: {suffix}"
);
}
#[test]
fn third_turn_extends_the_frozen_prefix_transitively() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let base = vec![
user("alpha context paragraph one. detail detail detail"),
user("beta question about alpha"),
];
let a = json!({ "messages": base });
let mut ca = fake_compress(&a);
apply(&memo, b"t", &a, &mut ca);
let mut b_msgs = base.clone();
b_msgs.push(user("gamma follow up question number two"));
let b = json!({ "messages": b_msgs.clone() });
let mut cb = fake_compress(&b);
assert_eq!(apply(&memo, b"t", &b, &mut cb), 2);
let mut c_msgs = b_msgs.clone();
c_msgs.push(user(
"delta a third follow up that is appended at the very end",
));
let c = json!({ "messages": c_msgs });
let mut cc = fake_compress(&c);
assert_eq!(
apply(&memo, b"t", &c, &mut cc),
3,
"the frozen prefix extends transitively as the conversation grows"
);
assert_eq!(prefix_contents(&cc, 3), prefix_contents(&cb, 3));
assert_eq!(prefix_contents(&cb, 2), prefix_contents(&ca, 2));
}
#[test]
fn divergent_history_does_not_reuse() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let a = json!({"messages": [
user("original first message about the budget"),
user("a question"),
]});
let mut ca = fake_compress(&a);
apply(&memo, b"t", &a, &mut ca);
let b = json!({"messages": [
user("original first message about the BUDGET"), user("a question"),
user("a new appended turn"),
]});
let mut cb = fake_compress(&b);
assert_eq!(
apply(&memo, b"t", &b, &mut cb),
0,
"a changed old message busts the prefix → no reuse (correctness over caching)"
);
let fresh = fake_compress(&b);
assert_eq!(prefix_contents(&cb, 2), prefix_contents(&fresh, 2));
}
#[test]
fn appended_turn_after_changed_prefix_does_not_reuse_a_later_match() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let a = json!({"messages": [user("AAAA first"), user("BBBB second shared verbatim")]});
let mut ca = fake_compress(&a);
apply(&memo, b"t", &a, &mut ca);
let b =
json!({"messages": [user("ZZZZ first changed"), user("BBBB second shared verbatim")]});
let mut cb = fake_compress(&b);
assert_eq!(
apply(&memo, b"t", &b, &mut cb),
0,
"message 1 is identical but message 0 diverged → no contiguous prefix from the front"
);
}
#[test]
fn memory_cap_evicts_and_stays_bounded() {
let memo = Memo::with_capacity(4);
for i in 0..1000 {
let req = json!({"messages": [user(&format!("unique conversation number {i}"))]});
let mut c = fake_compress(&req);
apply(&memo, b"t", &req, &mut c);
}
assert!(
memo.len() <= 8,
"generation eviction bounds the memo at 2×cap; got {}",
memo.len()
);
assert!(!memo.is_empty(), "but it is not empty after inserts");
}
#[test]
fn zero_capacity_is_an_inert_off_switch() {
let memo = Memo::with_capacity(0);
let a = json!({"messages": [user("first"), user("second")]});
let mut ca = fake_compress(&a);
assert_eq!(apply(&memo, b"t", &a, &mut ca), 0);
let b = json!({"messages": [user("first"), user("second"), user("third")]});
let mut cb = fake_compress(&b);
assert_eq!(
apply(&memo, b"t", &b, &mut cb),
0,
"cap 0 never reuses or stores — a hard off-switch (flag off ⇒ stateless behavior)"
);
assert!(memo.is_empty());
}
#[test]
fn leading_system_injection_offsets_alignment() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let compress_with_system = |req: &Value| -> Value {
let mut out = fake_compress(req);
if let Some(msgs) = out.get_mut("messages").and_then(Value::as_array_mut) {
msgs.insert(0, json!({"role": "system", "content": "be terse"}));
}
out
};
let a = json!({"messages": [user("context here. plenty of it"), user("the query")]});
let mut ca = compress_with_system(&a);
assert_eq!(apply(&memo, b"t", &a, &mut ca), 0);
let b = json!({"messages": [
user("context here. plenty of it"),
user("the query"),
user("a brand new appended turn changing the query bias entirely"),
]});
let mut cb = compress_with_system(&b);
assert_eq!(
apply(&memo, b"t", &b, &mut cb),
2,
"alignment across the injected leading system message freezes both shared turns"
);
let conv = |c: &Value| -> Vec<String> {
c.get("messages").and_then(Value::as_array).unwrap()[1..=2]
.iter()
.map(|m| m.get("content").unwrap().to_string())
.collect()
};
assert_eq!(
conv(&ca),
conv(&cb),
"frozen turns byte-identical across the offset"
);
assert_eq!(
cb.get("messages").and_then(Value::as_array).unwrap()[0]
.get("content")
.unwrap(),
"be terse"
);
}
#[test]
fn unrecognized_shape_falls_back_without_panic() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let weird = json!({"prompt": "just a string completion request", "max_tokens": 5});
let mut c = weird.clone();
assert_eq!(apply(&memo, b"t", &weird, &mut c), 0);
assert_eq!(c, weird, "untouched when there's no conversation array");
}
#[test]
fn message_count_mismatch_falls_back() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let original = json!({"messages": [user("a"), user("b"), user("c")]});
let mut compressed = json!({"messages": [user("a"), user("c")]});
assert_eq!(apply(&memo, b"t", &original, &mut compressed), 0);
}
#[test]
fn responses_input_shape_is_supported() {
let memo = Memo::with_capacity(DEFAULT_CAPACITY);
let a = json!({"input": [
{"role": "user", "content": "first turn long context here"},
{"role": "user", "content": "the query"},
]});
let comp = |req: &Value| -> Value {
let mut out = req.clone();
if let Some(arr) = out.get_mut("input").and_then(Value::as_array_mut) {
for (i, m) in arr.iter_mut().enumerate() {
if let Some(obj) = m.as_object_mut() {
obj.insert("content".to_string(), json!(format!("c{i}")));
}
}
}
out
};
let mut ca = comp(&a);
assert_eq!(apply(&memo, b"t", &a, &mut ca), 0);
let b = json!({"input": [
{"role": "user", "content": "first turn long context here"},
{"role": "user", "content": "the query"},
{"role": "user", "content": "appended turn"},
]});
let mut cb = comp(&b);
assert_eq!(
apply(&memo, b"t", &b, &mut cb),
2,
"the `input` (Responses) shape is memoized like `messages`"
);
}
}