use dashmap::DashMap;
use serde_json::Value;
const MAX_TRACKED_SESSIONS: usize = 4096;
pub const MAX_TRACKED_BLOCKS: usize = 64;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PrefixShape {
pub horizon: u32,
pub observations: u32,
pub changed_now: Vec<bool>,
pub changes: Vec<u32>,
}
impl PrefixShape {
pub fn is_stable(&self, index: usize) -> bool {
self.observations >= 2 && self.changes.get(index).copied() == Some(0)
}
pub fn is_volatile_now(&self, index: usize, min_changes: u32) -> bool {
self.changed_now.get(index).copied() == Some(true)
&& self
.changes
.get(index)
.copied()
.is_some_and(|c| c >= min_changes)
}
}
#[derive(Clone, Debug)]
struct SessionState {
prefix_hash: u64,
prefix_repeats: u32,
system_hashes: Vec<u64>,
system_changes: Vec<u32>,
observations: u32,
}
#[derive(Default)]
pub struct PrefixTracker {
sessions: DashMap<String, SessionState>,
}
impl PrefixTracker {
pub fn observe(&self, install: &str, session: &str, body: &Value) -> PrefixShape {
let key = format!("{install}\u{1}{session}");
let prefix_hash = hash_prefix(body);
let system_hashes = system_block_hashes(body);
let trackable =
self.sessions.contains_key(&key) || self.sessions.len() < MAX_TRACKED_SESSIONS;
let mut state = self
.sessions
.get(&key)
.map(|e| e.value().clone())
.unwrap_or(SessionState {
prefix_hash,
prefix_repeats: 0,
system_hashes: Vec::new(),
system_changes: Vec::new(),
observations: 0,
});
state.prefix_repeats = if state.observations > 0 && state.prefix_hash == prefix_hash {
state.prefix_repeats.saturating_add(1)
} else {
1
};
state.prefix_hash = prefix_hash;
let mut changed_now = vec![false; system_hashes.len()];
if state.observations > 0 && state.system_hashes.len() == system_hashes.len() {
for (i, h) in system_hashes.iter().enumerate() {
if state.system_hashes[i] != *h {
changed_now[i] = true;
if let Some(c) = state.system_changes.get_mut(i) {
*c = c.saturating_add(1);
}
}
}
} else if state.observations > 0 {
state.system_changes = vec![0; system_hashes.len()];
state.observations = 0;
}
if state.system_changes.len() != system_hashes.len() {
state.system_changes = vec![0; system_hashes.len()];
}
state.system_hashes = system_hashes;
state.observations = state.observations.saturating_add(1);
let shape = PrefixShape {
horizon: state.prefix_repeats,
observations: state.observations,
changed_now,
changes: state.system_changes.clone(),
};
if trackable {
self.sessions.insert(key, state);
}
shape
}
}
fn hash_prefix(body: &Value) -> u64 {
let mut h = FNV_OFFSET;
for key in ["tools", "system"] {
h = fnv(h, key.as_bytes());
if let Some(v) = body.get(key) {
h = fnv(h, v.to_string().as_bytes());
}
}
h
}
fn system_block_hashes(body: &Value) -> Vec<u64> {
let Some(blocks) = body.get("system").and_then(Value::as_array) else {
return Vec::new();
};
if blocks.len() > MAX_TRACKED_BLOCKS {
return Vec::new();
}
blocks
.iter()
.map(|b| fnv(FNV_OFFSET, b.to_string().as_bytes()))
.collect()
}
fn fnv(mut state: u64, bytes: &[u8]) -> u64 {
for &b in bytes {
state ^= u64::from(b);
state = state.wrapping_mul(FNV_PRIME);
}
state
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn sys(blocks: Vec<Value>) -> Value {
json!({ "model": "claude-opus-4-8", "system": blocks, "messages": [] })
}
fn text(t: &str) -> Value {
json!({ "type": "text", "text": t })
}
#[test]
fn a_first_request_has_horizon_one() {
let t = PrefixTracker::default();
let shape = t.observe("i", "s", &sys(vec![text("a")]));
assert_eq!(shape.horizon, 1, "one turn cannot amortise a write");
assert_eq!(shape.observations, 1);
assert!(
!shape.is_stable(0),
"one observation is not evidence of stability"
);
}
#[test]
fn an_unchanged_prefix_grows_the_horizon() {
let t = PrefixTracker::default();
let body = sys(vec![text("a"), text("b")]);
assert_eq!(t.observe("i", "s", &body).horizon, 1);
assert_eq!(t.observe("i", "s", &body).horizon, 2);
assert_eq!(t.observe("i", "s", &body).horizon, 3);
let shape = t.observe("i", "s", &body);
assert_eq!(shape.horizon, 4);
assert!(shape.is_stable(0) && shape.is_stable(1));
}
#[test]
fn a_changed_prefix_resets_the_horizon_to_one() {
let t = PrefixTracker::default();
t.observe("i", "s", &sys(vec![text("a")]));
t.observe("i", "s", &sys(vec![text("a")]));
let shape = t.observe("i", "s", &sys(vec![text("CHANGED")]));
assert_eq!(
shape.horizon, 1,
"the prefix we would cache is not the one we saw"
);
}
#[test]
fn messages_do_not_touch_the_horizon() {
let t = PrefixTracker::default();
let mut body = sys(vec![text("stable")]);
for i in 0..4 {
body["messages"] = json!([{ "role": "user", "content": format!("turn {i}") }]);
let shape = t.observe("i", "s", &body);
assert_eq!(shape.horizon, u32::try_from(i).unwrap() + 1);
}
}
#[test]
fn per_block_volatility_is_located_precisely() {
let t = PrefixTracker::default();
for i in 0..4 {
let body = sys(vec![
text("frozen preamble"),
text(&format!("current time: {i}")),
text("frozen tail"),
]);
t.observe("i", "s", &body);
}
let shape = t.observe(
"i",
"s",
&sys(vec![
text("frozen preamble"),
text("current time: 99"),
text("frozen tail"),
]),
);
assert!(shape.is_stable(0), "block 0 never changed");
assert!(!shape.is_stable(1), "block 1 is the volatile one");
assert!(shape.is_stable(2), "block 2 never changed");
assert!(
shape.is_volatile_now(1, 2),
"and it is changing on this very request"
);
assert!(!shape.is_volatile_now(0, 2));
}
#[test]
fn a_block_that_changed_once_is_not_yet_volatile_at_a_bar_of_two() {
let t = PrefixTracker::default();
t.observe("i", "s", &sys(vec![text("v1")]));
let shape = t.observe("i", "s", &sys(vec![text("v2")]));
assert!(shape.changed_now[0]);
assert!(!shape.is_volatile_now(0, 2), "one change is not a pattern");
}
#[test]
fn a_block_count_change_voids_every_per_index_claim() {
let t = PrefixTracker::default();
for _ in 0..5 {
t.observe("i", "s", &sys(vec![text("a"), text("b")]));
}
let shape = t.observe("i", "s", &sys(vec![text("a"), text("b"), text("c")]));
assert_eq!(shape.observations, 1, "the per-index record restarted");
assert!(
!shape.is_stable(0),
"no stability claim survives a re-shape"
);
}
#[test]
fn sessions_are_isolated_from_each_other() {
let t = PrefixTracker::default();
let body = sys(vec![text("a")]);
t.observe("i", "s1", &body);
t.observe("i", "s1", &body);
assert_eq!(t.observe("i", "s2", &body).horizon, 1);
assert_eq!(t.observe("i", "s1", &body).horizon, 3);
}
#[test]
fn a_string_system_yields_no_block_record_but_still_tracks_the_horizon() {
let t = PrefixTracker::default();
let body = json!({ "system": "a plain string prompt", "messages": [] });
t.observe("i", "s", &body);
let shape = t.observe("i", "s", &body);
assert_eq!(shape.horizon, 2);
assert!(shape.changes.is_empty());
assert!(!shape.is_stable(0));
}
#[test]
fn observation_is_deterministic() {
let body = sys(vec![text("a"), text("b")]);
let run = || {
let t = PrefixTracker::default();
t.observe("i", "s", &body);
t.observe("i", "s", &body);
t.observe("i", "s", &body)
};
let first = run();
for _ in 0..25 {
assert_eq!(run(), first);
}
}
#[test]
fn an_over_wide_system_array_is_not_tracked() {
let t = PrefixTracker::default();
let blocks: Vec<Value> = (0..MAX_TRACKED_BLOCKS + 1)
.map(|i| text(&i.to_string()))
.collect();
let shape = t.observe("i", "s", &sys(blocks));
assert!(
shape.changes.is_empty(),
"L-0 declines rather than acting on a partial view"
);
}
}