interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-serve-http / tests / reasoning.rs

298 lines · 9975 bytes Raw Blame History
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//! Thinking-block split (sc #642 Qwen3.8 serving): a prompt that ends in `<think>\n` sends the
17//! reply's text up to the closing token as `reasoning_content`, drops that token, trims the
18//! answer's leading newlines, and `aien_return_token_ids` returns every generated id.
19#![allow(dead_code)] // helpers shared in shape with tests/loopback.rs
20
21use std::io::{Read, Write};
22use std::net::{SocketAddr, TcpStream};
23use std::sync::Arc;
24use std::time::Duration;
25
26use aien_inference_abi::tokenizer::ChatOptions;
27use aien_serve_http::codec::{ByteCodec, Codec, CodecError};
28use aien_serve_http::engine::StubEngine;
29use aien_serve_http::server::{serve, ServerConfig};
30const TOKEN: &str = "integration-test-private-credential";
31use serde_json::Value;
32
33/// Byte codec whose generation prompt opens a thinking block unless `enable_thinking` is false;
34/// token 300 closes it.
35struct ThinkCodec;
36
37const THINK_END: u32 = 300;
38
39impl Codec for ThinkCodec {
40 fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> {
41 self.render_chat_with(turns, &ChatOptions::default())
42 }
43 fn render_chat_with(
44 &self,
45 turns: &[(&str, &str)],
46 o: &ChatOptions,
47 ) -> Result<String, CodecError> {
48 let mut t = ByteCodec.render_chat(turns)?;
49 t.push_str(if o.enable_thinking == Some(false) {
50 "<think>\n\n</think>\n\n"
51 } else {
52 "<think>\n"
53 });
54 Ok(t)
55 }
56 fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> {
57 ByteCodec.encode(text)
58 }
59 fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> {
60 ByteCodec.decode(tokens)
61 }
62 fn stop_token_ids(&self) -> Vec<u32> {
63 ByteCodec.stop_token_ids()
64 }
65 fn reasoning_end_id(&self) -> Option<u32> {
66 Some(THINK_END)
67 }
68}
69
70fn reply_ids() -> Vec<u32> {
71 let mut ids: Vec<u32> = "Plan it.\n".bytes().map(u32::from).collect();
72 ids.push(THINK_END);
73 ids.extend("\n\nThe answer.".bytes().map(u32::from));
74 ids
75}
76
77fn start() -> (SocketAddr, tokio::runtime::Runtime) {
78 start_with(None)
79}
80
81fn start_with(thinking: Option<bool>) -> (SocketAddr, tokio::runtime::Runtime) {
82 let rt = tokio::runtime::Runtime::new().expect("runtime");
83 let cfg = ServerConfig {
84 port: 0,
85 model_id: "test-model".into(),
86 default_enable_thinking: thinking,
87 bearer_token: TOKEN.into(),
88 ..ServerConfig::default()
89 };
90 let (addr, _h) = rt
91 .block_on(serve(
92 cfg,
93 Arc::new(StubEngine::new(reply_ids())),
94 Arc::new(ThinkCodec),
95 ))
96 .expect("bind loopback");
97 (addr, rt)
98}
99
100struct Reply {
101 status: u16,
102 headers: String,
103 body: String,
104}
105
106fn dechunk(raw: &[u8]) -> Vec<u8> {
107 let mut out = Vec::new();
108 let mut i = 0;
109 loop {
110 let line_end = raw[i..]
111 .windows(2)
112 .position(|w| w == b"\r\n")
113 .expect("chunk size line")
114 + i;
115 let size =
116 usize::from_str_radix(std::str::from_utf8(&raw[i..line_end]).unwrap().trim(), 16)
117 .expect("hex chunk size");
118 if size == 0 {
119 return out;
120 }
121 out.extend_from_slice(&raw[line_end + 2..line_end + 2 + size]);
122 i = line_end + 2 + size + 2;
123 }
124}
125
126fn request(addr: SocketAddr, method: &str, path: &str, body: Option<&str>) -> Reply {
127 let mut s = TcpStream::connect(addr).expect("connect");
128 s.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
129 let body = body.unwrap_or("");
130 let req = format!(
131 "{method} {path} HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {TOKEN}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
132 body.len()
133 );
134 s.write_all(req.as_bytes()).unwrap();
135 let mut raw = Vec::new();
136 s.read_to_end(&mut raw).expect("read reply");
137 let split = raw
138 .windows(4)
139 .position(|w| w == b"\r\n\r\n")
140 .expect("header end");
141 let headers = String::from_utf8_lossy(&raw[..split]).to_string();
142 let status: u16 = headers
143 .split_whitespace()
144 .nth(1)
145 .and_then(|s| s.parse().ok())
146 .expect("status code");
147 let body_raw = &raw[split + 4..];
148 let body = if headers
149 .to_ascii_lowercase()
150 .contains("transfer-encoding: chunked")
151 {
152 String::from_utf8(dechunk(body_raw)).unwrap()
153 } else {
154 String::from_utf8(body_raw.to_vec()).unwrap()
155 };
156 Reply {
157 status,
158 headers,
159 body,
160 }
161}
162
163fn chat(addr: SocketAddr, body: &str) -> Reply {
164 request(addr, "POST", "/v1/chat/completions", Some(body))
165}
166
167fn json(r: &Reply) -> Value {
168 serde_json::from_str(&r.body).unwrap_or_else(|e| panic!("not JSON ({e}): {}", r.body))
169}
170
171/// `data:` payloads of an SSE body, in order; comment lines are skipped.
172fn sse_data(body: &str) -> Vec<String> {
173 body.lines()
174 .filter_map(|l| l.strip_prefix("data: ").or_else(|| l.strip_prefix("data:")))
175 .map(|s| s.trim().to_string())
176 .collect()
177}
178
179#[test]
180fn thinking_reply_splits_into_reasoning_and_answer() {
181 let (addr, _rt) = start();
182 let r = request(
183 addr,
184 "POST",
185 "/v1/chat/completions",
186 Some(r#"{"messages":[{"role":"user","content":"q"}],"aien_return_token_ids":true}"#),
187 );
188 assert_eq!(r.status, 200, "{}", r.body);
189 let v: Value = serde_json::from_str(&r.body).unwrap();
190 let m = &v["choices"][0]["message"];
191 assert_eq!(m["reasoning_content"], "Plan it.");
192 assert_eq!(m["content"], "The answer.");
193 let ids: Vec<u32> = v["usage"]["aien_token_ids"]
194 .as_array()
195 .unwrap()
196 .iter()
197 .map(|x| x.as_u64().unwrap() as u32)
198 .collect();
199 assert_eq!(ids, reply_ids());
200}
201
202#[test]
203fn thinking_off_keeps_everything_as_content_and_ids_stay_opt_in() {
204 let (addr, _rt) = start();
205 let r = request(
206 addr,
207 "POST",
208 "/v1/chat/completions",
209 Some(
210 r#"{"messages":[{"role":"user","content":"q"}],"chat_template_kwargs":{"enable_thinking":false}}"#,
211 ),
212 );
213 assert_eq!(r.status, 200, "{}", r.body);
214 let v: Value = serde_json::from_str(&r.body).unwrap();
215 let m = &v["choices"][0]["message"];
216 assert!(m.get("reasoning_content").is_none());
217 assert_eq!(m["content"], "Plan it.\n\n\nThe answer.");
218 assert!(v["usage"].get("aien_token_ids").is_none());
219 let bad = request(
220 addr,
221 "POST",
222 "/v1/chat/completions",
223 Some(
224 r#"{"messages":[{"role":"user","content":"q"}],"chat_template_kwargs":{"enable_thinking":"no"}}"#,
225 ),
226 );
227 assert_eq!(bad.status, 400);
228}
229
230#[test]
231fn streamed_thinking_reply_sends_reasoning_deltas_first() {
232 let (addr, _rt) = start();
233 let r = request(
234 addr,
235 "POST",
236 "/v1/chat/completions",
237 Some(r#"{"messages":[{"role":"user","content":"q"}],"stream":true}"#),
238 );
239 assert_eq!(r.status, 200);
240 let (mut reasoning, mut content) = (String::new(), String::new());
241 for d in sse_data(&r.body) {
242 if d == "[DONE]" {
243 break;
244 }
245 let v: Value = serde_json::from_str(&d).unwrap();
246 let delta = &v["choices"][0]["delta"];
247 if let Some(t) = delta["reasoning_content"].as_str() {
248 assert!(content.is_empty(), "reasoning after the answer started");
249 reasoning.push_str(t);
250 }
251 if let Some(t) = delta["content"].as_str() {
252 content.push_str(t);
253 }
254 }
255 assert_eq!(reasoning.trim(), "Plan it.");
256 assert_eq!(content, "The answer.");
257}
258
259#[test]
260fn server_default_thinking_off_applies_unless_the_request_asks() {
261 let (addr, _rt) = start_with(Some(false));
262 let body = r#"{"messages":[{"role":"user","content":"q"}]}"#;
263 let v: Value =
264 serde_json::from_str(&request(addr, "POST", "/v1/chat/completions", Some(body)).body)
265 .unwrap();
266 assert!(v["choices"][0]["message"]
267 .get("reasoning_content")
268 .is_none());
269 let body = r#"{"messages":[{"role":"user","content":"q"}],"chat_template_kwargs":{"enable_thinking":true}}"#;
270 let v: Value =
271 serde_json::from_str(&request(addr, "POST", "/v1/chat/completions", Some(body)).body)
272 .unwrap();
273 assert_eq!(v["choices"][0]["message"]["reasoning_content"], "Plan it.");
274}
275
276/// The merge train's `aien_test` field (L384): an engine without the switches refuses it
277/// (400), in a test build as in the live build; the same request without the field is served.
278#[test]
279fn aien_test_switches_are_refused_by_an_engine_without_them() {
280 let (addr, _rt) = start();
281 let r = request(
282 addr,
283 "POST",
284 "/v1/chat/completions",
285 Some(r#"{"messages":[{"role":"user","content":"q"}],"aien_test":{"mutant":4}}"#),
286 );
287 assert_eq!(r.status, 400, "{}", r.body);
288 assert!(r.body.contains("aien_test"), "{}", r.body);
289 let r = request(
290 addr,
291 "POST",
292 "/v1/chat/completions",
293 Some(r#"{"messages":[{"role":"user","content":"q"}]}"#),
294 );
295 assert_eq!(r.status, 200, "{}", r.body);
296 let v: Value = serde_json::from_str(&r.body).unwrap();
297 assert!(v["usage"].get("aien_test").is_none(), "{}", r.body);
298}