Skip to main content

kute_types/
input.rs

1use crate::{KuteError, Result, Version, VocabularyId};
2use serde::{Deserialize, Serialize};
3use std::io::{Read, Write};
4
5/// What kind of information a payload carries. Declared by the adapter.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[serde(rename_all = "snake_case")]
8pub enum Modality {
9    Text,
10    Binary,
11    Structured,
12    Events,
13    Other,
14}
15
16/// The two canonical shapes a tokenizer accepts (ADR-0004).
17///
18/// `Bytes` covers text, binary and serialized structured data. `Symbols` is an
19/// ordered sequence of opaque names (events, opcodes, gates) for information
20/// whose units are not bytes.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum Payload {
23    Bytes(Vec<u8>),
24    Symbols(Vec<String>),
25}
26
27impl Payload {
28    pub fn kind(&self) -> PayloadKind {
29        match self {
30            Payload::Bytes(_) => PayloadKind::Bytes,
31            Payload::Symbols(_) => PayloadKind::Symbols,
32        }
33    }
34
35    /// Number of units: bytes or symbols.
36    pub fn len(&self) -> usize {
37        match self {
38            Payload::Bytes(b) => b.len(),
39            Payload::Symbols(s) => s.len(),
40        }
41    }
42
43    pub fn is_empty(&self) -> bool {
44        self.len() == 0
45    }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum PayloadKind {
51    Bytes,
52    Symbols,
53}
54
55/// Adapter output and tokenizer input: one record of canonical information.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct CanonicalInput {
58    pub modality: Modality,
59    pub payload: Payload,
60}
61
62impl CanonicalInput {
63    pub fn bytes(modality: Modality, bytes: impl Into<Vec<u8>>) -> Self {
64        Self { modality, payload: Payload::Bytes(bytes.into()) }
65    }
66
67    pub fn text(text: &str) -> Self {
68        Self::bytes(Modality::Text, text.as_bytes())
69    }
70
71    pub fn symbols<I, S>(symbols: I) -> Self
72    where
73        I: IntoIterator<Item = S>,
74        S: Into<String>,
75    {
76        Self {
77            modality: Modality::Events,
78            payload: Payload::Symbols(symbols.into_iter().map(Into::into).collect()),
79        }
80    }
81}
82
83/// Token ids scoped to the exact vocabulary that produced them.
84///
85/// Ids from different vocabularies are never interchangeable, so a sequence
86/// always travels with the vocabulary id, version and content digest.
87#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
88pub struct TokenSequence {
89    pub vocabulary_id: VocabularyId,
90    pub vocabulary_version: Version,
91    pub vocabulary_digest: String,
92    pub modality: Modality,
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub adapter: Option<String>,
95    pub ids: Vec<u32>,
96    /// Symbols the vocabulary does not contain, carried literally. An id of
97    /// `vocabulary length + i` stands for `escapes[i]`. Empty unless the
98    /// sequence was encoded with [`UnknownPolicy::Escape`].
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub escapes: Vec<String>,
101}
102
103/// What an encoder does with a symbol its frozen vocabulary does not contain.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub enum UnknownPolicy {
107    /// Refuse the input.
108    #[default]
109    Strict,
110    /// Carry the symbol literally in the sequence's escape table. The
111    /// vocabulary is not changed and decoding returns the input exactly.
112    Escape,
113}
114
115impl UnknownPolicy {
116    pub fn parse(name: &str) -> Result<Self> {
117        match name {
118            "strict" => Ok(Self::Strict),
119            "escape" => Ok(Self::Escape),
120            other => Err(KuteError::InvalidConfig(format!("unknown-symbol policy {other:?}; expected strict or escape"))),
121        }
122    }
123}
124
125/// Most escaped symbols one sequence may carry.
126pub const MAX_ESCAPES: usize = 65_536;
127
128#[derive(Serialize, Deserialize)]
129struct ContainerHeader {
130    vocabulary_id: VocabularyId,
131    vocabulary_version: Version,
132    vocabulary_digest: String,
133    modality: Modality,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    adapter: Option<String>,
136    count: u64,
137    #[serde(default, skip_serializing_if = "Vec::is_empty")]
138    escapes: Vec<String>,
139    /// Format 2 only: width of each id in the compressed body, 1 to 4 bytes.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    id_bytes: Option<u8>,
142}
143
144const MAGIC: &[u8; 5] = b"KUTE\x01";
145/// Format 2: the ids are fixed-width little-endian integers in a zlib stream.
146const MAGIC_COMPRESSED: &[u8; 5] = b"KUTE\x02";
147/// Headers without escaped symbols stay far below this; the room is for the
148/// escape table.
149const MAX_HEADER: usize = 4 * 1024 * 1024;
150/// DEFLATE cannot expand by more than about 1032 to 1, so a body that claims
151/// more output than this for its size is rejected before any is produced.
152const MAX_INFLATE_RATIO: u64 = 1040;
153/// Largest buffer reserved on the word of a container header alone.
154const MAX_PREALLOCATE: u64 = 1 << 20;
155
156impl TokenSequence {
157    /// Serialize to the `.kute` container: magic, little-endian header length,
158    /// JSON header, then LEB128 varint token ids.
159    pub fn to_bytes(&self) -> Result<Vec<u8>> {
160        let mut out = self.start_container(MAGIC, None, self.ids.len() * 2)?;
161        for &id in &self.ids {
162            let mut v = id;
163            loop {
164                let byte = (v & 0x7f) as u8;
165                v >>= 7;
166                if v == 0 {
167                    out.push(byte);
168                    break;
169                }
170                out.push(byte | 0x80);
171            }
172        }
173        Ok(out)
174    }
175
176    fn start_container(&self, magic: &[u8; 5], id_bytes: Option<u8>, body_hint: usize) -> Result<Vec<u8>> {
177        let header = serde_json::to_vec(&ContainerHeader {
178            vocabulary_id: self.vocabulary_id.clone(),
179            vocabulary_version: self.vocabulary_version.clone(),
180            vocabulary_digest: self.vocabulary_digest.clone(),
181            modality: self.modality,
182            adapter: self.adapter.clone(),
183            count: self.ids.len() as u64,
184            escapes: self.escapes.clone(),
185            id_bytes,
186        })?;
187        if header.len() > MAX_HEADER || self.escapes.len() > MAX_ESCAPES {
188            return Err(KuteError::LimitExceeded("token sequence header exceeds 4 MiB or carries more than 65,536 escaped symbols".into()));
189        }
190        let mut out = Vec::with_capacity(magic.len() + 4 + header.len() + body_hint);
191        out.extend_from_slice(magic);
192        out.extend_from_slice(&(header.len() as u32).to_le_bytes());
193        out.extend_from_slice(&header);
194        Ok(out)
195    }
196
197    /// Serialize to the compressed `.kute` container (format 2): the same
198    /// header, then the ids as fixed-width little-endian integers inside one
199    /// zlib stream. Smaller than format 1 on anything repetitive; `from_bytes`
200    /// reads both.
201    pub fn to_bytes_compressed(&self) -> Result<Vec<u8>> {
202        let max = self.ids.iter().copied().max().unwrap_or(0);
203        let width: usize = match max {
204            0..=0xff => 1,
205            0x100..=0xffff => 2,
206            0x1_0000..=0xff_ffff => 3,
207            _ => 4,
208        };
209        let mut plain = Vec::with_capacity(self.ids.len() * width);
210        for &id in &self.ids {
211            plain.extend_from_slice(&id.to_le_bytes()[..width]);
212        }
213        let out = self.start_container(MAGIC_COMPRESSED, Some(width as u8), plain.len() / 2)?;
214        let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::best());
215        encoder.write_all(&plain)?;
216        Ok(encoder.finish()?)
217    }
218
219    /// Parse a `.kute` container of either format. Rejects truncated,
220    /// oversized or trailing data.
221    ///
222    /// A compressed container can hold about four thousand times its own
223    /// size in ids. For a container from a party you do not trust, use
224    /// [`TokenSequence::from_bytes_bounded`].
225    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
226        Self::from_bytes_bounded(bytes, u64::MAX)
227    }
228
229    /// As [`TokenSequence::from_bytes`], but a container that declares more
230    /// than `max_tokens` tokens is refused before any id is read or
231    /// decompressed, so the caller decides how much memory a container may
232    /// claim.
233    pub fn from_bytes_bounded(bytes: &[u8], max_tokens: u64) -> Result<Self> {
234        let bad = |why: &str| KuteError::InvalidInput(format!("not a valid .kute token sequence: {why}"));
235        if bytes.len() < MAGIC.len() + 4 {
236            return Err(bad("missing KUTE magic"));
237        }
238        let compressed = match &bytes[..MAGIC.len()] {
239            m if m == MAGIC => false,
240            m if m == MAGIC_COMPRESSED => true,
241            _ => return Err(bad("missing KUTE magic")),
242        };
243        let mut pos = MAGIC.len();
244        let header_len = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
245        pos += 4;
246        if header_len > MAX_HEADER {
247            return Err(bad("header longer than 4 MiB"));
248        }
249        let header_end = pos.checked_add(header_len).filter(|&e| e <= bytes.len()).ok_or_else(|| bad("truncated header"))?;
250        let header: ContainerHeader = serde_json::from_slice(&bytes[pos..header_end]).map_err(|e| bad(&format!("header: {e}")))?;
251        pos = header_end;
252        if header.count > max_tokens {
253            return Err(KuteError::LimitExceeded(format!("the container declares {} tokens; the limit is {max_tokens}", header.count)));
254        }
255        if header.escapes.len() > MAX_ESCAPES || header.escapes.iter().any(|s| s.is_empty() || s.len() > crate::vocab::MAX_SYMBOL_BYTES) {
256            return Err(bad("escape table too large, or an escaped symbol is empty or oversized"));
257        }
258        let remaining = bytes.len() - pos;
259        let ids = if compressed {
260            let width = match header.id_bytes {
261                Some(w @ 1..=4) => w as usize,
262                _ => return Err(bad("compressed container needs id_bytes between 1 and 4")),
263            };
264            let expected = header.count.checked_mul(width as u64).ok_or_else(|| bad("token count overflows"))?;
265            if expected > (remaining as u64).saturating_mul(MAX_INFLATE_RATIO) {
266                return Err(bad("declared token count exceeds what the data can hold"));
267            }
268            let mut decoder = flate2::read::ZlibDecoder::new(&bytes[pos..]);
269            // The count comes from the file, so it only sizes the buffer up to a
270            // fixed bound. Past that the buffer grows as real data arrives; a
271            // header that claims gigabytes over a short or corrupt stream costs
272            // nothing.
273            let mut plain = Vec::with_capacity(expected.min(MAX_PREALLOCATE) as usize);
274            // One byte past the expected length, so a longer stream is caught
275            // and the stream checksum is verified.
276            (&mut decoder).take(expected + 1).read_to_end(&mut plain).map_err(|e| bad(&format!("compressed ids: {e}")))?;
277            if plain.len() as u64 != expected {
278                return Err(bad("token count does not match the header"));
279            }
280            if decoder.total_in() != remaining as u64 {
281                return Err(bad("data after the compressed ids"));
282            }
283            plain
284                .chunks_exact(width)
285                .map(|c| {
286                    let mut le = [0u8; 4];
287                    le[..width].copy_from_slice(c);
288                    u32::from_le_bytes(le)
289                })
290                .collect()
291        } else {
292            if header.id_bytes.is_some() {
293                return Err(bad("id_bytes belongs to the compressed format only"));
294            }
295            Self::read_varints(&bytes[pos..], header.count).map_err(bad)?
296        };
297        Ok(Self {
298            vocabulary_id: header.vocabulary_id,
299            vocabulary_version: header.vocabulary_version,
300            vocabulary_digest: header.vocabulary_digest,
301            modality: header.modality,
302            adapter: header.adapter,
303            ids,
304            escapes: header.escapes,
305        })
306    }
307
308    fn read_varints(bytes: &[u8], count: u64) -> std::result::Result<Vec<u32>, &'static str> {
309        let bad = |why: &'static str| why;
310        let mut pos = 0;
311        if count > bytes.len() as u64 {
312            return Err(bad("declared token count exceeds the data present"));
313        }
314        let mut ids = Vec::with_capacity(count as usize);
315        while pos < bytes.len() {
316            let mut value: u32 = 0;
317            let mut shift = 0u32;
318            loop {
319                let byte = *bytes.get(pos).ok_or_else(|| bad("truncated token id"))?;
320                pos += 1;
321                let low = (byte & 0x7f) as u32;
322                if shift == 28 && low > 0x0f {
323                    return Err(bad("token id overflows 32 bits"));
324                }
325                value |= low << shift;
326                if byte & 0x80 == 0 {
327                    // One id, one encoding: a padded form such as 0x85 0x00
328                    // for 5 is refused, so equal sequences have equal bytes.
329                    if byte == 0 && shift > 0 {
330                        return Err(bad("token id has a padded encoding"));
331                    }
332                    break;
333                }
334                shift += 7;
335                if shift > 28 {
336                    return Err(bad("token id overflows 32 bits"));
337                }
338            }
339            ids.push(value);
340        }
341        if ids.len() as u64 != count {
342            return Err(bad("token count does not match the header"));
343        }
344        Ok(ids)
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    fn seq(ids: Vec<u32>) -> TokenSequence {
353        TokenSequence {
354            vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
355            vocabulary_version: Version::new(1, 0, 0),
356            vocabulary_digest: "sha256:00".into(),
357            modality: Modality::Text,
358            adapter: Some("text".into()),
359            ids,
360            escapes: Vec::new(),
361        }
362    }
363
364    #[test]
365    fn container_round_trip() {
366        let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
367        let bytes = s.to_bytes().unwrap();
368        assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
369        let empty = seq(vec![]);
370        assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
371    }
372
373    #[test]
374    fn compressed_container_round_trip() {
375        for ids in [vec![], vec![7], vec![0, 255], vec![0, 256, 65_535], vec![65_536, 3], vec![1, u32::MAX], (0..5000).map(|i| i % 97).collect()] {
376            let s = seq(ids);
377            let bytes = s.to_bytes_compressed().unwrap();
378            assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
379        }
380        let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
381        assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
382    }
383
384    #[test]
385    fn compressed_container_rejects_damage() {
386        let s = seq((0..400).map(|i| 1000 + i % 13).collect());
387        let bytes = s.to_bytes_compressed().unwrap();
388        for cut in 0..bytes.len() {
389            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
390        }
391        let mut extra = bytes.clone();
392        extra.push(0);
393        assert!(TokenSequence::from_bytes(&extra).is_err());
394        // A header that claims more ids than the body holds, and one that
395        // claims an absurd number, are both refused.
396        let text = String::from_utf8_lossy(&bytes).to_string();
397        assert!(text.contains("\"count\":400"));
398        for claim in ["401", "399", "999999999999"] {
399            let mut forged = Vec::new();
400            let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
401            let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
402            forged.extend_from_slice(&bytes[..5]);
403            forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
404            forged.extend_from_slice(header.as_bytes());
405            forged.extend_from_slice(&bytes[9 + header_len..]);
406            assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
407        }
408        // A header may claim as many ids as the ratio limit allows over a body
409        // that is not a zlib stream at all. The reader must refuse it without
410        // first reserving the claimed size (64 GiB here).
411        let junk = 64usize << 20;
412        let header = format!(
413            "{{\"vocabulary_id\":\"kute:test\",\"vocabulary_version\":\"1.0.0\",\"vocabulary_digest\":\"sha256:00\",\"modality\":\"text\",\"count\":{},\"id_bytes\":1}}",
414            junk as u64 * 1024
415        );
416        let mut bomb = Vec::with_capacity(9 + header.len() + junk);
417        bomb.extend_from_slice(MAGIC_COMPRESSED);
418        bomb.extend_from_slice(&(header.len() as u32).to_le_bytes());
419        bomb.extend_from_slice(header.as_bytes());
420        bomb.resize(bomb.len() + junk, 0xaa);
421        assert!(TokenSequence::from_bytes(&bomb).is_err());
422        let mut flipped = bytes.clone();
423        let last = flipped.len() - 6;
424        flipped[last] ^= 0x40;
425        assert!(TokenSequence::from_bytes(&flipped).is_err());
426    }
427
428    #[test]
429    fn escapes_survive_both_containers() {
430        let mut s = seq(vec![3, 9, 10, 4]);
431        s.escapes = vec!["VALVE_7_OPEN".into(), "naïve symbol".into()];
432        assert_eq!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).unwrap(), s);
433        assert_eq!(TokenSequence::from_bytes(&s.to_bytes_compressed().unwrap()).unwrap(), s);
434        s.escapes = vec![String::new()];
435        assert!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).is_err());
436    }
437
438    /// Malformed containers must be refused, never panic and never allocate
439    /// by a forged count. Deterministic mutations stand in for a fuzzer.
440    #[test]
441    fn mutated_containers_never_panic() {
442        let mut base = seq((0..300).map(|i| (i * 37) % 5000).collect());
443        base.escapes = vec!["X".into()];
444        let mut state = 0x243f6a8885a308d3u64;
445        let mut next = move || {
446            state ^= state << 13;
447            state ^= state >> 7;
448            state ^= state << 17;
449            state
450        };
451        for original in [base.to_bytes().unwrap(), base.to_bytes_compressed().unwrap()] {
452            for _ in 0..6000 {
453                let mut bytes = original.clone();
454                for _ in 0..(1 + next() % 4) {
455                    let at = (next() % bytes.len() as u64) as usize;
456                    match next() % 4 {
457                        0 => bytes[at] ^= 1 << (next() % 8),
458                        1 => bytes[at] = next() as u8,
459                        2 => bytes.truncate(at),
460                        _ => bytes.insert(at, next() as u8),
461                    }
462                    if bytes.is_empty() {
463                        break;
464                    }
465                }
466                if let Ok(parsed) = TokenSequence::from_bytes(&bytes) {
467                    assert!(parsed.ids.len() <= 400_000 && parsed.escapes.len() <= MAX_ESCAPES);
468                }
469            }
470        }
471    }
472
473    #[test]
474    fn container_rejects_damage() {
475        let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
476        for cut in 0..bytes.len() {
477            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
478        }
479        let mut extra = bytes.clone();
480        extra.push(0x05);
481        assert!(TokenSequence::from_bytes(&extra).is_err());
482        let mut overflow = seq(vec![]).to_bytes().unwrap();
483        overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
484        assert!(TokenSequence::from_bytes(&overflow).is_err());
485        assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
486    }
487
488    #[test]
489    fn padded_token_ids_are_refused() {
490        let seq = TokenSequence {
491            vocabulary_id: "kute:test:pad".parse().unwrap(),
492            vocabulary_version: "1.0.0".parse().unwrap(),
493            vocabulary_digest: "sha256:00".into(),
494            modality: Modality::Text,
495            adapter: None,
496            ids: vec![5],
497            escapes: Vec::new(),
498        };
499        let mut bytes = seq.to_bytes().unwrap();
500        assert_eq!(bytes.pop(), Some(5));
501        let mut exact = bytes.clone();
502        exact.push(5);
503        assert_eq!(TokenSequence::from_bytes(&exact).unwrap().ids, vec![5]);
504        // The same id with a continuation bit and a zero byte after it.
505        bytes.extend_from_slice(&[0x85, 0x00]);
506        assert!(TokenSequence::from_bytes(&bytes).is_err());
507    }
508}