aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-serve-http / src / text.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Turns the engine's token stream into text deltas: decodes incrementally |
| 17 | //! (holding back a token run that ends inside a multi-byte character) and |
| 18 | //! applies stop strings (holding back any text that could still grow into one). |
| 19 | |
| 20 | use std::sync::Arc; |
| 21 | |
| 22 | use crate::codec::Codec; |
| 23 | |
| 24 | /// How many tokens may be held back waiting for a character to complete before |
| 25 | /// the run is flushed as-is (guards against a model emitting invalid bytes forever). |
| 26 | const MAX_PARTIAL_TOKENS: usize = 8; |
| 27 | |
| 28 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 29 | pub enum Push { |
| 30 | /// Nothing to emit yet. |
| 31 | Hold, |
| 32 | /// Emit this text and keep going. |
| 33 | Delta(String), |
| 34 | /// Emit this text (possibly empty) and stop: a stop string matched. |
| 35 | StopAt(String), |
| 36 | } |
| 37 | |
| 38 | pub struct TextAssembler { |
| 39 | codec: Arc<dyn Codec>, |
| 40 | stop_strings: Vec<String>, |
| 41 | tokens: Vec<u32>, |
| 42 | /// Tokens before this index have been decoded into `pending` or emitted. |
| 43 | decoded_upto: usize, |
| 44 | /// Decoded text not yet emitted (may be a prefix of a stop string). |
| 45 | pending: String, |
| 46 | stopped: bool, |
| 47 | } |
| 48 | |
| 49 | impl TextAssembler { |
| 50 | pub fn new(codec: Arc<dyn Codec>, stop_strings: Vec<String>) -> Self { |
| 51 | Self { |
| 52 | codec, |
| 53 | stop_strings, |
| 54 | tokens: Vec::new(), |
| 55 | decoded_upto: 0, |
| 56 | pending: String::new(), |
| 57 | stopped: false, |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | pub fn push(&mut self, token: u32) -> Push { |
| 62 | if self.stopped { |
| 63 | return Push::Hold; |
| 64 | } |
| 65 | self.tokens.push(token); |
| 66 | let window = &self.tokens[self.decoded_upto..]; |
| 67 | let text = match self.codec.decode(window) { |
| 68 | Ok(t) => t, |
| 69 | Err(_) => return Push::Hold, |
| 70 | }; |
| 71 | let partial = text.ends_with('\u{FFFD}'); |
| 72 | if partial && window.len() < MAX_PARTIAL_TOKENS { |
| 73 | return Push::Hold; |
| 74 | } |
| 75 | self.decoded_upto = self.tokens.len(); |
| 76 | self.pending.push_str(&text); |
| 77 | self.drain() |
| 78 | } |
| 79 | |
| 80 | /// Emits whatever is still held back. Call once when the engine is done. |
| 81 | pub fn finish(&mut self) -> Option<String> { |
| 82 | if self.stopped { |
| 83 | return None; |
| 84 | } |
| 85 | // A run that never completed its character still has to be shown. |
| 86 | if self.decoded_upto < self.tokens.len() { |
| 87 | if let Ok(t) = self.codec.decode(&self.tokens[self.decoded_upto..]) { |
| 88 | self.pending.push_str(&t); |
| 89 | } |
| 90 | self.decoded_upto = self.tokens.len(); |
| 91 | } |
| 92 | if self.pending.is_empty() { |
| 93 | None |
| 94 | } else { |
| 95 | Some(std::mem::take(&mut self.pending)) |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | fn drain(&mut self) -> Push { |
| 100 | if let Some(idx) = self |
| 101 | .stop_strings |
| 102 | .iter() |
| 103 | .filter_map(|s| self.pending.find(s.as_str())) |
| 104 | .min() |
| 105 | { |
| 106 | self.stopped = true; |
| 107 | let out = self.pending[..idx].to_string(); |
| 108 | self.pending.clear(); |
| 109 | return Push::StopAt(out); |
| 110 | } |
| 111 | // Keep the longest suffix that is a proper prefix of some stop string. |
| 112 | let keep_from = self |
| 113 | .pending |
| 114 | .char_indices() |
| 115 | .map(|(i, _)| i) |
| 116 | .find(|&i| { |
| 117 | let tail = &self.pending[i..]; |
| 118 | self.stop_strings |
| 119 | .iter() |
| 120 | .any(|s| s.len() > tail.len() && s.starts_with(tail)) |
| 121 | }) |
| 122 | .unwrap_or(self.pending.len()); |
| 123 | if keep_from == 0 { |
| 124 | return Push::Hold; |
| 125 | } |
| 126 | let out = self.pending[..keep_from].to_string(); |
| 127 | self.pending = self.pending[keep_from..].to_string(); |
| 128 | Push::Delta(out) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | #[cfg(test)] |
| 133 | mod tests { |
| 134 | use super::*; |
| 135 | use crate::codec::ByteCodec; |
| 136 | |
| 137 | fn asm(stops: &[&str]) -> TextAssembler { |
| 138 | TextAssembler::new( |
| 139 | Arc::new(ByteCodec), |
| 140 | stops.iter().map(|s| s.to_string()).collect(), |
| 141 | ) |
| 142 | } |
| 143 | |
| 144 | fn run(mut a: TextAssembler, text: &str) -> (String, bool) { |
| 145 | let mut out = String::new(); |
| 146 | let mut stopped = false; |
| 147 | for b in text.bytes() { |
| 148 | match a.push(u32::from(b)) { |
| 149 | Push::Hold => {} |
| 150 | Push::Delta(d) => out.push_str(&d), |
| 151 | Push::StopAt(d) => { |
| 152 | out.push_str(&d); |
| 153 | stopped = true; |
| 154 | break; |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | if let Some(rest) = a.finish() { |
| 159 | out.push_str(&rest); |
| 160 | } |
| 161 | (out, stopped) |
| 162 | } |
| 163 | |
| 164 | #[test] |
| 165 | fn multibyte_characters_are_never_split() { |
| 166 | let mut a = asm(&[]); |
| 167 | let mut deltas = Vec::new(); |
| 168 | for b in "héllo wörld".bytes() { |
| 169 | if let Push::Delta(d) = a.push(u32::from(b)) { |
| 170 | deltas.push(d); |
| 171 | } |
| 172 | } |
| 173 | assert!(deltas.iter().all(|d| !d.contains('\u{FFFD}')), "{deltas:?}"); |
| 174 | assert_eq!(deltas.concat(), "héllo wörld"); |
| 175 | } |
| 176 | |
| 177 | #[test] |
| 178 | fn stop_string_truncates_and_holds_back_prefix() { |
| 179 | assert_eq!( |
| 180 | run(asm(&["world"]), "hello world!"), |
| 181 | ("hello ".into(), true) |
| 182 | ); |
| 183 | assert_eq!(run(asm(&["<|end|>"]), "a<|en"), ("a<|en".into(), false)); |
| 184 | assert_eq!(run(asm(&["xx", "b"]), "aaxxb"), ("aa".into(), true)); |
| 185 | } |
| 186 | |
| 187 | #[test] |
| 188 | fn no_stops_passes_everything() { |
| 189 | assert_eq!(run(asm(&[]), "plain text"), ("plain text".into(), false)); |
| 190 | } |
| 191 | } |