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    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
222        let bad = |why: &str| KuteError::InvalidInput(format!("not a valid .kute token sequence: {why}"));
223        if bytes.len() < MAGIC.len() + 4 {
224            return Err(bad("missing KUTE magic"));
225        }
226        let compressed = match &bytes[..MAGIC.len()] {
227            m if m == MAGIC => false,
228            m if m == MAGIC_COMPRESSED => true,
229            _ => return Err(bad("missing KUTE magic")),
230        };
231        let mut pos = MAGIC.len();
232        let header_len = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
233        pos += 4;
234        if header_len > MAX_HEADER {
235            return Err(bad("header longer than 4 MiB"));
236        }
237        let header_end = pos.checked_add(header_len).filter(|&e| e <= bytes.len()).ok_or_else(|| bad("truncated header"))?;
238        let header: ContainerHeader = serde_json::from_slice(&bytes[pos..header_end]).map_err(|e| bad(&format!("header: {e}")))?;
239        pos = header_end;
240        if header.escapes.len() > MAX_ESCAPES || header.escapes.iter().any(|s| s.is_empty() || s.len() > crate::vocab::MAX_SYMBOL_BYTES) {
241            return Err(bad("escape table too large, or an escaped symbol is empty or oversized"));
242        }
243        let remaining = bytes.len() - pos;
244        let ids = if compressed {
245            let width = match header.id_bytes {
246                Some(w @ 1..=4) => w as usize,
247                _ => return Err(bad("compressed container needs id_bytes between 1 and 4")),
248            };
249            let expected = header.count.checked_mul(width as u64).ok_or_else(|| bad("token count overflows"))?;
250            if expected > (remaining as u64).saturating_mul(MAX_INFLATE_RATIO) {
251                return Err(bad("declared token count exceeds what the data can hold"));
252            }
253            let mut decoder = flate2::read::ZlibDecoder::new(&bytes[pos..]);
254            // The count comes from the file, so it only sizes the buffer up to a
255            // fixed bound. Past that the buffer grows as real data arrives; a
256            // header that claims gigabytes over a short or corrupt stream costs
257            // nothing.
258            let mut plain = Vec::with_capacity(expected.min(MAX_PREALLOCATE) as usize);
259            // One byte past the expected length, so a longer stream is caught
260            // and the stream checksum is verified.
261            (&mut decoder).take(expected + 1).read_to_end(&mut plain).map_err(|e| bad(&format!("compressed ids: {e}")))?;
262            if plain.len() as u64 != expected {
263                return Err(bad("token count does not match the header"));
264            }
265            if decoder.total_in() != remaining as u64 {
266                return Err(bad("data after the compressed ids"));
267            }
268            plain
269                .chunks_exact(width)
270                .map(|c| {
271                    let mut le = [0u8; 4];
272                    le[..width].copy_from_slice(c);
273                    u32::from_le_bytes(le)
274                })
275                .collect()
276        } else {
277            if header.id_bytes.is_some() {
278                return Err(bad("id_bytes belongs to the compressed format only"));
279            }
280            Self::read_varints(&bytes[pos..], header.count).map_err(bad)?
281        };
282        Ok(Self {
283            vocabulary_id: header.vocabulary_id,
284            vocabulary_version: header.vocabulary_version,
285            vocabulary_digest: header.vocabulary_digest,
286            modality: header.modality,
287            adapter: header.adapter,
288            ids,
289            escapes: header.escapes,
290        })
291    }
292
293    fn read_varints(bytes: &[u8], count: u64) -> std::result::Result<Vec<u32>, &'static str> {
294        let bad = |why: &'static str| why;
295        let mut pos = 0;
296        if count > bytes.len() as u64 {
297            return Err(bad("declared token count exceeds the data present"));
298        }
299        let mut ids = Vec::with_capacity(count as usize);
300        while pos < bytes.len() {
301            let mut value: u32 = 0;
302            let mut shift = 0u32;
303            loop {
304                let byte = *bytes.get(pos).ok_or_else(|| bad("truncated token id"))?;
305                pos += 1;
306                let low = (byte & 0x7f) as u32;
307                if shift == 28 && low > 0x0f {
308                    return Err(bad("token id overflows 32 bits"));
309                }
310                value |= low << shift;
311                if byte & 0x80 == 0 {
312                    // One id, one encoding: a padded form such as 0x85 0x00
313                    // for 5 is refused, so equal sequences have equal bytes.
314                    if byte == 0 && shift > 0 {
315                        return Err(bad("token id has a padded encoding"));
316                    }
317                    break;
318                }
319                shift += 7;
320                if shift > 28 {
321                    return Err(bad("token id overflows 32 bits"));
322                }
323            }
324            ids.push(value);
325        }
326        if ids.len() as u64 != count {
327            return Err(bad("token count does not match the header"));
328        }
329        Ok(ids)
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    fn seq(ids: Vec<u32>) -> TokenSequence {
338        TokenSequence {
339            vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
340            vocabulary_version: Version::new(1, 0, 0),
341            vocabulary_digest: "sha256:00".into(),
342            modality: Modality::Text,
343            adapter: Some("text".into()),
344            ids,
345            escapes: Vec::new(),
346        }
347    }
348
349    #[test]
350    fn container_round_trip() {
351        let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
352        let bytes = s.to_bytes().unwrap();
353        assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
354        let empty = seq(vec![]);
355        assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
356    }
357
358    #[test]
359    fn compressed_container_round_trip() {
360        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()] {
361            let s = seq(ids);
362            let bytes = s.to_bytes_compressed().unwrap();
363            assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
364        }
365        let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
366        assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
367    }
368
369    #[test]
370    fn compressed_container_rejects_damage() {
371        let s = seq((0..400).map(|i| 1000 + i % 13).collect());
372        let bytes = s.to_bytes_compressed().unwrap();
373        for cut in 0..bytes.len() {
374            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
375        }
376        let mut extra = bytes.clone();
377        extra.push(0);
378        assert!(TokenSequence::from_bytes(&extra).is_err());
379        // A header that claims more ids than the body holds, and one that
380        // claims an absurd number, are both refused.
381        let text = String::from_utf8_lossy(&bytes).to_string();
382        assert!(text.contains("\"count\":400"));
383        for claim in ["401", "399", "999999999999"] {
384            let mut forged = Vec::new();
385            let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
386            let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
387            forged.extend_from_slice(&bytes[..5]);
388            forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
389            forged.extend_from_slice(header.as_bytes());
390            forged.extend_from_slice(&bytes[9 + header_len..]);
391            assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
392        }
393        // A header may claim as many ids as the ratio limit allows over a body
394        // that is not a zlib stream at all. The reader must refuse it without
395        // first reserving the claimed size (64 GiB here).
396        let junk = 64usize << 20;
397        let header = format!(
398            "{{\"vocabulary_id\":\"kute:test\",\"vocabulary_version\":\"1.0.0\",\"vocabulary_digest\":\"sha256:00\",\"modality\":\"text\",\"count\":{},\"id_bytes\":1}}",
399            junk as u64 * 1024
400        );
401        let mut bomb = Vec::with_capacity(9 + header.len() + junk);
402        bomb.extend_from_slice(MAGIC_COMPRESSED);
403        bomb.extend_from_slice(&(header.len() as u32).to_le_bytes());
404        bomb.extend_from_slice(header.as_bytes());
405        bomb.resize(bomb.len() + junk, 0xaa);
406        assert!(TokenSequence::from_bytes(&bomb).is_err());
407        let mut flipped = bytes.clone();
408        let last = flipped.len() - 6;
409        flipped[last] ^= 0x40;
410        assert!(TokenSequence::from_bytes(&flipped).is_err());
411    }
412
413    #[test]
414    fn escapes_survive_both_containers() {
415        let mut s = seq(vec![3, 9, 10, 4]);
416        s.escapes = vec!["VALVE_7_OPEN".into(), "naïve symbol".into()];
417        assert_eq!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).unwrap(), s);
418        assert_eq!(TokenSequence::from_bytes(&s.to_bytes_compressed().unwrap()).unwrap(), s);
419        s.escapes = vec![String::new()];
420        assert!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).is_err());
421    }
422
423    /// Malformed containers must be refused, never panic and never allocate
424    /// by a forged count. Deterministic mutations stand in for a fuzzer.
425    #[test]
426    fn mutated_containers_never_panic() {
427        let mut base = seq((0..300).map(|i| (i * 37) % 5000).collect());
428        base.escapes = vec!["X".into()];
429        let mut state = 0x243f6a8885a308d3u64;
430        let mut next = move || {
431            state ^= state << 13;
432            state ^= state >> 7;
433            state ^= state << 17;
434            state
435        };
436        for original in [base.to_bytes().unwrap(), base.to_bytes_compressed().unwrap()] {
437            for _ in 0..6000 {
438                let mut bytes = original.clone();
439                for _ in 0..(1 + next() % 4) {
440                    let at = (next() % bytes.len() as u64) as usize;
441                    match next() % 4 {
442                        0 => bytes[at] ^= 1 << (next() % 8),
443                        1 => bytes[at] = next() as u8,
444                        2 => bytes.truncate(at),
445                        _ => bytes.insert(at, next() as u8),
446                    }
447                    if bytes.is_empty() {
448                        break;
449                    }
450                }
451                if let Ok(parsed) = TokenSequence::from_bytes(&bytes) {
452                    assert!(parsed.ids.len() <= 400_000 && parsed.escapes.len() <= MAX_ESCAPES);
453                }
454            }
455        }
456    }
457
458    #[test]
459    fn container_rejects_damage() {
460        let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
461        for cut in 0..bytes.len() {
462            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
463        }
464        let mut extra = bytes.clone();
465        extra.push(0x05);
466        assert!(TokenSequence::from_bytes(&extra).is_err());
467        let mut overflow = seq(vec![]).to_bytes().unwrap();
468        overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
469        assert!(TokenSequence::from_bytes(&overflow).is_err());
470        assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
471    }
472
473    #[test]
474    fn padded_token_ids_are_refused() {
475        let seq = TokenSequence {
476            vocabulary_id: "kute:test:pad".parse().unwrap(),
477            vocabulary_version: "1.0.0".parse().unwrap(),
478            vocabulary_digest: "sha256:00".into(),
479            modality: Modality::Text,
480            adapter: None,
481            ids: vec![5],
482            escapes: Vec::new(),
483        };
484        let mut bytes = seq.to_bytes().unwrap();
485        assert_eq!(bytes.pop(), Some(5));
486        let mut exact = bytes.clone();
487        exact.push(5);
488        assert_eq!(TokenSequence::from_bytes(&exact).unwrap().ids, vec![5]);
489        // The same id with a continuation bit and a zero byte after it.
490        bytes.extend_from_slice(&[0x85, 0x00]);
491        assert!(TokenSequence::from_bytes(&bytes).is_err());
492    }
493}