From 6bbb26f67ab704dfd0227aa9420ff4d33f933ef4 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 24 Oct 2026 01:30:26 +0200 Subject: [PATCH] cp-latency: native chat rendering for text conversations (verified against the template), log writes off the response path, replay --verify (captured Codex prompt ids) Co-Authored-By: Claude Sonnet 5.5 --- control-plane/examples/cp_replay.rs | 101 ++++++++++++++++- control-plane/src/backend_worker.rs | 36 +++--- control-plane/src/main.rs | 5 + control-plane/src/prompt.rs | 164 ++++++++++++++++++++++++++++ control-plane/src/responses.rs | 1 + control-plane/src/wire.rs | 1 + control-plane/src/worker.rs | 26 +++-- 7 files changed, 304 insertions(+), 30 deletions(-) diff --git a/control-plane/examples/cp_replay.rs b/control-plane/examples/cp_replay.rs index 26487726..7a2301a0 100644 --- a/control-plane/examples/cp_replay.rs +++ b/control-plane/examples/cp_replay.rs @@ -67,11 +67,18 @@ pub struct EngineMarks { pub terminal: AtomicU64, pub prompt_bytes: AtomicU64, pub prompt_hash: AtomicU64, + /// The last prompt text, kept only when `--verify` asks for it. + pub last_prompt: Mutex>, } +static KEEP_PROMPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + /// How long the instant engine waits after taking the prompt before its first token (a real engine needs far longer; the /// wait lets the response's opening events leave first, as they do in production). static ENGINE_DELAY_MS: AtomicU64 = AtomicU64::new(20); +/// Pause between two text deltas (a real engine delivers a few tokens per round, tens of ms apart; with no pause the host +/// pipeline would be measured while it drains a backlog). +static DELTA_GAP_US: AtomicU64 = AtomicU64::new(1000); fn fnv(bytes: &[u8]) -> u64 { let mut hash = 0xcbf29ce484222325u64; @@ -108,7 +115,7 @@ impl InstantBackend { let mut current = String::new(); for ch in text.chars() { current.push(ch); - if current.len() >= 10 { + if current.len() >= 24 { pieces.push(std::mem::take(&mut current)); } } @@ -177,16 +184,22 @@ impl Backend for InstantBackend { self.marks .prompt_hash .store(fnv(request.prompt.as_bytes()), Ordering::SeqCst); + if KEEP_PROMPT.load(Ordering::Relaxed) { + *self.marks.last_prompt.lock().unwrap() = Some(request.prompt.clone()); + } let (sink, stream) = GenerationSink::channel(); let reply = self.reply.clone(); let marks = Arc::clone(&self.marks); let input = (request.prompt.len() / 4) as u64; let delay = ENGINE_DELAY_MS.load(Ordering::Relaxed); + let gap = DELTA_GAP_US.load(Ordering::Relaxed); std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(delay)); for (at, piece) in reply.into_iter().enumerate() { if at == 0 { marks.first_delta.store(now_ns(), Ordering::SeqCst); + } else if gap > 0 { + std::thread::sleep(Duration::from_micros(gap)); } if sink.emit(GenerationEvent::TextDelta { text: piece }).is_err() { return; @@ -272,6 +285,10 @@ where let addr = listener.local_addr().unwrap(); let app = router(state); let server = tokio::spawn(async move { + use axum::serve::ListenerExt as _; + let listener = listener.tap_io(|tcp| { + let _ = tcp.set_nodelay(true); + }); let _ = axum::serve(listener, app).await; }); tokio::time::timeout(Duration::from_secs(10), async { @@ -424,6 +441,8 @@ struct Session { tools: Vec, items: Vec, rounds: Vec, + capture_items: usize, + capture_ids: Vec, } fn load_session(path: &str) -> Session { @@ -438,6 +457,11 @@ fn load_session(path: &str) -> Session { .iter() .map(|v| v.as_u64().unwrap() as usize) .collect(), + capture_items: doc["capture_items"].as_u64().unwrap_or(0) as usize, + capture_ids: doc["capture_prompt_ids"] + .as_array() + .map(|ids| ids.iter().map(|v| v.as_u64().unwrap() as u32).collect()) + .unwrap_or_default(), } } @@ -450,7 +474,7 @@ fn body_at(session: &Session, round: usize, stream: bool) -> Vec { "input": &session.items[..end], "tools": session.tools, "tool_choice": "auto", - "parallel_tool_calls": false, + "parallel_tool_calls": true, "reasoning": {"effort": "medium", "summary": "auto"}, "store": false, "stream": stream, @@ -500,6 +524,72 @@ async fn request_raw(conn: &mut TcpStream, path: &str, body: &[u8]) -> String { } } +/// Equivalence on real data. For every round of the session (`--verify-step n` takes every n-th) the prompt the engine received is +/// tokenized by the production path and by the original implementation (`encode_reference`) and must give the same ids, the ids +/// must decode back to the text, `/v1/responses/input_tokens` must count them, and the round whose history is exactly what the +/// captured Codex request held must reproduce the captured prompt ids (the ids the real engine prefilled). Prints one +/// `PROMPT round fnv ids_fnv` line per round so two builds can be diffed. +async fn verify(tokenizer_dir: &Path, session: &Session, make: &F, args: &[String]) +where + F: AsyncFn(Arc) -> Box, +{ + KEEP_PROMPT.store(true, Ordering::Relaxed); + let reference = Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets"); + let step: usize = arg(args, "--verify-step").and_then(|v| v.parse().ok()).unwrap_or(1); + let stack = start_stack(tokenizer_dir, make).await; + let mut conn = TcpStream::connect(stack.addr).await.unwrap(); + conn.set_nodelay(true).unwrap(); + let mut checked = 0; + let mut captured = false; + for round in 0..session.rounds.len() { + if round % step != 0 && session.rounds[round] != session.capture_items { + continue; + } + let counted = token_count(&mut conn, session, round).await; + let body = body_at(session, round, false); + let reply = request(&mut conn, "/v1/responses", &body, false).await; + assert_eq!(reply.status, 200, "round {round}"); + let prompt = stack.marks.last_prompt.lock().unwrap().take().expect("prompt"); + let fast = reference.encode(&prompt, true).unwrap(); + let slow = reference.encode_reference(&prompt, true).unwrap(); + assert_eq!(fast, slow, "round {round}: fast path ids differ from the reference"); + assert_eq!(fast.len(), counted, "round {round}: input_tokens differs from the ids"); + assert!(reference.decodes_to(&fast, prompt.as_bytes()), "round {round}: ids do not decode to the prompt"); + let mut hash = 0xcbf29ce484222325u64; + for id in &fast { + hash = (hash ^ u64::from(*id)).wrapping_mul(0x100000001b3); + } + println!("PROMPT round={round} tokens={} prompt_fnv={:016x} ids_fnv={hash:016x}", fast.len(), fnv(prompt.as_bytes())); + if session.rounds[round] == session.capture_items && !session.capture_ids.is_empty() { + if fast != session.capture_ids { + let at = fast + .iter() + .zip(&session.capture_ids) + .position(|(a, b)| a != b) + .unwrap_or(fast.len().min(session.capture_ids.len())); + let window = |ids: &[u32]| { + let (from, to) = (at.saturating_sub(12), (at + 12).min(ids.len())); + reference.decode(&ids[from..to]).unwrap_or_default() + }; + panic!( + "round {round}: differs from the captured engine prompt at token {at} (mine {} tokens, capture {}): + mine: {:?} + capture: {:?}", + fast.len(), + session.capture_ids.len(), + window(&fast), + window(&session.capture_ids) + ); + } + captured = true; + println!("CAPTURE round={round} tokens={} identical to the captured prompt ids", fast.len()); + } + checked += 1; + } + stack.stop().await; + println!("VERIFY ok rounds={checked} capture_checked={captured}"); +} + fn arg(args: &[String], name: &str) -> Option { args.iter() .position(|a| a == name) @@ -539,6 +629,13 @@ where if let Some(delay) = arg(&args, "--engine-delay-ms").and_then(|v| v.parse().ok()) { ENGINE_DELAY_MS.store(delay, Ordering::Relaxed); } + if let Some(gap) = arg(&args, "--delta-gap-us").and_then(|v| v.parse().ok()) { + DELTA_GAP_US.store(gap, Ordering::Relaxed); + } + if args.iter().any(|a| a == "--verify") { + verify(&tokenizer_dir, &session, &make, &args).await; + return; + } let mut results = Vec::new(); for &size in &sizes { let stack = start_stack(&tokenizer_dir, &make).await; diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index 508cf8fd..3fbe8a09 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -186,17 +186,21 @@ async fn prepare( } let fixed = leleka_serving_policy::fixed::to_fixed_point(&request.sampling) .map_err(|error| format!("sampling: {error}"))?; - let tokenizer = Arc::clone(&config.tokenizer); - let ids = request.token_ids.clone(); - let known = request.prompt_text.clone(); let prompt_span = crate::stage_trace::span("worker_prompt_text"); - let prompt = tokio::task::spawn_blocking(move || match known { - // The HTTP layer produced `ids` from this very text; the engine is given the text if the ids still decode to it. - Some(text) if tokenizer.decodes_to(&ids, text.as_bytes()) => Ok(text.to_string()), - _ => prompt_text(&tokenizer, &ids), - }) - .await - .map_err(|error| error.to_string())??; + let prompt = match &request.prompt_text { + // The HTTP layer produced the ids from this very text; the engine is given the text if the ids still decode to it + // (a table walk over the ids, well under a millisecond for a whole conversation). + Some(text) if config.tokenizer.decodes_to(&request.token_ids, text.as_bytes()) => { + text.to_string() + } + _ => { + let tokenizer = Arc::clone(&config.tokenizer); + let ids = request.token_ids.clone(); + tokio::task::spawn_blocking(move || prompt_text(&tokenizer, &ids)) + .await + .map_err(|error| error.to_string())?? + } + }; drop(prompt_span); Ok(api::GenerationRequest { request_id: request_id(), @@ -403,12 +407,9 @@ async fn serve_one( let id = request.request_id.clone(); let counted_input = u64::try_from(command.request.token_ids.len()).unwrap_or(u64::MAX); status.write().await.metrics.start(); - crate::elog!( - "generation start: t_unix_ms={} prompt_tokens={} max_new={}", - crate::worker::unix_ms(), - counted_input, - request.max_output_tokens - ); + // The line is written once the engine has the request (its time is taken now), so a slow log sink cannot delay the start. + let start_ms = crate::worker::unix_ms(); + let max_new = request.max_output_tokens; let started = Instant::now(); let start = { let _span = crate::stage_trace::span("engine_start"); @@ -418,6 +419,9 @@ async fn serve_one( }) .await }; + crate::elog!( + "generation start: t_unix_ms={start_ms} prompt_tokens={counted_input} max_new={max_new}" + ); let stream = match start { Ok(Ok(stream)) => stream, Ok(Err(error)) => { diff --git a/control-plane/src/main.rs b/control-plane/src/main.rs index 44c7cd92..c606e722 100644 --- a/control-plane/src/main.rs +++ b/control-plane/src/main.rs @@ -1032,6 +1032,11 @@ async fn serve(config_path: Option<&Path>) -> Result<(), Box bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_REFERENCE_RENDER").is_some_and(|v| v == "1")) +} + +/// The prompt of a text-only conversation without running the Jinja template over the history. +/// +/// For the pinned template a message after the leading system/developer ones renders to text that depends on that message +/// alone, because `preserve_thinking` is never set (an assistant turn always keeps its `` block): +/// +/// ```text +/// user: <|im_start|>user\n{content|trim}<|im_end|>\n +/// assistant: <|im_start|>assistant\n\n{reasoning|trim}\n\n\n{content|trim}<|im_end|>\n +/// ``` +/// +/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the leading +/// system messages, the tools and the effort, so the template renders just that part, with the history left out. The +/// generation prompt is the template's own closing lines. The result is the template's output byte for byte +/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template. +fn render_native(messages: &[Message<'_>], effort: Effort, tools: &[Json]) -> Result { + let leading = messages + .iter() + .take_while(|message| matches!(message.role, Role::System | Role::Developer)) + .count(); + let object = |message: &Message<'_>| { + let mut fields = vec![ + ("role".to_owned(), Json::str(message.role.name())), + ("content".to_owned(), Json::str(message.content)), + ]; + if let Some(reasoning) = message.reasoning { + fields.push(("reasoning_content".to_owned(), Json::str(reasoning))); + } + Json::Object(fields) + }; + // The template refuses an empty message list, so a conversation without system messages gets a placeholder user turn whose + // exact output is cut off again. + const PLACEHOLDER: &str = "<|im_start|>user\n<|im_end|>\n"; + let head: Vec = if leading == 0 { + vec![Json::object([("role", Json::str("user")), ("content", Json::str(""))])] + } else { + messages[..leading].iter().map(object).collect() + }; + let mut prompt = pinned().render(&ChatInput { + messages: &head, + tools: (!tools.is_empty()).then_some(tools), + add_generation_prompt: false, + kwargs: effort.kwargs(), + })?; + if leading == 0 { + prompt = prompt + .strip_suffix(PLACEHOLDER) + .ok_or("the chat template changed its output for an empty user turn")? + .to_owned(); + } + let rest = &messages[leading..]; + prompt.reserve( + rest.iter() + .map(|m| m.content.len() + m.reasoning.map_or(0, str::len) + 64) + .sum::() + + 64, + ); + for message in rest { + let content = message.content.trim_matches(py_space); + match message.role { + Role::User => { + prompt.push_str("<|im_start|>user\n"); + prompt.push_str(content); + prompt.push_str("<|im_end|>\n"); + } + Role::Assistant => { + prompt.push_str("<|im_start|>assistant\n\n"); + prompt.push_str(message.reasoning.unwrap_or("").trim_matches(py_space)); + prompt.push_str("\n\n\n"); + prompt.push_str(content); + prompt.push_str("<|im_end|>\n"); + } + Role::System | Role::Developer => { + return Err("System message must be at the beginning.".into()); + } + } + } + prompt.push_str("<|im_start|>assistant\n"); + prompt.push_str(if matches!(effort, Effort::None) { + "\n\n\n\n" + } else { + "\n" + }); + Ok(prompt) +} + /// [`render_with_tools`] and the sources of the pictures the prompt contains, in prompt order (`images_of`). pub fn render_with_images( messages: &[Message<'_>], @@ -595,6 +686,19 @@ pub fn render_with_images( { return Err("generation needs a final user message".into()); } + if !reference_render() && messages.iter().all(|message| message.parts.is_none()) { + let tools = tools.iter().map(chat_tool).collect::, _>>()?; + return render_native(messages, effort, &tools).map(|prompt| (prompt, Vec::new())); + } + render_via_template(messages, effort, tools) +} + +/// The whole conversation through the Jinja template (the reference the native renderer is tested against). +fn render_via_template( + messages: &[Message<'_>], + effort: Effort, + tools: &[Plain], +) -> Result<(String, Vec), String> { let chat: Vec = messages .iter() .map(|message| { @@ -744,6 +848,66 @@ mod tests { } } + /// Random text-only conversations (white space of every kind at the edges of contents, empty contents and reasoning, + /// template-looking text, special-token text, non-ASCII), all efforts, with and without system messages and tools: + /// the native renderer and the template produce the same bytes (or the same error). + #[test] + fn native_render_equals_the_template() { + struct Rng(u64); + impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n as u64) as usize + } + } + const ATOMS: &[&str] = &[ + "", " ", " ", "\n", "\n\n", "\t", "\r\n", "\u{a0}", "\u{2003}", "\u{1c}", "\u{85}", "\u{200b}", "word", "a b", + "{{ x }}", "{% if %}", "{# c #}", "<|im_start|>", "<|im_end|>", "", "", "", "", + "\u{fc}\u{4e2d}\u{6587}\u{1f600}", "\"quoted\"", "back\\slash", "0", "-1.5e10", "null", "[1, 2]", "{\"a\": 1}", + ]; + let tools_pool = [ + json!({"type":"function","name":"exec","description":"Run a command","parameters":{"type":"object","properties":{"cmd":{"type":"string"},"n":{"type":"number"}},"required":["cmd"]}}), + json!({"type":"function","name":"plan","parameters":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"step":{"type":"string"}}}}}},"strict":false}), + json!({"type":"function","name":"bare"}), + ]; + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let text = |rng: &mut Rng| { + (0..rng.below(5)) + .map(|_| ATOMS[rng.below(ATOMS.len())]) + .collect::() + }; + for case in 0..4000 { + let mut storage: Vec<(Role, String, Option)> = Vec::new(); + for _ in 0..rng.below(3) { + let role = if rng.below(2) == 0 { Role::System } else { Role::Developer }; + storage.push((role, text(&mut rng), None)); + } + for _ in 0..rng.below(5) { + let role = if rng.below(2) == 0 { Role::User } else { Role::Assistant }; + let reasoning = (rng.below(2) == 0).then(|| text(&mut rng)); + storage.push((role, text(&mut rng), if role == Role::Assistant { reasoning } else { None })); + } + storage.push((Role::User, text(&mut rng), None)); + let messages: Vec> = storage + .iter() + .map(|(role, content, reasoning)| Message { + role: *role, + content, + reasoning: reasoning.as_deref(), + parts: None, + }) + .collect(); + let tools: Vec = tools_pool.iter().take(rng.below(4)).cloned().collect(); + let effort = [Effort::None, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh][rng.below(5)]; + let reference = render_via_template(&messages, effort, &tools).map(|(prompt, _)| prompt); + let chat_tools = tools.iter().map(chat_tool).collect::, _>>().unwrap(); + let native = render_native(&messages, effort, &chat_tools); + assert_eq!(native, reference, "case {case}: {storage:?} {effort:?} tools {}", tools.len()); + } + } + #[test] fn flattened_tool_continuation_matches_the_golden_bytes() { let case = golden() diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index 9aa41ff4..3a09de3a 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -2120,6 +2120,7 @@ fn render_request(request: &CreateRequest) -> Result<(String, Vec), Stri }) .collect::>(); let catalog = Catalog::new(&request.tools)?; + let _template = crate::stage_trace::span("render_template"); prompt::render_with_images( &messages, reasoning_effort(request).map_err(|(_, message)| message.to_owned())?, diff --git a/control-plane/src/wire.rs b/control-plane/src/wire.rs index 03a6e5f8..d7472d64 100644 --- a/control-plane/src/wire.rs +++ b/control-plane/src/wire.rs @@ -326,6 +326,7 @@ mod tests { embeddings: case["embeddings"].as_str().map(str::to_owned), keep: Default::default(), reasoning: None, + prompt_text: None, }; assert_eq!( request.line().unwrap(), diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index ac32148d..817588e0 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -915,18 +915,9 @@ pub(crate) async fn finish( disconnected: bool, status: &RwLock, ) -> Result<(), String> { - // One line per generation: the operator's only per-request record (no prompt or output text). - crate::elog!( - "generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}", - unix_ms(), - done.finish, - done.prompt_tokens, - done.reused.unwrap_or(0), - done.generated, - done.prompt_ms, - done.decode_ms, - disconnected - ); + // One line per generation: the operator's only per-request record (no prompt or output text). The time is taken now; the + // line is written after the client side has the terminal event, so a slow log sink never delays a response. + let finished_ms = unix_ms(); let event = Event::Done(done.clone()); match command.result.take() { GenerationResult::Buffered(sender) => { @@ -938,6 +929,17 @@ pub(crate) async fn finish( } GenerationResult::Finished => {} } + crate::elog!( + "generation done: t_unix_ms={} finish={:?} prompt_tokens={} reused={} generated={} prompt_ms={:.1} decode_ms={:.1} disconnected={}", + finished_ms, + done.finish, + done.prompt_tokens, + done.reused.unwrap_or(0), + done.generated, + done.prompt_ms, + done.decode_ms, + disconnected + ); status.write().await.metrics.finish(&done, disconnected); Ok(()) }