Skip to main content

hol_cigar/
tokenizer.rs

1use crate::ContextError;
2use std::collections::{HashMap, VecDeque};
3use std::sync::{Arc, Mutex};
4
5#[cfg(feature = "bpe")]
6mod ordinary;
7#[cfg(all(test, feature = "bpe"))]
8mod ordinary_patterns;
9#[cfg(feature = "bpe")]
10mod segmenter;
11#[cfg(feature = "bpe")]
12mod vocabulary;
13#[cfg(feature = "bpe")]
14mod vocabulary_hash;
15
16/// Exact token accounting for the rendered context text, excluding the provider chat envelope.
17/// Implementations must use an immutable identity for their algorithm and vocabulary.
18pub trait TokenCounter {
19    /// Algorithm/vocabulary identity; changes invalidate snapshot reuse.
20    fn identity(&self) -> &str;
21    /// Counts text as ordinary data, including strings resembling special model tokens.
22    fn count(&self, text: &str) -> Result<usize, ContextError>;
23}
24
25/// Bounds for exact-text token memoization. Either zero limit disables caching.
26#[derive(Clone, Copy, Debug)]
27pub struct TokenCacheLimits {
28    /// Maximum distinct cached strings; also bounds map/queue overhead.
29    pub max_entries: usize,
30    /// Maximum retained UTF-8 payload bytes, excluding bounded entry/allocator overhead.
31    pub max_text_bytes: usize,
32}
33
34impl Default for TokenCacheLimits {
35    fn default() -> Self {
36        Self {
37            max_entries: 2048,
38            max_text_bytes: 8 * 1024 * 1024,
39        }
40    }
41}
42
43/// Content-free counters for an instance-local token cache.
44#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
45pub struct TokenCacheStats {
46    /// Successful exact-text lookups.
47    pub hits: u64,
48    /// Requests sent to the underlying tokenizer, including bypasses and errors.
49    pub misses: u64,
50    /// Current number of distinct entries.
51    pub entries: usize,
52    /// Current retained UTF-8 text bytes, excluding allocator/entry overhead.
53    pub text_bytes: usize,
54}
55
56#[derive(Default)]
57struct Cache {
58    values: HashMap<Arc<str>, usize>,
59    order: VecDeque<Arc<str>>,
60    stats: TokenCacheStats,
61    generation: u64,
62}
63
64/// Bounded, thread-safe, exact-text memoization for an immutable token counter.
65///
66/// Counts are never estimated or added across blocks. Equality checks the complete string, not
67/// only a digest. FIFO eviction changes performance only. Errors are never cached. The cache
68/// retains source text in memory: own one per privacy boundary and clear/drop it when appropriate.
69/// Concurrent misses may compute twice; the expensive tokenizer never runs under the cache lock.
70pub struct CachedTokenCounter<T> {
71    inner: T,
72    limits: TokenCacheLimits,
73    cache: Mutex<Cache>,
74}
75
76impl<T: TokenCounter> CachedTokenCounter<T> {
77    /// Wraps an immutable tokenizer with an empty, instance-local cache.
78    pub fn new(inner: T, limits: TokenCacheLimits) -> Self {
79        Self {
80            inner,
81            limits,
82            cache: Mutex::new(Cache::default()),
83        }
84    }
85
86    /// Returns counters without exposing retained text.
87    pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
88        self.cache
89            .lock()
90            .map(|cache| cache.stats)
91            .map_err(|_| ContextError::Tokenizer)
92    }
93
94    /// Drops all retained strings and resets counters. Does not promise allocator zeroization.
95    pub fn clear_cache(&self) -> Result<(), ContextError> {
96        let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
97        let generation = cache
98            .generation
99            .checked_add(1)
100            .ok_or(ContextError::LimitExceeded)?;
101        *cache = Cache {
102            generation,
103            ..Cache::default()
104        };
105        Ok(())
106    }
107}
108
109impl<T: TokenCounter> TokenCounter for CachedTokenCounter<T> {
110    fn identity(&self) -> &str {
111        self.inner.identity()
112    }
113
114    fn count(&self, text: &str) -> Result<usize, ContextError> {
115        let generation = {
116            let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
117            if let Some(value) = cache.values.get(text).copied() {
118                cache.stats.hits = cache.stats.hits.saturating_add(1);
119                return Ok(value);
120            }
121            cache.stats.misses = cache.stats.misses.saturating_add(1);
122            cache.generation
123        };
124        let count = self.inner.count(text)?;
125        if self.limits.max_entries == 0
126            || text.len() > self.limits.max_text_bytes
127            || self.limits.max_text_bytes == 0
128        {
129            return Ok(count);
130        }
131        let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
132        // A concurrent clear must not be undone by an in-flight count retaining old source text.
133        if cache.generation != generation || cache.values.contains_key(text) {
134            return Ok(count);
135        }
136        while cache.values.len() >= self.limits.max_entries
137            || cache.stats.text_bytes > self.limits.max_text_bytes - text.len()
138        {
139            if let Some(old) = cache.order.pop_front() {
140                cache.values.remove(old.as_ref());
141                cache.stats.text_bytes -= old.len();
142            } else {
143                break;
144            }
145        }
146        let key: Arc<str> = Arc::from(text);
147        cache.values.insert(Arc::clone(&key), count);
148        cache.order.push_back(key);
149        cache.stats.text_bytes += text.len();
150        cache.stats.entries = cache.values.len();
151        Ok(count)
152    }
153}
154
155/// Exact UTF-8 byte accounting for diagnostics. These units are not model tokens.
156#[derive(Clone, Copy, Debug, Default)]
157pub struct Utf8ByteCounter;
158
159impl TokenCounter for Utf8ByteCounter {
160    fn identity(&self) -> &str {
161        "cigar.utf8-bytes.v1"
162    }
163
164    fn count(&self, text: &str) -> Result<usize, ContextError> {
165        Ok(text.len())
166    }
167}
168
169/// Exact ordinary o200k counts using the vocabulary and merge rules from pinned
170/// tiktoken-rs 0.12.0, without constructing unused decoding/special-token tables.
171#[cfg(feature = "bpe")]
172pub struct O200kTokenizer(CachedTokenCounter<RawO200kTokenizer>);
173
174#[cfg(feature = "bpe")]
175struct RawO200kTokenizer(ordinary::OrdinaryCounter);
176
177#[cfg(feature = "bpe")]
178impl O200kTokenizer {
179    /// Loads the embedded vocabulary once; reuse this object across requests.
180    pub fn new() -> Result<Self, ContextError> {
181        Self::with_cache_limits(TokenCacheLimits::default())
182    }
183
184    /// Loads the same exact vocabulary with explicit cache bounds (zero disables caching).
185    pub fn with_cache_limits(limits: TokenCacheLimits) -> Result<Self, ContextError> {
186        ordinary::OrdinaryCounter::new()
187            .map(|bpe| Self(CachedTokenCounter::new(RawO200kTokenizer(bpe), limits)))
188            .map_err(|_| ContextError::Tokenizer)
189    }
190
191    /// Content-free cache measurements for this tokenizer instance.
192    pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
193        self.0.cache_stats()
194    }
195
196    /// Drops cached source strings; the reusable vocabulary remains loaded.
197    pub fn clear_cache(&self) -> Result<(), ContextError> {
198        self.0.clear_cache()
199    }
200}
201
202#[cfg(feature = "bpe")]
203impl TokenCounter for O200kTokenizer {
204    fn identity(&self) -> &str {
205        self.0.identity()
206    }
207    fn count(&self, text: &str) -> Result<usize, ContextError> {
208        self.0.count(text)
209    }
210}
211
212#[cfg(feature = "bpe")]
213impl TokenCounter for RawO200kTokenizer {
214    fn identity(&self) -> &str {
215        "o200k_base.tiktoken-rs-0.12.0.ordinary"
216    }
217
218    fn count(&self, text: &str) -> Result<usize, ContextError> {
219        self.0.count(text)
220    }
221}