Files
strata-ctl/tests/inkling_tokenizer.rs
adm 597ac432e1 strata-ctl: Rust control layer for the Strata engine (OpenAI-compatible API)
From-scratch rewrite of the Python serve (Python kept as behavioral spec).

- engine: line-protocol supervisor (GEN/T/DONE/STOP/QUIT), silence watchdog,
  abort, is_idle probe.
- config: tolerant shared-JSON loader; foreign keys ignored so one file drives
  strata-ctl and uostream; CLI --config/--host/--port/--serve.
- inkling: o200k tokenizer wrapper + incremental UTF-8-safe detok; chat template
  via minijinja; channel-token dialect (reasoning streamed live); image bridge
  (in-process Vision, image=<path>); formatter assembling the API seam.
- api: /v1/chat/completions (stream SSE + non-stream), /v1/models, /health;
  reasoning_content; structured tool_calls (llama.cpp --jinja style, client-side
  execution); stop sequences with hold-back; abort on client disconnect.

69 tests green + 2 real-file ignored; clippy clean. Text, images and tools
validated live against the real Inkling engine.
2026-11-24 05:28:56 +01:00

134 lines
5.1 KiB
Rust

//! Tests for the Inkling tokenizer wrapper.
//!
//! The deterministic tests build a tiny fixture tokenizer with the `tokenizers`
//! crate (no host files), so the suite is green anywhere. A separate `#[ignore]`
//! test exercises the REAL o200k tokenizer when STRATA_TOK_DIR is set; run it
//! with `cargo test -- --ignored`.
use std::collections::HashMap;
use std::sync::Arc;
use tokenizers::models::wordlevel::WordLevel;
use tokenizers::AddedToken;
use tokenizers::Tokenizer;
use strata_ctl::inkling::dialect::Tag;
use strata_ctl::inkling::tokenizer::{Detok, InklingTokenizer};
/// Unique suffix so parallel tests never share a fixture file.
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
/// Build a small WordLevel tokenizer with a few Inkling channel tokens added,
/// save it, and load it through our wrapper. Returns (wrapper, path, ids).
fn fixture() -> (InklingTokenizer, std::path::PathBuf) {
let mut vocab = HashMap::new();
vocab.insert("hello".to_string(), 0u32);
vocab.insert("world".to_string(), 1u32);
vocab.insert("[UNK]".to_string(), 2u32);
let model = WordLevel::builder()
.vocab(vocab.into_iter().collect())
.unk_token("[UNK]".to_string())
.build()
.unwrap();
let mut tok = Tokenizer::new(model);
tok.with_pre_tokenizer(Some(tokenizers::pre_tokenizers::whitespace::Whitespace));
let _ = tok.add_special_tokens([
AddedToken::from("<|message_model|>", true),
AddedToken::from("<|content_text|>", true),
AddedToken::from("<|content_thinking|>", true),
AddedToken::from("<|end_message|>", true),
]);
let path = std::env::temp_dir().join(format!(
"strata-ctl-tok-{}-{}.json",
std::process::id(),
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
tok.save(&path, false).unwrap();
let wrapped = InklingTokenizer::from_file(&path).unwrap();
(wrapped, path)
}
#[test]
fn encode_decode_roundtrip() {
let (t, path) = fixture();
let ids = t.encode("hello world").unwrap();
assert_eq!(ids, vec![0, 1]);
let decoded = t.decode_all(&ids).unwrap();
assert!(
decoded.contains("hello") && decoded.contains("world"),
"{decoded}"
);
let _ = std::fs::remove_file(&path);
}
#[test]
fn channel_tokens_map_to_tags() {
let (t, path) = fixture();
// a channel token encodes to a single id and maps back to its dialect tag
let ids = t.encode("<|content_thinking|>").unwrap();
assert_eq!(ids.len(), 1);
assert!(t.is_special(ids[0]));
assert_eq!(t.channel_tag(ids[0]), Some(Tag::ContentThinking));
let ids = t.encode("<|end_message|>").unwrap();
assert_eq!(t.channel_tag(ids[0]), Some(Tag::EndMessage));
// an ordinary word is not special
assert!(!t.is_special(0));
assert_eq!(t.channel_tag(0), None);
let _ = std::fs::remove_file(&path);
}
#[test]
fn detok_streams_incrementally() {
let (t, path) = fixture();
let mut d = Detok::new(Arc::new(t));
let a = d.push(0);
let b = d.push(1);
let c = d.finish();
// WordLevel decode re-inserts the whitespace between words
assert_eq!(format!("{a}{b}{c}"), "hello world");
let _ = std::fs::remove_file(&path);
}
#[test]
fn detok_emits_special_tokens_immediately() {
let (t, path) = fixture();
let think_id = t.encode("<|content_thinking|>").unwrap()[0];
let mut d = Detok::new(Arc::new(t));
// ordinary word then a channel token: both surface as text pieces
let a = d.push(0);
let b = d.push(think_id);
assert_eq!(a, "hello");
assert!(b.contains("<|content_thinking|>"), "{b}");
let _ = std::fs::remove_file(&path);
}
/// Real-tokenizer check, ignored by default (host files). Run with:
/// STRATA_TOK_DIR=~/.config/strata-inkling/inkling-tok cargo test -- --ignored
#[test]
#[ignore = "needs the real Inkling tokenizer dir"]
fn real_tokenizer_channel_ids() {
let dir = std::env::var("STRATA_TOK_DIR")
.unwrap_or_else(|_| "/home/federico/.config/strata-inkling/inkling-tok".to_string());
let t = InklingTokenizer::load_dir(std::path::Path::new(&dir)).expect("load real tokenizer");
// the exact ids observed in tokenizer.hf.json's added_tokens
assert_eq!(t.channel_tag(200001), Some(Tag::MessageModel));
assert_eq!(t.channel_tag(200004), Some(Tag::ContentText));
assert_eq!(t.channel_tag(200006), Some(Tag::EndSampling));
assert_eq!(t.channel_tag(200008), Some(Tag::ContentThinking));
assert_eq!(t.channel_tag(200010), Some(Tag::EndMessage));
assert_eq!(t.channel_tag(200024), Some(Tag::ContentXml));
assert_eq!(t.channel_tag(200049), Some(Tag::ContentInvokeToolJson));
assert_eq!(t.channel_tag(200057), Some(Tag::ContentInvokeToolText));
assert_eq!(t.channel_tag(199999), Some(Tag::EndOfText));
// a channel token in a rendered prompt encodes to its single id
let ids = t
.encode("<|message_model|><|content_text|>ciao<|end_message|>")
.unwrap();
assert_eq!(ids.first().copied(), Some(200001));
assert_eq!(ids.last().copied(), Some(200010));
assert!(t.decode_all(&ids).unwrap().contains("ciao"));
}