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
154impl TokenSequence {
155    /// Serialize to the `.kute` container: magic, little-endian header length,
156    /// JSON header, then LEB128 varint token ids.
157    pub fn to_bytes(&self) -> Result<Vec<u8>> {
158        let mut out = self.start_container(MAGIC, None, self.ids.len() * 2)?;
159        for &id in &self.ids {
160            let mut v = id;
161            loop {
162                let byte = (v & 0x7f) as u8;
163                v >>= 7;
164                if v == 0 {
165                    out.push(byte);
166                    break;
167                }
168                out.push(byte | 0x80);
169            }
170        }
171        Ok(out)
172    }
173
174    fn start_container(&self, magic: &[u8; 5], id_bytes: Option<u8>, body_hint: usize) -> Result<Vec<u8>> {
175        let header = serde_json::to_vec(&ContainerHeader {
176            vocabulary_id: self.vocabulary_id.clone(),
177            vocabulary_version: self.vocabulary_version.clone(),
178            vocabulary_digest: self.vocabulary_digest.clone(),
179            modality: self.modality,
180            adapter: self.adapter.clone(),
181            count: self.ids.len() as u64,
182            escapes: self.escapes.clone(),
183            id_bytes,
184        })?;
185        if header.len() > MAX_HEADER || self.escapes.len() > MAX_ESCAPES {
186            return Err(KuteError::LimitExceeded("token sequence header exceeds 4 MiB or carries more than 65,536 escaped symbols".into()));
187        }
188        let mut out = Vec::with_capacity(magic.len() + 4 + header.len() + body_hint);
189        out.extend_from_slice(magic);
190        out.extend_from_slice(&(header.len() as u32).to_le_bytes());
191        out.extend_from_slice(&header);
192        Ok(out)
193    }
194
195    /// Serialize to the compressed `.kute` container (format 2): the same
196    /// header, then the ids as fixed-width little-endian integers inside one
197    /// zlib stream. Smaller than format 1 on anything repetitive; `from_bytes`
198    /// reads both.
199    pub fn to_bytes_compressed(&self) -> Result<Vec<u8>> {
200        let max = self.ids.iter().copied().max().unwrap_or(0);
201        let width: usize = match max {
202            0..=0xff => 1,
203            0x100..=0xffff => 2,
204            0x1_0000..=0xff_ffff => 3,
205            _ => 4,
206        };
207        let mut plain = Vec::with_capacity(self.ids.len() * width);
208        for &id in &self.ids {
209            plain.extend_from_slice(&id.to_le_bytes()[..width]);
210        }
211        let out = self.start_container(MAGIC_COMPRESSED, Some(width as u8), plain.len() / 2)?;
212        let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::best());
213        encoder.write_all(&plain)?;
214        Ok(encoder.finish()?)
215    }
216
217    /// Parse a `.kute` container of either format. Rejects truncated,
218    /// oversized or trailing data.
219    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
220        let bad = |why: &str| KuteError::InvalidInput(format!("not a valid .kute token sequence: {why}"));
221        if bytes.len() < MAGIC.len() + 4 {
222            return Err(bad("missing KUTE magic"));
223        }
224        let compressed = match &bytes[..MAGIC.len()] {
225            m if m == MAGIC => false,
226            m if m == MAGIC_COMPRESSED => true,
227            _ => return Err(bad("missing KUTE magic")),
228        };
229        let mut pos = MAGIC.len();
230        let header_len = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
231        pos += 4;
232        if header_len > MAX_HEADER {
233            return Err(bad("header longer than 4 MiB"));
234        }
235        let header_end = pos.checked_add(header_len).filter(|&e| e <= bytes.len()).ok_or_else(|| bad("truncated header"))?;
236        let header: ContainerHeader = serde_json::from_slice(&bytes[pos..header_end]).map_err(|e| bad(&format!("header: {e}")))?;
237        pos = header_end;
238        if header.escapes.len() > MAX_ESCAPES || header.escapes.iter().any(|s| s.is_empty() || s.len() > crate::vocab::MAX_SYMBOL_BYTES) {
239            return Err(bad("escape table too large, or an escaped symbol is empty or oversized"));
240        }
241        let remaining = bytes.len() - pos;
242        let ids = if compressed {
243            let width = match header.id_bytes {
244                Some(w @ 1..=4) => w as usize,
245                _ => return Err(bad("compressed container needs id_bytes between 1 and 4")),
246            };
247            let expected = header.count.checked_mul(width as u64).ok_or_else(|| bad("token count overflows"))?;
248            if expected > (remaining as u64).saturating_mul(MAX_INFLATE_RATIO) {
249                return Err(bad("declared token count exceeds what the data can hold"));
250            }
251            let mut decoder = flate2::read::ZlibDecoder::new(&bytes[pos..]);
252            let mut plain = Vec::with_capacity(expected as usize);
253            // One byte past the expected length, so a longer stream is caught
254            // and the stream checksum is verified.
255            (&mut decoder).take(expected + 1).read_to_end(&mut plain).map_err(|e| bad(&format!("compressed ids: {e}")))?;
256            if plain.len() as u64 != expected {
257                return Err(bad("token count does not match the header"));
258            }
259            if decoder.total_in() != remaining as u64 {
260                return Err(bad("data after the compressed ids"));
261            }
262            plain
263                .chunks_exact(width)
264                .map(|c| {
265                    let mut le = [0u8; 4];
266                    le[..width].copy_from_slice(c);
267                    u32::from_le_bytes(le)
268                })
269                .collect()
270        } else {
271            if header.id_bytes.is_some() {
272                return Err(bad("id_bytes belongs to the compressed format only"));
273            }
274            Self::read_varints(&bytes[pos..], header.count).map_err(bad)?
275        };
276        Ok(Self {
277            vocabulary_id: header.vocabulary_id,
278            vocabulary_version: header.vocabulary_version,
279            vocabulary_digest: header.vocabulary_digest,
280            modality: header.modality,
281            adapter: header.adapter,
282            ids,
283            escapes: header.escapes,
284        })
285    }
286
287    fn read_varints(bytes: &[u8], count: u64) -> std::result::Result<Vec<u32>, &'static str> {
288        let bad = |why: &'static str| why;
289        let mut pos = 0;
290        if count > bytes.len() as u64 {
291            return Err(bad("declared token count exceeds the data present"));
292        }
293        let mut ids = Vec::with_capacity(count as usize);
294        while pos < bytes.len() {
295            let mut value: u32 = 0;
296            let mut shift = 0u32;
297            loop {
298                let byte = *bytes.get(pos).ok_or_else(|| bad("truncated token id"))?;
299                pos += 1;
300                let low = (byte & 0x7f) as u32;
301                if shift == 28 && low > 0x0f {
302                    return Err(bad("token id overflows 32 bits"));
303                }
304                value |= low << shift;
305                if byte & 0x80 == 0 {
306                    break;
307                }
308                shift += 7;
309                if shift > 28 {
310                    return Err(bad("token id overflows 32 bits"));
311                }
312            }
313            ids.push(value);
314        }
315        if ids.len() as u64 != count {
316            return Err(bad("token count does not match the header"));
317        }
318        Ok(ids)
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    fn seq(ids: Vec<u32>) -> TokenSequence {
327        TokenSequence {
328            vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
329            vocabulary_version: Version::new(1, 0, 0),
330            vocabulary_digest: "sha256:00".into(),
331            modality: Modality::Text,
332            adapter: Some("text".into()),
333            ids,
334            escapes: Vec::new(),
335        }
336    }
337
338    #[test]
339    fn container_round_trip() {
340        let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
341        let bytes = s.to_bytes().unwrap();
342        assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
343        let empty = seq(vec![]);
344        assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
345    }
346
347    #[test]
348    fn compressed_container_round_trip() {
349        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()] {
350            let s = seq(ids);
351            let bytes = s.to_bytes_compressed().unwrap();
352            assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
353        }
354        let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
355        assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
356    }
357
358    #[test]
359    fn compressed_container_rejects_damage() {
360        let s = seq((0..400).map(|i| 1000 + i % 13).collect());
361        let bytes = s.to_bytes_compressed().unwrap();
362        for cut in 0..bytes.len() {
363            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
364        }
365        let mut extra = bytes.clone();
366        extra.push(0);
367        assert!(TokenSequence::from_bytes(&extra).is_err());
368        // A header that claims more ids than the body holds, and one that
369        // claims an absurd number, are both refused.
370        let text = String::from_utf8_lossy(&bytes).to_string();
371        assert!(text.contains("\"count\":400"));
372        for claim in ["401", "399", "999999999999"] {
373            let mut forged = Vec::new();
374            let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
375            let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
376            forged.extend_from_slice(&bytes[..5]);
377            forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
378            forged.extend_from_slice(header.as_bytes());
379            forged.extend_from_slice(&bytes[9 + header_len..]);
380            assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
381        }
382        let mut flipped = bytes.clone();
383        let last = flipped.len() - 6;
384        flipped[last] ^= 0x40;
385        assert!(TokenSequence::from_bytes(&flipped).is_err());
386    }
387
388    #[test]
389    fn escapes_survive_both_containers() {
390        let mut s = seq(vec![3, 9, 10, 4]);
391        s.escapes = vec!["VALVE_7_OPEN".into(), "naïve symbol".into()];
392        assert_eq!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).unwrap(), s);
393        assert_eq!(TokenSequence::from_bytes(&s.to_bytes_compressed().unwrap()).unwrap(), s);
394        s.escapes = vec![String::new()];
395        assert!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).is_err());
396    }
397
398    /// Malformed containers must be refused, never panic and never allocate
399    /// by a forged count. Deterministic mutations stand in for a fuzzer.
400    #[test]
401    fn mutated_containers_never_panic() {
402        let mut base = seq((0..300).map(|i| (i * 37) % 5000).collect());
403        base.escapes = vec!["X".into()];
404        let mut state = 0x243f6a8885a308d3u64;
405        let mut next = move || {
406            state ^= state << 13;
407            state ^= state >> 7;
408            state ^= state << 17;
409            state
410        };
411        for original in [base.to_bytes().unwrap(), base.to_bytes_compressed().unwrap()] {
412            for _ in 0..6000 {
413                let mut bytes = original.clone();
414                for _ in 0..(1 + next() % 4) {
415                    let at = (next() % bytes.len() as u64) as usize;
416                    match next() % 4 {
417                        0 => bytes[at] ^= 1 << (next() % 8),
418                        1 => bytes[at] = next() as u8,
419                        2 => bytes.truncate(at),
420                        _ => bytes.insert(at, next() as u8),
421                    }
422                    if bytes.is_empty() {
423                        break;
424                    }
425                }
426                if let Ok(parsed) = TokenSequence::from_bytes(&bytes) {
427                    assert!(parsed.ids.len() <= 400_000 && parsed.escapes.len() <= MAX_ESCAPES);
428                }
429            }
430        }
431    }
432
433    #[test]
434    fn container_rejects_damage() {
435        let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
436        for cut in 0..bytes.len() {
437            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
438        }
439        let mut extra = bytes.clone();
440        extra.push(0x05);
441        assert!(TokenSequence::from_bytes(&extra).is_err());
442        let mut overflow = seq(vec![]).to_bytes().unwrap();
443        overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
444        assert!(TokenSequence::from_bytes(&overflow).is_err());
445        assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
446    }
447}