1 //! The engine-neutral prefix chain of one chat request.2 //!3 //! The chain is the only place where prompt text becomes cache keys. An engine4 //! codec never invents a key: it asks this module for the canonical order, the5 //! longest-first lookup list, and the lineage that scopes the tip table.6 7 use std::collections::BTreeMap;8 use std::io::{self, Read};9 10 use inf3r_proto::Value;11 use inf3r_proto::body::PartKind;12 use inf3r_sha256::Sha256;13 14 use crate::capability::{Part, Request};15 16 /// How many keys a chain may carry. The wire limit reserves one slot for the17 /// shared `[system + tools]` anchor.18 pub const TABLE_LIMIT: usize = 64;19 20 /// The canonical parts of one request and the keys derived from them.21 ///22 /// `all` is the rendering order: leading system parts, all tools, then the23 /// remaining conversation parts. `stable` is the length of the shared prefix.24 pub struct Chain<'a> {25 /// Every part in rendering order.26 pub all: Vec<Part<'a>>,27 /// The leading system parts and the tools.28 pub stable: Vec<Part<'a>>,29 /// The full scoped tip chain, one key per part.30 pub keys: Vec<[u8; 32]>,31 /// The prompt-only `[system + tools]` key, when the request has one.32 pub anchor: Option<[u8; 32]>,33 /// A stable conversation identity.34 pub lineage: [u8; 32],35 }36 37 impl<'a> Chain<'a> {38 /// Derives the canonical order, the tip chain, the anchor, and the lineage.39 pub fn new(req: &Request<'a>) -> io::Result<Self> {40 let (all, stable) = canonical_parts(req.parts);41 let template = template_seed(req);42 let tip_seed = seed(template.as_deref(), cache_key(req));43 let keys = chain_keys(&all, tip_seed)?;44 let anchor = anchor_key(req, &all, stable)?;45 let lineage = lineage_key(req)?;46 Ok(Chain {47 stable: all[..stable].to_vec(),48 all,49 keys,50 anchor,51 lineage,52 })53 }54 55 /// The longest-first lookup, reserving one slot for the anchor when the56 /// tip chain is at the wire bound.57 pub fn lookup_keys(&self) -> Vec<[u8; 32]> {58 let mut keys: Vec<[u8; 32]> = self59 .keys60 .iter()61 .rev()62 .take(TABLE_LIMIT - 1)63 .copied()64 .collect();65 if let Some(anchor) = self.anchor66 && !keys.contains(&anchor)67 {68 keys.push(anchor);69 }70 keys71 }72 73 /// The tip of the full prompt, when it has one.74 pub fn tip(&self) -> Option<[u8; 32]> {75 self.keys.last().copied()76 }77 }78 79 /// The canonical order: leading system parts, all tools, then the rest.80 ///81 /// Returns the reordered parts and the length of the stable prefix. A tool82 /// that appears after a user message still belongs to the stable prefix; the83 /// caller declared it as a tool, not as conversation text.84 pub fn canonical_parts<'a>(parts: &'a [Part<'a>]) -> (Vec<Part<'a>>, usize) {85 let mut used = vec![false; parts.len()];86 let mut all = Vec::with_capacity(parts.len());87 for (index, part) in parts.iter().enumerate() {88 if part.role != Some("system") {89 break;90 }91 all.push(*part);92 used[index] = true;93 }94 for (index, part) in parts.iter().enumerate() {95 if !used[index] && part.role == Some("tools") {96 all.push(*part);97 used[index] = true;98 }99 }100 let stable = all.len();101 for (index, part) in parts.iter().enumerate() {102 if !used[index] {103 all.push(*part);104 }105 }106 (all, stable)107 }108 109 /// The client's `prompt_cache_key`, when it sent one.110 pub fn cache_key<'a>(req: &'a Request<'_>) -> Option<&'a str> {111 match req.params.get("cache_key") {112 Some(Value::Text(key)) => Some(key.as_str()),113 _ => None,114 }115 }116 117 /// The chat-template parameters that change the rendered prompt.118 pub fn template_seed(req: &Request<'_>) -> Option<Vec<u8>> {119 let value = req.params.get("chat_template_kwargs")?;120 let json = inf3r_proto::mirror::to_json(value);121 Some(inf3r_json::to_string(&json).into_bytes())122 }123 124 /// A stable conversation identity.125 ///126 /// A client that sends `prompt_cache_key` names the conversation. Without one127 /// the first conversation part is the stable identity, so anchor promotion128 /// still works across turns of the same prompt.129 pub fn lineage_key(req: &Request<'_>) -> io::Result<[u8; 32]> {130 let mut digest = Sha256::new();131 digest.update(b"inf3r-lineage-v1");132 if let Some(key) = cache_key(req) {133 digest.update(b"client\0");134 digest.update(key.as_bytes());135 digest.update(b"\0");136 return Ok(digest.finish());137 }138 let (all, stable) = canonical_parts(req.parts);139 let anchor = anchor_key(req, &all, stable)?;140 if let Some(part) = all.get(stable) {141 let mut part_digest = Sha256::new();142 part_digest.update(b"inf3r-lineage-v1-part");143 part_digest.update(&anchor.unwrap_or([0; 32]));144 hash_into(&mut part_digest, part)?;145 return Ok(part_digest.finish());146 }147 if let Some(anchor) = anchor {148 digest.update(b"anchor\0");149 digest.update(&anchor);150 return Ok(digest.finish());151 }152 digest.update(b"empty\0");153 Ok(digest.finish())154 }155 156 /// The prompt-only `[system + tools]` boundary, when the request has one.157 pub fn anchor_key(158 req: &Request<'_>,159 all: &[Part<'_>],160 stable: usize,161 ) -> io::Result<Option<[u8; 32]>> {162 if stable == 0 {163 return Ok(None);164 }165 let anchor_seed = seed(template_seed(req).as_deref(), None);166 Ok(chain_keys(&all[..stable], anchor_seed)?.last().copied())167 }168 169 /// Domain separation for the tip chain. The client cache key scopes the tip,170 /// not the shared anchor.171 pub fn seed(template: Option<&[u8]>, cache_key: Option<&str>) -> [u8; 32] {172 let mut digest = Sha256::new();173 digest.update(b"inf3r-prefix-v3");174 if let Some(template) = template {175 digest.update(b"template\0");176 digest.update(template);177 digest.update(b"\0");178 }179 if let Some(key) = cache_key {180 digest.update(b"cache-key\0");181 digest.update(key.as_bytes());182 digest.update(b"\0");183 }184 digest.finish()185 }186 187 /// One key per part. Assistant text is the post-turn boundary: it chains to the188 /// key that the previous turn saved, so the next request can find that tip.189 pub fn chain_keys(parts: &[Part<'_>], seed: [u8; 32]) -> io::Result<Vec<[u8; 32]>> {190 let mut previous = seed;191 let mut keys = Vec::with_capacity(parts.len());192 for (index, part) in parts.iter().enumerate() {193 if index > 0 && part.kind == PartKind::Text && part.role == Some("assistant") {194 previous = key_after(previous, &text_value(part));195 } else {196 let mut digest = Sha256::new();197 digest.update(b"inf3r-prefix-v3");198 digest.update(&previous);199 hash_into(&mut digest, part)?;200 previous = digest.finish();201 }202 keys.push(previous);203 }204 Ok(keys)205 }206 207 /// Hashes every part field that changes the prompt identity, including the208 /// bytes behind a descriptor.209 pub fn hash_into(digest: &mut Sha256, part: &Part<'_>) -> io::Result<()> {210 digest.update(part_kind_name(part.kind).as_bytes());211 digest.update(b"\0");212 digest.update(part.mime.as_bytes());213 digest.update(b"\0");214 if let Some(role) = part.role {215 digest.update(role.as_bytes());216 }217 digest.update(b"\0");218 digest.update(&part.len.to_le_bytes());219 // Tools, response formats, images and audio are part of the prompt220 // identity. A checkpoint that ignored them could be restored into a221 // different request.222 let mut reader = part.reader();223 let mut buffer = [0u8; 64 * 1024];224 loop {225 let read = reader.read(&mut buffer)?;226 if read == 0 {227 break;228 }229 digest.update(&buffer[..read]);230 }231 Ok(())232 }233 234 /// The post-turn key: the prior prefix plus the assistant text.235 pub fn key_after(prefix: [u8; 32], output: &str) -> [u8; 32] {236 let mut digest = Sha256::new();237 digest.update(b"inf3r-prefix-v3");238 digest.update(&prefix);239 digest.update(b"assistant\0");240 digest.update(output.as_bytes());241 digest.update(b"\0");242 digest.finish()243 }244 245 /// The wire name of a part kind. It is part of the hash, not a log label.246 pub fn part_kind_name(kind: PartKind) -> &'static str {247 match kind {248 PartKind::Text => "text",249 PartKind::Image => "image",250 PartKind::Audio => "audio",251 PartKind::Video => "video",252 PartKind::Tokens => "tokens",253 PartKind::Json => "json",254 }255 }256 257 fn text_value(part: &Part<'_>) -> String {258 if let Some(text) = part.text() {259 return text.to_string();260 }261 let mut bytes = Vec::new();262 let _ = part.reader().take(part.len).read_to_end(&mut bytes);263 String::from_utf8_lossy(&bytes).into_owned()264 }265 266 /// The per-lineage tips, bounded so a long-lived process cannot grow without267 /// limit. A tip is the only key that a later turn may supersede.268 #[derive(Default)]269 pub struct TipTable {270 tips: BTreeMap<[u8; 32], [u8; 32]>,271 order: std::collections::VecDeque<[u8; 32]>,272 }273 274 impl TipTable {275 /// Records the tip of one lineage and returns the tip it replaces.276 pub fn note(&mut self, lineage: [u8; 32], tip: [u8; 32]) -> Option<[u8; 32]> {277 let previous = self.tips.insert(lineage, tip);278 if previous.is_none() {279 self.order.push_back(lineage);280 while self.order.len() > TABLE_LIMIT {281 if let Some(old) = self.order.pop_front() {282 self.tips.remove(&old);283 }284 }285 }286 previous287 }288 289 /// Puts the previous tip back when its save failed.290 pub fn rollback(&mut self, lineage: [u8; 32], tip: [u8; 32], previous: Option<[u8; 32]>) {291 if self.tips.get(&lineage) != Some(&tip) {292 return;293 }294 match previous {295 Some(previous) => {296 self.tips.insert(lineage, previous);297 }298 None => {299 self.tips.remove(&lineage);300 if let Some(index) = self.order.iter().position(|item| *item == lineage) {301 self.order.remove(index);302 }303 }304 }305 }306 307 /// The current tip of one lineage.308 pub fn get(&self, lineage: &[u8; 32]) -> Option<[u8; 32]> {309 self.tips.get(lineage).copied()310 }311 312 /// The number of live lineages.313 pub fn len(&self) -> usize {314 self.tips.len()315 }316 317 /// Whether no lineage has a tip.318 pub fn is_empty(&self) -> bool {319 self.tips.is_empty()320 }321 }322 323 /// Anchors already attempted in this process. A long conversation must not324 /// re-checkpoint the same shared prefix every turn.325 #[derive(Default)]326 pub struct AnchorSet {327 seen: std::collections::VecDeque<[u8; 32]>,328 }329 330 impl AnchorSet {331 /// Claims an anchor. The first caller gets `true`; everyone else gets332 /// `false` until the anchor falls out of the bounded table.333 pub fn claim(&mut self, anchor: [u8; 32]) -> bool {334 if self.seen.contains(&anchor) {335 return false;336 }337 self.seen.push_back(anchor);338 while self.seen.len() > TABLE_LIMIT {339 self.seen.pop_front();340 }341 true342 }343 }344 345 #[cfg(test)]346 mod tests {347 use super::*;348 use crate::capability::{Part, PartBody, Request};349 use inf3r_proto::body::PartKind;350 351 fn text<'a>(role: &'a str, body: &'a str) -> Part<'a> {352 Part {353 kind: PartKind::Text,354 mime: "text/plain",355 role: Some(role),356 len: body.len() as u64,357 body: PartBody::Inline(body.as_bytes()),358 }359 }360 361 fn tools<'a>(body: &'a str) -> Part<'a> {362 Part {363 kind: PartKind::Json,364 mime: "application/json",365 role: Some("tools"),366 len: body.len() as u64,367 body: PartBody::Inline(body.as_bytes()),368 }369 }370 371 fn request<'a>(parts: &'a [Part<'a>], params: &'a Value) -> Request<'a> {372 Request {373 request_id: "test",374 model: "mock",375 capability: "chat",376 parts,377 params,378 }379 }380 381 fn cache_key_param(key: &str) -> Value {382 Value::map([(Value::Text("cache_key".into()), Value::Text(key.into()))])383 }384 385 #[test]386 fn every_part_kind_and_tool_payload_changes_the_prefix() {387 let text = text("user", "hi");388 let tools_a = tools(r#"{"tools":["a"]}"#);389 let tools_b = tools(r#"{"tools":["b"]}"#);390 let params = Value::Null;391 let one_parts = [text];392 let a_parts = [text, tools_a];393 let b_parts = [text, tools_b];394 let one = Chain::new(&request(&one_parts, ¶ms)).unwrap();395 let a = Chain::new(&request(&a_parts, ¶ms)).unwrap();396 let b = Chain::new(&request(&b_parts, ¶ms)).unwrap();397 assert_ne!(one.keys[0], a.keys[0]);398 assert_ne!(a.keys[0], b.keys[0]);399 }400 401 #[test]402 fn a_prompt_cache_key_scopes_the_tip_but_not_the_anchor() {403 let system = text("system", "be brief");404 let user = text("user", "hi");405 let params_a = cache_key_param("conversation-a");406 let params_b = cache_key_param("conversation-b");407 let parts = [system, user];408 let a = Chain::new(&request(&parts, ¶ms_a)).unwrap();409 let b = Chain::new(&request(&parts, ¶ms_b)).unwrap();410 assert_ne!(a.keys[0], b.keys[0]);411 assert_eq!(a.anchor, b.anchor);412 assert_ne!(a.lineage, b.lineage);413 }414 415 #[test]416 fn conversations_that_share_system_and_tools_share_an_anchor() {417 let system = text("system", "be brief");418 let user_a = text("user", "alpha");419 let user_b = text("user", "beta");420 let tool = tools(r#"{"tools":[{"type":"function"}]}"#);421 let params_a = cache_key_param("conversation-a");422 let params_b = cache_key_param("conversation-b");423 let parts_a = [system, user_a, tool];424 let parts_b = [system, user_b, tool];425 let a = Chain::new(&request(&parts_a, ¶ms_a)).unwrap();426 let b = Chain::new(&request(&parts_b, ¶ms_b)).unwrap();427 assert_eq!(a.anchor, b.anchor);428 assert_ne!(a.keys.last(), b.keys.last());429 }430 431 #[test]432 fn a_different_stable_prefix_is_a_different_lineage_without_a_client_key() {433 let system_a = text("system", "be brief");434 let system_b = text("system", "be verbose");435 let user = text("user", "same");436 let params = Value::Null;437 let parts_a = [system_a, user];438 let parts_b = [system_b, user];439 let a = Chain::new(&request(&parts_a, ¶ms)).unwrap();440 let b = Chain::new(&request(&parts_b, ¶ms)).unwrap();441 assert_ne!(a.anchor, b.anchor);442 assert_ne!(a.lineage, b.lineage);443 }444 445 #[test]446 fn tools_move_before_the_conversation_but_response_format_does_not() {447 let system = text("system", "be brief");448 let user = text("user", "hi");449 let tool = tools(r#"{"tools":[]}"#);450 let format = Part {451 kind: PartKind::Json,452 mime: "application/json",453 role: Some("response_format"),454 len: 4,455 body: PartBody::Inline(b"json"),456 };457 let params = Value::Null;458 let parts = [system, user, tool, format];459 let chain = Chain::new(&request(&parts, ¶ms)).unwrap();460 let roles: Vec<_> = chain.all.iter().map(|part| part.role).collect();461 assert_eq!(462 roles,463 vec![464 Some("system"),465 Some("tools"),466 Some("user"),467 Some("response_format")468 ]469 );470 assert_eq!(chain.stable.len(), 2);471 }472 473 #[test]474 fn assistant_text_chains_to_the_post_turn_key() {475 let system = text("system", "be brief");476 let user = text("user", "hi");477 let params = Value::Null;478 let first_parts = [system, user];479 let first = Chain::new(&request(&first_parts, ¶ms)).unwrap();480 let after = key_after(*first.keys.last().unwrap(), "hello");481 let assistant = text("assistant", "hello");482 let second_parts = [system, user, assistant];483 let second = Chain::new(&request(&second_parts, ¶ms)).unwrap();484 assert_eq!(second.keys.last().copied(), Some(after));485 }486 487 #[test]488 fn a_long_chain_still_looks_up_the_anchor() {489 let system = text("system", "be brief");490 let user = text("user", "u");491 let mut parts = vec![system];492 parts.extend(std::iter::repeat_n(user, 70));493 let params = Value::Null;494 let chain = Chain::new(&request(&parts, ¶ms)).unwrap();495 assert_eq!(chain.keys.len(), 71);496 let lookup = chain.lookup_keys();497 assert_eq!(lookup.len(), 64);498 assert_eq!(lookup.last().copied(), chain.anchor);499 }500 501 #[test]502 fn one_lineage_does_not_supersede_anothers_tip() {503 let mut tips = TipTable::default();504 let a = [1; 32];505 let b = [2; 32];506 let a1 = [3; 32];507 let b1 = [4; 32];508 assert_eq!(tips.note(a, a1), None);509 assert_eq!(tips.note(b, b1), None);510 assert_eq!(tips.note(a, [5; 32]), Some(a1));511 assert_eq!(tips.note(b, [6; 32]), Some(b1));512 assert_eq!(tips.get(&a), Some([5; 32]));513 assert_eq!(tips.get(&b), Some([6; 32]));514 }515 516 #[test]517 fn a_failed_save_rolls_the_tip_back() {518 let mut tips = TipTable::default();519 let lineage = [1; 32];520 let old = [2; 32];521 let new = [3; 32];522 assert_eq!(tips.note(lineage, old), None);523 assert_eq!(tips.note(lineage, new), Some(old));524 tips.rollback(lineage, new, Some(old));525 assert_eq!(tips.get(&lineage), Some(old));526 tips.rollback(lineage, old, None);527 assert!(tips.is_empty());528 }529 530 #[test]531 fn the_tip_table_is_bounded() {532 let mut tips = TipTable::default();533 for index in 0..=TABLE_LIMIT {534 let mut lineage = [0; 32];535 lineage[0] = index as u8;536 tips.note(lineage, lineage);537 }538 assert_eq!(tips.len(), TABLE_LIMIT);539 assert_eq!(tips.get(&[0; 32]), None);540 }541 542 #[test]543 fn an_anchor_is_claimed_once() {544 let mut anchors = AnchorSet::default();545 assert!(anchors.claim([1; 32]));546 assert!(!anchors.claim([1; 32]));547 assert!(anchors.claim([2; 32]));548 }549 }