kute-types 0.8.1

Shared data model for KUTE: identifiers, canonical inputs, token sequences and the vocabulary model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::{KuteError, Result, Version, VocabularyId};
use serde::{Deserialize, Serialize};
use std::io::{Read, Write};

/// What kind of information a payload carries. Declared by the adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Modality {
    Text,
    Binary,
    Structured,
    Events,
    Other,
}

/// The two canonical shapes a tokenizer accepts (ADR-0004).
///
/// `Bytes` covers text, binary and serialized structured data. `Symbols` is an
/// ordered sequence of opaque names (events, opcodes, gates) for information
/// whose units are not bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Payload {
    Bytes(Vec<u8>),
    Symbols(Vec<String>),
}

impl Payload {
    pub fn kind(&self) -> PayloadKind {
        match self {
            Payload::Bytes(_) => PayloadKind::Bytes,
            Payload::Symbols(_) => PayloadKind::Symbols,
        }
    }

    /// Number of units: bytes or symbols.
    pub fn len(&self) -> usize {
        match self {
            Payload::Bytes(b) => b.len(),
            Payload::Symbols(s) => s.len(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadKind {
    Bytes,
    Symbols,
}

/// Adapter output and tokenizer input: one record of canonical information.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CanonicalInput {
    pub modality: Modality,
    pub payload: Payload,
}

impl CanonicalInput {
    pub fn bytes(modality: Modality, bytes: impl Into<Vec<u8>>) -> Self {
        Self { modality, payload: Payload::Bytes(bytes.into()) }
    }

    pub fn text(text: &str) -> Self {
        Self::bytes(Modality::Text, text.as_bytes())
    }

    pub fn symbols<I, S>(symbols: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            modality: Modality::Events,
            payload: Payload::Symbols(symbols.into_iter().map(Into::into).collect()),
        }
    }
}

/// Token ids scoped to the exact vocabulary that produced them.
///
/// Ids from different vocabularies are never interchangeable, so a sequence
/// always travels with the vocabulary id, version and content digest.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenSequence {
    pub vocabulary_id: VocabularyId,
    pub vocabulary_version: Version,
    pub vocabulary_digest: String,
    pub modality: Modality,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub adapter: Option<String>,
    pub ids: Vec<u32>,
    /// Symbols the vocabulary does not contain, carried literally. An id of
    /// `vocabulary length + i` stands for `escapes[i]`. Empty unless the
    /// sequence was encoded with [`UnknownPolicy::Escape`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub escapes: Vec<String>,
}

/// What an encoder does with a symbol its frozen vocabulary does not contain.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnknownPolicy {
    /// Refuse the input.
    #[default]
    Strict,
    /// Carry the symbol literally in the sequence's escape table. The
    /// vocabulary is not changed and decoding returns the input exactly.
    Escape,
}

impl UnknownPolicy {
    pub fn parse(name: &str) -> Result<Self> {
        match name {
            "strict" => Ok(Self::Strict),
            "escape" => Ok(Self::Escape),
            other => Err(KuteError::InvalidConfig(format!("unknown-symbol policy {other:?}; expected strict or escape"))),
        }
    }
}

/// Most escaped symbols one sequence may carry.
pub const MAX_ESCAPES: usize = 65_536;

#[derive(Serialize, Deserialize)]
struct ContainerHeader {
    vocabulary_id: VocabularyId,
    vocabulary_version: Version,
    vocabulary_digest: String,
    modality: Modality,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    adapter: Option<String>,
    count: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    escapes: Vec<String>,
    /// Format 2 only: width of each id in the compressed body, 1 to 4 bytes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    id_bytes: Option<u8>,
}

const MAGIC: &[u8; 5] = b"KUTE\x01";
/// Format 2: the ids are fixed-width little-endian integers in a zlib stream.
const MAGIC_COMPRESSED: &[u8; 5] = b"KUTE\x02";
/// Headers without escaped symbols stay far below this; the room is for the
/// escape table.
const MAX_HEADER: usize = 4 * 1024 * 1024;
/// DEFLATE cannot expand by more than about 1032 to 1, so a body that claims
/// more output than this for its size is rejected before any is produced.
const MAX_INFLATE_RATIO: u64 = 1040;
/// Largest buffer reserved on the word of a container header alone.
const MAX_PREALLOCATE: u64 = 1 << 20;

