Files
leleka/control-plane/tests/reasoning_budget_oracle.rs
T
Pavlo Ratushnyi da8c974f68 Drop the stale engine/strata paths and retired generator names from comments, doc strings and generated fixtures (STRA-407)
Rust comments that named scripts/offline/*, gen_goldens.py, oracle/gen_*.{sh,cpp,py}, build_oracle.sh and similar retired generators now say where the data
came from (the Original's code, Strata 41cf05a0) or drop the sentence. The path/generator text of seven generated fixtures (sampler_oracle.json, sampling_keys.json,
memory_plan_golden.json, rope_golden.json, cvec_oracle.json, stra161 fixtures.json, commentary-tool-prompt.json) is reworded; no test reads those fields and no pin
covers their bytes. cmd_time/doc.rs: the two path texts in the format string; its lines are re-broken so they stay within 120 columns (the string is unchanged
otherwise). Comment-only except those data/string spots; no behaviour change.
2026-11-23 22:37:17 +01:00

159 lines
5.2 KiB
Rust

//! The reasoning-budget logic against the Python server's `Service.reasoning_budget` and `Service.run` (#123).
//!
//! `tests/fixtures/offline/reasoning_budget_oracle.json` was recorded from the Original's Python
//! code (Strata 41cf05a0): 247 budget lookups (request and configured values of every JSON type, with the message
//! of the 400) and 400 generations of the unmodified `Service.run` over a scripted engine and a byte-level toy
//! vocabulary, recording each engine call (prompt, max_new), the finish reason, the completion tokens and the text
//! the output parser was fed.
use std::collections::HashSet;
use leleka_control_plane::reasoning_budget::{
Finish, REASONING_WRAP_UP, RunRequest, TokenCodec, TokenEngine, reasoning_budget, run,
};
use serde::Deserialize;
use serde_json::Value;
#[derive(Deserialize)]
struct BudgetCase {
request: Value,
default: Value,
ok: Option<Value>,
error: Option<String>,
}
#[derive(Deserialize)]
struct Expect {
calls: Vec<(Vec<u32>, usize)>,
finish: String,
completion_tokens: usize,
text: String,
}
#[derive(Deserialize)]
struct RunCase {
prompt: Vec<u32>,
thinking: bool,
sampling: Value,
default: Value,
max_new: usize,
cancel: bool,
streams: Vec<Vec<u32>>,
expect: Expect,
}
#[derive(Deserialize)]
struct Golden {
vocab: Vec<String>,
wrap_up_ids: Vec<u32>,
wrap_up: String,
stop_ids: Vec<u32>,
budget: Vec<BudgetCase>,
run: Vec<RunCase>,
}
struct Codec {
pieces: Vec<Vec<u8>>,
wrap_up: Vec<u32>,
}
impl TokenCodec for Codec {
fn token_bytes(&self, id: u32) -> Vec<u8> {
self.pieces[id as usize].clone()
}
fn wrap_up_ids(&self) -> Vec<u32> {
self.wrap_up.clone()
}
}
struct Scripted {
streams: Vec<Vec<u32>>,
calls: Vec<(Vec<u32>, usize)>,
}
impl TokenEngine for Scripted {
fn generate<'a>(&'a mut self, prompt: &[u32], max_new: usize) -> impl Iterator<Item = Result<u32, String>> + 'a {
self.calls.push((prompt.to_vec(), max_new));
let stream = self.streams.get(self.calls.len() - 1).cloned().unwrap_or_default();
Box::new(stream.into_iter().take(max_new).map(Ok))
}
}
fn golden() -> Golden {
serde_json::from_str(include_str!("fixtures/offline/reasoning_budget_oracle.json")).unwrap()
}
#[test]
fn wrap_up_text_is_the_servers() {
assert_eq!(golden().wrap_up, REASONING_WRAP_UP);
}
#[test]
fn budget_lookup_matches_python() {
let golden = golden();
for (index, case) in golden.budget.iter().enumerate() {
let request = if case.request.is_null() { None } else { Some(&case.request) };
let got = reasoning_budget(request, &case.default);
match (&case.error, &case.ok) {
(Some(message), _) => assert_eq!(
got.as_ref().unwrap_err(),
message,
"case {index}: {case_request}",
case_request = case.request
),
(None, Some(expected)) => {
// Python's ints are unbounded; a value above u64 comes through the JSON golden as a float
let want = if expected.is_null() { None } else { Some(expected.as_u64().unwrap_or(u64::MAX)) };
assert_eq!(got, Ok(want), "case {index}: {}", case.request);
}
(None, None) => assert_eq!(got, Ok(None), "case {index}"),
}
}
}
fn finish_name(finish: &Finish) -> &'static str {
match finish {
Finish::Length => "length",
Finish::Stop => "stop",
Finish::Cancel => "cancel",
}
}
fn budget_of(case: &RunCase) -> Option<u64> {
if case.thinking { reasoning_budget(Some(&case.sampling), &case.default).unwrap() } else { None }
}
/// Plays one recorded run against the port and compares the engine calls, finish, tokens and text;
/// true when the run wrapped up.
fn replay_case(codec: &Codec, stops: &HashSet<u32>, case: &RunCase, index: usize) -> bool {
let budget = budget_of(case);
let mut engine = Scripted { streams: case.streams.clone(), calls: Vec::new() };
let request =
RunRequest { prompt: &case.prompt, thinking: case.thinking, budget, max_new: case.max_new, stop_ids: stops };
let cancel = case.cancel;
let got = run(&mut engine, codec, &request, &move || cancel).unwrap();
let finish = finish_name(&got.finish);
assert_eq!(engine.calls, case.expect.calls, "case {index}: engine calls");
assert_eq!(finish, case.expect.finish, "case {index}: finish");
assert_eq!(got.completion_tokens, case.expect.completion_tokens, "case {index}: tokens");
assert_eq!(got.text, case.expect.text, "case {index}: text");
got.wrapped_after.is_some()
}
#[test]
fn run_matches_python() {
let golden = golden();
let codec =
Codec { pieces: golden.vocab.iter().map(|hex| decode_hex(hex)).collect(), wrap_up: golden.wrap_up_ids.clone() };
let stops: HashSet<u32> = golden.stop_ids.iter().copied().collect();
let mut wrapped = 0;
for (index, case) in golden.run.iter().enumerate() {
wrapped += usize::from(replay_case(&codec, &stops, case, index));
}
assert!(wrapped >= 40, "the golden should exercise the wrap-up often, saw {wrapped}");
}
fn decode_hex(hex: &str) -> Vec<u8> {
(0..hex.len() / 2).map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap()).collect()
}