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                    break;
313                }
314                shift += 7;
315                if shift > 28 {
316                    return Err(bad("token id overflows 32 bits"));
317                }
318            }
319            ids.push(value);
320        }
321        if ids.len() as u64 != count {
322            return Err(bad("token count does not match the header"));
323        }
324        Ok(ids)
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    fn seq(ids: Vec<u32>) -> TokenSequence {
333        TokenSequence {
334            vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
335            vocabulary_version: Version::new(1, 0, 0),
336            vocabulary_digest: "sha256:00".into(),
337            modality: Modality::Text,
338            adapter: Some("text".into()),
339            ids,
340            escapes: Vec::new(),
341        }
342    }
343
344    #[test]
345    fn container_round_trip() {
346        let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
347        let bytes = s.to_bytes().unwrap();
348        assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
349        let empty = seq(vec![]);
350        assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
351    }
352
353    #[test]
354    fn compressed_container_round_trip() {
355        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()] {
356            let s = seq(ids);
357            let bytes = s.to_bytes_compressed().unwrap();
358            assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
359        }
360        let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
361        assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
362    }
363
364    #[test]
365    fn compressed_container_rejects_damage() {
366        let s = seq((0..400).map(|i| 1000 + i % 13).collect());
367        let bytes = s.to_bytes_compressed().unwrap();
368        for cut in 0..bytes.len() {
369            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
370        }
371        let mut extra = bytes.clone();
372        extra.push(0);
373        assert!(TokenSequence::from_bytes(&extra).is_err());
374        // A header that claims more ids than the body holds, and one that
375        // claims an absurd number, are both refused.
376        let text = String::from_utf8_lossy(&bytes).to_string();
377        assert!(text.contains("\"count\":400"));
378        for claim in ["401", "399", "999999999999"] {
379            let mut forged = Vec::new();
380            let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
381            let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
382            forged.extend_from_slice(&bytes[..5]);
383            forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
384            forged.extend_from_slice(header.as_bytes());
385            forged.extend_from_slice(&bytes[9 + header_len..]);
386            assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
387        }
388        // A header may claim as many ids as the ratio limit allows over a body
389        // that is not a zlib stream at all. The reader must refuse it without
390        // first reserving the claimed size (64 GiB here).
391        let junk = 64usize << 20;
392        let header = format!(
393            "{{\"vocabulary_id\":\"kute:test\",\"vocabulary_version\":\"1.0.0\",\"vocabulary_digest\":\"sha256:00\",\"modality\":\"text\",\"count\":{},\"id_bytes\":1}}",
394            junk as u64 * 1024
395        );
396        let mut bomb = Vec::with_capacity(9 + header.len() + junk);
397        bomb.extend_from_slice(MAGIC_COMPRESSED);
398        bomb.extend_from_slice(&(header.len() as u32).to_le_bytes());
399        bomb.extend_from_slice(header.as_bytes());
400        bomb.resize(bomb.len() + junk, 0xaa);
401        assert!(TokenSequence::from_bytes(&bomb).is_err());
402        let mut flipped = bytes.clone();
403        let last = flipped.len() - 6;
404        flipped[last] ^= 0x40;
405        assert!(TokenSequence::from_bytes(&flipped).is_err());
406    }
407
408    #[test]
409    fn escapes_survive_both_containers() {
410        let mut s = seq(vec![3, 9, 10, 4]);
411        s.escapes = vec!["VALVE_7_OPEN".into(), "naïve symbol".into()];
412        assert_eq!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).unwrap(), s);
413        assert_eq!(TokenSequence::from_bytes(&s.to_bytes_compressed().unwrap()).unwrap(), s);
414        s.escapes = vec![String::new()];
415        assert!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).is_err());
416    }
417
418    /// Malformed containers must be refused, never panic and never allocate
419    /// by a forged count. Deterministic mutations stand in for a fuzzer.
420    #[test]
421    fn mutated_containers_never_panic() {
422        let mut base = seq((0..300).map(|i| (i * 37) % 5000).collect());
423        base.escapes = vec!["X".into()];
424        let mut state = 0x243f6a8885a308d3u64;
425        let mut next = move || {
426            state ^= state << 13;
427            state ^= state >> 7;
428            state ^= state << 17;
429            state
430        };
431        for original in [base.to_bytes().unwrap(), base.to_bytes_compressed().unwrap()] {
432            for _ in 0..6000 {
433                let mut bytes = original.clone();
434                for _ in 0..(1 + next() % 4) {
435                    let at = (next() % bytes.len() as u64) as usize;
436                    match next() % 4 {
437                        0 => bytes[at] ^= 1 << (next() % 8),
438                        1 => bytes[at] = next() as u8,
439                        2 => bytes.truncate(at),
440                        _ => bytes.insert(at, next() as u8),
441                    }
442                    if bytes.is_empty() {
443                        break;
444                    }
445                }
446                if let Ok(parsed) = TokenSequence::from_bytes(&bytes) {
447                    assert!(parsed.ids.len() <= 400_000 && parsed.escapes.len() <= MAX_ESCAPES);
448                }
449            }
450        }
451    }
452
453    #[test]
454    fn container_rejects_damage() {
455        let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
456        for cut in 0..bytes.len() {
457            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
458        }
459        let mut extra = bytes.clone();
460        extra.push(0x05);
461        assert!(TokenSequence::from_bytes(&extra).is_err());
462        let mut overflow = seq(vec![]).to_bytes().unwrap();
463        overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
464        assert!(TokenSequence::from_bytes(&overflow).is_err());
465        assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
466    }
467}