impl TokenSequence {
    /// Serialize to the `.kute` container: magic, little-endian header length,
    /// JSON header, then LEB128 varint token ids.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut out = self.start_container(MAGIC, None, self.ids.len() * 2)?;
        for &id in &self.ids {
            let mut v = id;
            loop {
                let byte = (v & 0x7f) as u8;
                v >>= 7;
                if v == 0 {
                    out.push(byte);
                    break;
                }
                out.push(byte | 0x80);
            }
        }
        Ok(out)
    }

    fn start_container(&self, magic: &[u8; 5], id_bytes: Option<u8>, body_hint: usize) -> Result<Vec<u8>> {
        let header = serde_json::to_vec(&ContainerHeader {
            vocabulary_id: self.vocabulary_id.clone(),
            vocabulary_version: self.vocabulary_version.clone(),
            vocabulary_digest: self.vocabulary_digest.clone(),
            modality: self.modality,
            adapter: self.adapter.clone(),
            count: self.ids.len() as u64,
            escapes: self.escapes.clone(),
            id_bytes,
        })?;
        if header.len() > MAX_HEADER || self.escapes.len() > MAX_ESCAPES {
            return Err(KuteError::LimitExceeded("token sequence header exceeds 4 MiB or carries more than 65,536 escaped symbols".into()));
        }
        let mut out = Vec::with_capacity(magic.len() + 4 + header.len() + body_hint);
        out.extend_from_slice(magic);
        out.extend_from_slice(&(header.len() as u32).to_le_bytes());
        out.extend_from_slice(&header);
        Ok(out)
    }

    /// Serialize to the compressed `.kute` container (format 2): the same
    /// header, then the ids as fixed-width little-endian integers inside one
    /// zlib stream. Smaller than format 1 on anything repetitive; `from_bytes`
    /// reads both.
    pub fn to_bytes_compressed(&self) -> Result<Vec<u8>> {
        let max = self.ids.iter().copied().max().unwrap_or(0);
        let width: usize = match max {
            0..=0xff => 1,
            0x100..=0xffff => 2,
            0x1_0000..=0xff_ffff => 3,
            _ => 4,
        };
        let mut plain = Vec::with_capacity(self.ids.len() * width);
        for &id in &self.ids {
            plain.extend_from_slice(&id.to_le_bytes()[..width]);
        }
        let out = self.start_container(MAGIC_COMPRESSED, Some(width as u8), plain.len() / 2)?;
        let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::best());
        encoder.write_all(&plain)?;
        Ok(encoder.finish()?)
    }

    /// Parse a `.kute` container of either format. Rejects truncated,
    /// oversized or trailing data.
    ///
    /// A compressed container can hold about four thousand times its own
    /// size in ids. For a container from a party you do not trust, use
    /// [`TokenSequence::from_bytes_bounded`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        Self::from_bytes_bounded(bytes, u64::MAX)
    }

    /// As [`TokenSequence::from_bytes`], but a container that declares more
    /// than `max_tokens` tokens is refused before any id is read or
    /// decompressed, so the caller decides how much memory a container may
    /// claim.
    pub fn from_bytes_bounded(bytes: &[u8], max_tokens: u64) -> Result<Self> {
        let bad = |why: &str| KuteError::InvalidInput(format!("not a valid .kute token sequence: {why}"));
        if bytes.len() < MAGIC.len() + 4 {
            return Err(bad("missing KUTE magic"));
        }
        let compressed = match &bytes[..MAGIC.len()] {
            m if m == MAGIC => false,
            m if m == MAGIC_COMPRESSED => true,
            _ => return Err(bad("missing KUTE magic")),
        };
        let mut pos = MAGIC.len();
        let header_len = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) as usize;
        pos += 4;
        if header_len > MAX_HEADER {
            return Err(bad("header longer than 4 MiB"));
        }
        let header_end = pos.checked_add(header_len).filter(|&e| e <= bytes.len()).ok_or_else(|| bad("truncated header"))?;
        let header: ContainerHeader = serde_json::from_slice(&bytes[pos..header_end]).map_err(|e| bad(&format!("header: {e}")))?;
        pos = header_end;
        if header.count > max_tokens {
            return Err(KuteError::LimitExceeded(format!("the container declares {} tokens; the limit is {max_tokens}", header.count)));
        }
        if header.escapes.len() > MAX_ESCAPES || header.escapes.iter().any(|s| s.is_empty() || s.len() > crate::vocab::MAX_SYMBOL_BYTES) {
            return Err(bad("escape table too large, or an escaped symbol is empty or oversized"));
        }
        let remaining = bytes.len() - pos;
        let ids = if compressed {
            let width = match header.id_bytes {
                Some(w @ 1..=4) => w as usize,
                _ => return Err(bad("compressed container needs id_bytes between 1 and 4")),
            };
            let expected = header.count.checked_mul(width as u64).ok_or_else(|| bad("token count overflows"))?;
            if expected > (remaining as u64).saturating_mul(MAX_INFLATE_RATIO) {
                return Err(bad("declared token count exceeds what the data can hold"));
            }
            let mut decoder = flate2::read::ZlibDecoder::new(&bytes[pos..]);
            // The count comes from the file, so it only sizes the buffer up to a
            // fixed bound. Past that the buffer grows as real data arrives; a
            // header that claims gigabytes over a short or corrupt stream costs
            // nothing.
            let mut plain = Vec::with_capacity(expected.min(MAX_PREALLOCATE) as usize);
            // One byte past the expected length, so a longer stream is caught
            // and the stream checksum is verified.
            (&mut decoder).take(expected + 1).read_to_end(&mut plain).map_err(|e| bad(&format!("compressed ids: {e}")))?;
            if plain.len() as u64 != expected {
                return Err(bad("token count does not match the header"));
            }
            if decoder.total_in() != remaining as u64 {
                return Err(bad("data after the compressed ids"));
            }
            plain
                .chunks_exact(width)
                .map(|c| {
                    let mut le = [0u8; 4];
                    le[..width].copy_from_slice(c);
                    u32::from_le_bytes(le)
                })
                .collect()
        } else {
            if header.id_bytes.is_some() {
                return Err(bad("id_bytes belongs to the compressed format only"));
            }
            Self::read_varints(&bytes[pos..], header.count).map_err(bad)?
        };
        Ok(Self {
            vocabulary_id: header.vocabulary_id,
            vocabulary_version: header.vocabulary_version,
            vocabulary_digest: header.vocabulary_digest,
            modality: header.modality,
            adapter: header.adapter,
            ids,
            escapes: header.escapes,
        })
    }

    fn read_varints(bytes: &[u8], count: u64) -> std::result::Result<Vec<u32>, &'static str> {
        let bad = |why: &'static str| why;
        let mut pos = 0;
        if count > bytes.len() as u64 {
            return Err(bad("declared token count exceeds the data present"));
        }
        let mut ids = Vec::with_capacity(count as usize);
        while pos < bytes.len() {
            let mut value: u32 = 0;
            let mut shift = 0u32;
            loop {
                let byte = *bytes.get(pos).ok_or_else(|| bad("truncated token id"))?;
                pos += 1;
                let low = (byte & 0x7f) as u32;
                if shift == 28 && low > 0x0f {
                    return Err(bad("token id overflows 32 bits"));
                }
                value |= low << shift;
                if byte & 0x80 == 0 {
                    // One id, one encoding: a padded form such as 0x85 0x00
                    // for 5 is refused, so equal sequences have equal bytes.
                    if byte == 0 && shift > 0 {
                        return Err(bad("token id has a padded encoding"));
                    }
                    break;
                }
                shift += 7;
                if shift > 28 {
                    return Err(bad("token id overflows 32 bits"));
                }
            }
            ids.push(value);
        }
        if ids.len() as u64 != count {
            return Err(bad("token count does not match the header"));
        }
        Ok(ids)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn seq(ids: Vec<u32>) -> TokenSequence {
        TokenSequence {
            vocabulary_id: VocabularyId::parse("kute:test").unwrap(),
            vocabulary_version: Version::new(1, 0, 0),
            vocabulary_digest: "sha256:00".into(),
            modality: Modality::Text,
            adapter: Some("text".into()),
            ids,
            escapes: Vec::new(),
        }
    }

    #[test]
    fn container_round_trip() {
        let s = seq(vec![0, 1, 127, 128, 255, 16_384, 1_048_576, u32::MAX]);
        let bytes = s.to_bytes().unwrap();
        assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
        let empty = seq(vec![]);
        assert_eq!(TokenSequence::from_bytes(&empty.to_bytes().unwrap()).unwrap(), empty);
    }

    #[test]
    fn compressed_container_round_trip() {
        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()] {
            let s = seq(ids);
            let bytes = s.to_bytes_compressed().unwrap();
            assert_eq!(TokenSequence::from_bytes(&bytes).unwrap(), s);
        }
        let repetitive = seq((0..20_000).map(|i| 300 + i % 50).collect());
        assert!(repetitive.to_bytes_compressed().unwrap().len() * 10 < repetitive.to_bytes().unwrap().len());
    }

    #[test]
    fn compressed_container_rejects_damage() {
        let s = seq((0..400).map(|i| 1000 + i % 13).collect());
        let bytes = s.to_bytes_compressed().unwrap();
        for cut in 0..bytes.len() {
            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
        }
        let mut extra = bytes.clone();
        extra.push(0);
        assert!(TokenSequence::from_bytes(&extra).is_err());
        // A header that claims more ids than the body holds, and one that
        // claims an absurd number, are both refused.
        let text = String::from_utf8_lossy(&bytes).to_string();
        assert!(text.contains("\"count\":400"));
        for claim in ["401", "399", "999999999999"] {
            let mut forged = Vec::new();
            let header_len = u32::from_le_bytes([bytes[5], bytes[6], bytes[7], bytes[8]]) as usize;
            let header = String::from_utf8(bytes[9..9 + header_len].to_vec()).unwrap().replace("\"count\":400", &format!("\"count\":{claim}"));
            forged.extend_from_slice(&bytes[..5]);
            forged.extend_from_slice(&(header.len() as u32).to_le_bytes());
            forged.extend_from_slice(header.as_bytes());
            forged.extend_from_slice(&bytes[9 + header_len..]);
            assert!(TokenSequence::from_bytes(&forged).is_err(), "count {claim}");
        }
        // A header may claim as many ids as the ratio limit allows over a body
        // that is not a zlib stream at all. The reader must refuse it without
        // first reserving the claimed size (64 GiB here).
        let junk = 64usize << 20;
        let header = format!(
            "{{\"vocabulary_id\":\"kute:test\",\"vocabulary_version\":\"1.0.0\",\"vocabulary_digest\":\"sha256:00\",\"modality\":\"text\",\"count\":{},\"id_bytes\":1}}",
            junk as u64 * 1024
        );
        let mut bomb = Vec::with_capacity(9 + header.len() + junk);
        bomb.extend_from_slice(MAGIC_COMPRESSED);
        bomb.extend_from_slice(&(header.len() as u32).to_le_bytes());
        bomb.extend_from_slice(header.as_bytes());
        bomb.resize(bomb.len() + junk, 0xaa);
        assert!(TokenSequence::from_bytes(&bomb).is_err());
        let mut flipped = bytes.clone();
        let last = flipped.len() - 6;
        flipped[last] ^= 0x40;
        assert!(TokenSequence::from_bytes(&flipped).is_err());
    }

    #[test]
    fn escapes_survive_both_containers() {
        let mut s = seq(vec![3, 9, 10, 4]);
        s.escapes = vec!["VALVE_7_OPEN".into(), "naïve symbol".into()];
        assert_eq!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).unwrap(), s);
        assert_eq!(TokenSequence::from_bytes(&s.to_bytes_compressed().unwrap()).unwrap(), s);
        s.escapes = vec![String::new()];
        assert!(TokenSequence::from_bytes(&s.to_bytes().unwrap()).is_err());
    }

    /// Malformed containers must be refused, never panic and never allocate
    /// by a forged count. Deterministic mutations stand in for a fuzzer.
    #[test]
    fn mutated_containers_never_panic() {
        let mut base = seq((0..300).map(|i| (i * 37) % 5000).collect());
        base.escapes = vec!["X".into()];
        let mut state = 0x243f6a8885a308d3u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        for original in [base.to_bytes().unwrap(), base.to_bytes_compressed().unwrap()] {
            for _ in 0..6000 {
                let mut bytes = original.clone();
                for _ in 0..(1 + next() % 4) {
                    let at = (next() % bytes.len() as u64) as usize;
                    match next() % 4 {
                        0 => bytes[at] ^= 1 << (next() % 8),
                        1 => bytes[at] = next() as u8,
                        2 => bytes.truncate(at),
                        _ => bytes.insert(at, next() as u8),
                    }
                    if bytes.is_empty() {
                        break;
                    }
                }
                if let Ok(parsed) = TokenSequence::from_bytes(&bytes) {
                    assert!(parsed.ids.len() <= 400_000 && parsed.escapes.len() <= MAX_ESCAPES);
                }
            }
        }
    }

    #[test]
    fn container_rejects_damage() {
        let bytes = seq(vec![1, 2, 300, 70_000]).to_bytes().unwrap();
        for cut in 0..bytes.len() {
            assert!(TokenSequence::from_bytes(&bytes[..cut]).is_err(), "truncated at {cut}");
        }
        let mut extra = bytes.clone();
        extra.push(0x05);
        assert!(TokenSequence::from_bytes(&extra).is_err());
        let mut overflow = seq(vec![]).to_bytes().unwrap();
        overflow.extend_from_slice(&[0xff, 0xff, 0xff, 0xff, 0x7f]);
        assert!(TokenSequence::from_bytes(&overflow).is_err());
        assert!(TokenSequence::from_bytes(b"not a kute file").is_err());
    }

    #[test]
    fn padded_token_ids_are_refused() {
        let seq = TokenSequence {
            vocabulary_id: "kute:test:pad".parse().unwrap(),
            vocabulary_version: "1.0.0".parse().unwrap(),
            vocabulary_digest: "sha256:00".into(),
            modality: Modality::Text,
            adapter: None,
            ids: vec![5],
            escapes: Vec::new(),
        };
        let mut bytes = seq.to_bytes().unwrap();
        assert_eq!(bytes.pop(), Some(5));
        let mut exact = bytes.clone();
        exact.push(5);
        assert_eq!(TokenSequence::from_bytes(&exact).unwrap().ids, vec![5]);
        // The same id with a continuation bit and a zero byte after it.
        bytes.extend_from_slice(&[0x85, 0x00]);
        assert!(TokenSequence::from_bytes(&bytes).is_err());
    }
}