Files
leleka/control-plane/examples/cp_replay.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 b3274c1130
Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Failing after 8s
Desktop foundation / core (ubuntu-latest) (push) Failing after 11s
Rust port / port-oracles (push) Failing after 11s
Rust port / port-linux-tests (push) Failing after 14s
Rust port / port-fast (push) Failing after 9s
Linux / verify (push) Failing after 17s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Merge claude/port-gpu-bringup (CUDA runtime port, upstream sync) into main
Brings the Rust/CUDA port of the Strata mode17 serve path together with the
CPU/iGPU/NPU gpt-oss runtime that main gained meanwhile.

Control plane: the Qwen tokenizer is the implementation behind the Qwen35
variant of codec::TextCodec (qwen(), encode_prompt() widen the trait; QwenCodec
derefs to the tokenizer), so control-token marks, images, chat template, the
runtime backend and vision keep their behavior, while the gpt-oss/Harmony path
and the worker pool keep main's. Config carries the union of fields; extra_workers
is rejected together with runtime, lazy_load, idle_unload_s and vision; the
gpt-oss family refuses top_k/min_p/penalties (its GEN line has no such keys).
leleka-kar-codec takes f16_bits_to_f32 from leleka-quant-core (identical code).
Workspace members and default-members are the union of both sides.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:32:33 +01:00

947 lines
36 KiB
Rust

//! Host-side latency replay (`docs/cp-latency.md`): Codex-shaped Responses requests with a growing history sent over real
//! loopback HTTP to the real router, the real worker adapter and the real tokenizer, in front of an *instant* engine that
//! returns a canned reply the moment it has the prompt. Everything this prints is therefore the cost of the control plane
//! outside the engine, per stage; it says nothing about the engine.
//!
//! ```text
//! cargo run --release -p strata-control --example cp_replay -- TOKENIZER_DIR SESSION.json \
//! [--sizes 20000,60000,120000,180000] [--turns 24] [--out results.json] [--json-response] [--verify]
//! ```
//!
//! SESSION.json comes from `scripts/cp/synth_session.py` (a captured Codex session inverted into Responses items).
//! For every size the history is cut at the round whose rendered prompt is closest to the size, then `--turns` consecutive
//! rounds are replayed on one keep-alive connection: turn 0 is cold (nothing cached), turns 1.. are the steady state of a real
//! session (each request is the previous history plus a few new items). Per request it reports, in milliseconds:
//!
//! * `pre_engine`: client finished sending -> the engine received the prompt (body read, parse, validation, template,
//! tokenization, queue, prompt text for the engine);
//! * `first_event`: engine's first text delta -> that delta's SSE event reached the client;
//! * `tail`: engine's terminal event -> `response.completed` reached the client;
//! * the stage table (`STRATA_STAGE_TRACE` spans, summed per request).
//!
//! `--verify` checks, for every request, that the prompt the engine received is byte-identical to the one produced by the
//! reference path (`STRATA_REFERENCE_PROMPT=1` semantics are implemented in the library; here the harness compares the prompt
//! text against `reference_prompt.json` when given and always records an FNV hash of every prompt and its token ids in the
//! results so two runs of different builds can be diffed).
use std::{
collections::BTreeMap,
io::Write as _,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use leleka_backend_api::{
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
GenerationRequest, GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig,
SupportedModelTuple, Usage,
};
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, run_backend_worker},
stage_trace,
tokenizer::Tokenizer,
worker::{WorkerState, WorkerStatus},
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
sync::{RwLock, mpsc, watch},
};
/// Nanoseconds since the process epoch, shared by the engine thread and the client.
pub fn now_ns() -> u64 {
static EPOCH: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64
}
#[derive(Default)]
pub struct EngineMarks {
pub received: AtomicU64,
pub first_delta: AtomicU64,
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<Option<String>>,
}
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;
for &byte in bytes {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
hash
}
fn reply_text() -> String {
let reasoning = "The task needs a look at the current state of the repository before anything is changed. I will list the \
files, check the git status and then open the module that the failing test exercises. The previous command output shows that the \
test suite is red because the handler returns a 500 instead of a 404 for a missing customer, so the fix is probably in the \
router or in the error mapping. Let me inspect both with one command and then decide on the patch. ";
let mut text = reasoning.repeat(3);
text.push_str(
"\n</think>\n\n<tool_call>\n<function=exec_command>\n<parameter=cmd>\nls -la && git status --short && sed -n '1,120p' router.py\n</parameter>\n</function>\n</tool_call>",
);
text
}
/// An engine with no latency: it records when it got the prompt and answers at once.
pub struct InstantBackend {
descriptor: leleka_backend_api::ModelDescriptor,
marks: Arc<EngineMarks>,
ready: bool,
reply: Vec<String>,
}
impl InstantBackend {
pub fn new(marks: Arc<EngineMarks>) -> Self {
let text = reply_text();
let mut pieces = Vec::new();
let mut current = String::new();
for ch in text.chars() {
current.push(ch);
if current.len() >= 24 {
pieces.push(std::mem::take(&mut current));
}
}
if !current.is_empty() {
pieces.push(current);
}
Self {
descriptor: leleka_backend_api::scripted::ScriptedEngine::fixture_descriptor(),
marks,
ready: false,
reply: pieces,
}
}
}
impl Backend for InstantBackend {
fn identity(&self) -> BackendIdentity {
BackendIdentity {
name: "instant".into(),
implementation_version: "bench".into(),
api_version: leleka_backend_api::BACKEND_API_VERSION,
}
}
fn capabilities(&self) -> BackendCapabilities {
BackendCapabilities {
supported_models: if self.ready {
vec![SupportedModelTuple {
family: self.descriptor.family.clone(),
architecture: self.descriptor.architecture.clone(),
weight_format: self.descriptor.weight_format.clone(),
}]
} else {
Vec::new()
},
max_concurrent_generations: 1,
supports_cancellation: true,
supports_tool_call_streaming: false,
}
}
fn load(
&mut self,
model: leleka_backend_api::ModelDescriptor,
config: RuntimeConfig,
) -> Result<LoadedModel, BackendError> {
self.ready = true;
Ok(LoadedModel {
handle: "instant-handle".into(),
descriptor: model,
load_config_version: config.load_config_version,
effective_mode: config.inference_mode,
mode_identity_digest: format!("sha256:{}", "d".repeat(64)),
})
}
fn start_generation(
&mut self,
_model: &LoadedModel,
request: GenerationRequest,
) -> Result<GenerationStream, BackendError> {
self.marks.received.store(now_ns(), Ordering::SeqCst);
self.marks
.prompt_bytes
.store(request.prompt.len() as u64, Ordering::SeqCst);
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;
}
}
marks.terminal.store(now_ns(), Ordering::SeqCst);
let _ = sink.complete(
FinishReason::Stop,
Usage {
input_tokens: input,
output_tokens: 420,
reused_input_tokens: input * 97 / 100,
},
);
});
Ok(stream)
}
fn cancel(&mut self, _request_id: &str) -> Result<(), BackendError> {
Ok(())
}
fn unload(&mut self, _model: LoadedModel) -> Result<(), BackendError> {
Ok(())
}
}
struct Stack {
addr: std::net::SocketAddr,
marks: Arc<EngineMarks>,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
}
async fn start_stack<F>(tokenizer_dir: &Path, make: &F) -> Stack
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
let tokenizer = Arc::new(Tokenizer::from_assets(tokenizer_dir).expect("tokenizer assets"));
let marks = Arc::new(EngineMarks::default());
let backend = make(marks.clone()).await;
let config = BackendWorkerConfig {
tokenizer: tokenizer.clone(),
model: leleka_backend_api::scripted::ScriptedEngine::fixture_descriptor(),
runtime: RuntimeConfig {
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
inference_mode: InferenceMode::Native,
gpu_memory_limit_bytes: None,
allow_experimental: false,
},
max_context: 262_144,
max_output_tokens: 32768,
health_interval: Duration::from_secs(3600),
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(20),
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: None,
};
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(8);
let (control, control_rx) = mpsc::channel(8);
let worker = tokio::spawn(run_backend_worker(
backend,
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let state = AppState {
model: Some("fixture".into()),
worker: status.clone(),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
generation: Some(requests),
control: Some(control),
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
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 {
while status.read().await.state != WorkerState::Ready {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("worker ready");
Stack {
addr,
marks,
stop,
worker,
server,
}
}
impl Stack {
async fn stop(self) {
let _ = self.stop.send(true);
let _ = tokio::time::timeout(Duration::from_secs(5), self.worker).await;
self.server.abort();
}
}
struct Reply {
status: u16,
body_len: usize,
t_sent: u64,
t_first_byte: u64,
t_created: u64,
t_first_delta: u64,
t_completed: u64,
saw_function_call: bool,
saw_completed: bool,
sent_unix_ms: u128,
done_unix_ms: u128,
/// `input_tokens` / `cached_tokens` of the terminal event's usage, when present.
usage: (u64, u64),
terminal: String,
}
/// `Authorization` value for `--live` runs (the key is read from a file and never printed).
static AUTH: std::sync::OnceLock<String> = std::sync::OnceLock::new();
static MODEL: std::sync::OnceLock<String> = std::sync::OnceLock::new();
static MAX_OUTPUT: AtomicU64 = AtomicU64::new(0);
/// `--store`: send `store: true` (Codex sends false; the Responses API default is true).
static STORE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn unix_ms() -> u128 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis())
}
fn number_after(text: &[u8], key: &[u8]) -> u64 {
find(text, 0, key)
.map(|at| {
text[at + key.len()..]
.iter()
.take_while(|b| b.is_ascii_digit())
.fold(0u64, |n, b| n * 10 + u64::from(b - b'0'))
})
.unwrap_or(0)
}
fn find(haystack: &[u8], from: usize, needle: &[u8]) -> Option<usize> {
let start = from.saturating_sub(needle.len());
haystack[start.min(haystack.len())..]
.windows(needle.len())
.position(|w| w == needle)
.map(|p| p + start)
}
/// One request on an open keep-alive connection; timestamps are taken as the bytes arrive.
async fn request(conn: &mut TcpStream, path: &str, body: &[u8], stream: bool) -> Reply {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAccept: {}\r\n{auth}\r\n",
body.len(),
if stream {
"text/event-stream"
} else {
"application/json"
}
);
conn.write_all(head.as_bytes()).await.unwrap();
conn.write_all(body).await.unwrap();
conn.flush().await.unwrap();
let t_sent = now_ns();
let sent_unix_ms = unix_ms();
let mut t_created = 0;
let mut data: Vec<u8> = Vec::with_capacity(64 * 1024);
let mut buf = vec![0u8; 256 * 1024];
let mut t_first_byte = 0;
let mut t_first_delta = 0;
let mut t_completed = 0;
let mut header_end = None;
let mut chunked = false;
let mut content_length = None;
let mut status = 0;
let mut scanned = 0usize;
loop {
let n = conn.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed mid-response");
if t_first_byte == 0 {
t_first_byte = now_ns();
}
let before = data.len();
data.extend_from_slice(&buf[..n]);
if header_end.is_none() {
if let Some(end) = find(&data, 0, b"\r\n\r\n") {
header_end = Some(end + 4);
let head = String::from_utf8_lossy(&data[..end]).to_ascii_lowercase();
status = head
.split_whitespace()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(0);
chunked = head.contains("transfer-encoding: chunked");
content_length = head
.lines()
.find_map(|l| l.strip_prefix("content-length: "))
.and_then(|v| v.trim().parse::<usize>().ok());
} else {
continue;
}
}
let start = header_end.unwrap();
if t_first_delta == 0 {
let from = scanned.max(start).min(before.max(start));
if find(&data, from, b"response.reasoning_text.delta").is_some()
|| find(&data, from, b"response.output_text.delta").is_some()
|| find(&data, from, b"response.function_call_arguments.delta").is_some()
{
t_first_delta = now_ns();
}
}
if t_created == 0 && find(&data, scanned.max(start), b"response.created").is_some() {
t_created = now_ns();
}
if t_completed == 0
&& (find(&data, scanned.max(start), b"response.completed").is_some()
|| find(&data, scanned.max(start), b"response.incomplete").is_some()
|| find(&data, scanned.max(start), b"response.failed").is_some())
{
t_completed = now_ns();
}
scanned = data.len();
let finished = if chunked {
data.ends_with(b"0\r\n\r\n")
} else if let Some(length) = content_length {
data.len() - start >= length
} else {
false
};
if finished {
let now = now_ns();
if t_completed == 0 {
t_completed = now;
}
if t_first_delta == 0 {
t_first_delta = t_completed;
}
let text = &data[start..];
let terminal = [
"response.completed",
"response.incomplete",
"response.failed",
]
.into_iter()
.find(|name| find(text, 0, name.as_bytes()).is_some())
.unwrap_or("")
.to_owned();
let tail = &text[text.len().saturating_sub(4096)..];
return Reply {
status,
body_len: text.len(),
t_sent,
t_first_byte,
t_created,
t_first_delta,
t_completed,
saw_function_call: find(text, 0, b"\"type\":\"function_call\"").is_some(),
saw_completed: terminal == "response.completed"
|| find(text, 0, b"\"status\":\"completed\"").is_some(),
sent_unix_ms,
done_unix_ms: unix_ms(),
usage: (
number_after(tail, b"\"input_tokens\":"),
number_after(tail, b"\"cached_tokens\":"),
),
terminal,
};
}
}
}
fn percentile(values: &[f64], q: f64) -> f64 {
if values.is_empty() {
return f64::NAN;
}
let mut sorted = values.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
let rank = (q * (sorted.len() - 1) as f64).round() as usize;
sorted[rank]
}
struct Session {
instructions: String,
tools: Vec<Value>,
items: Vec<Value>,
rounds: Vec<usize>,
capture_items: usize,
capture_ids: Vec<u32>,
}
fn load_session(path: &str) -> Session {
let doc: Value = serde_json::from_slice(&std::fs::read(path).expect("session file")).unwrap();
Session {
instructions: doc["instructions"].as_str().unwrap().to_owned(),
tools: doc["tools"].as_array().unwrap().clone(),
items: doc["items"].as_array().unwrap().clone(),
rounds: doc["rounds"]
.as_array()
.unwrap()
.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(),
}
}
/// The request Codex would send at round `round` (history = the items before it).
fn body_at(session: &Session, round: usize, stream: bool) -> Vec<u8> {
let end = session.rounds[round];
let mut body = json!({
"model": MODEL.get().map_or("fixture", String::as_str),
"instructions": session.instructions,
"input": &session.items[..end],
"tools": session.tools,
"tool_choice": "auto",
"parallel_tool_calls": true,
"reasoning": {"effort": "medium", "summary": "auto"},
"store": STORE.load(Ordering::Relaxed),
"stream": stream,
"include": ["reasoning.encrypted_content"],
"prompt_cache_key": "019a0000-0000-7000-8000-00000000e2e0",
"text": {"verbosity": "low"},
});
let limit = MAX_OUTPUT.load(Ordering::Relaxed);
if limit > 0 {
body["max_output_tokens"] = json!(limit);
}
serde_json::to_vec(&body).unwrap()
}
async fn token_count(conn: &mut TcpStream, session: &Session, round: usize) -> usize {
let mut body: Value = serde_json::from_slice(&body_at(session, round, false)).unwrap();
for key in ["stream", "store", "prompt_cache_key", "include"] {
body.as_object_mut().unwrap().remove(key);
}
let bytes = serde_json::to_vec(&body).unwrap();
// reuse the sender, response is small JSON
let reply = request_raw(conn, "/v1/responses/input_tokens", &bytes).await;
let value: Value =
serde_json::from_str(&reply).unwrap_or_else(|_| panic!("input_tokens reply: {reply}"));
value["input_tokens"].as_u64().unwrap() as usize
}
async fn request_raw(conn: &mut TcpStream, path: &str, body: &[u8]) -> String {
let auth = AUTH
.get()
.map(|value| format!("Authorization: Bearer {value}\r\n"))
.unwrap_or_default();
let head = format!(
"POST {path} HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\n{auth}\r\n",
body.len()
);
conn.write_all(head.as_bytes()).await.unwrap();
conn.write_all(body).await.unwrap();
let mut data = Vec::new();
let mut buf = vec![0u8; 64 * 1024];
loop {
let n = conn.read(&mut buf).await.unwrap();
assert!(n > 0);
data.extend_from_slice(&buf[..n]);
if let Some(end) = find(&data, 0, b"\r\n\r\n") {
let head = String::from_utf8_lossy(&data[..end]).to_ascii_lowercase();
let length = head
.lines()
.find_map(|l| l.strip_prefix("content-length: "))
.and_then(|v| v.trim().parse::<usize>().ok())
.unwrap_or(0);
if data.len() >= end + 4 + length {
return String::from_utf8_lossy(&data[end + 4..end + 4 + length]).into_owned();
}
}
}
}
/// `--live URL[,URL2]`: the same requests against servers that are already running (a real engine behind them), alternating between
/// the URLs turn by turn so that both see the same conversation and the engine the same sequence of prompts. One JSON line per turn on
/// stdout (`LIVE {...}`); the join with the servers' `STRATA_STAGE_TRACE=log` lines is done by scripts/cp/live_report.py.
///
/// `--key-file F --model M --size N | --first-round R --turns T --max-output-tokens K --names a,b`
async fn live(targets: &str, session: Session, args: &[String]) {
let key = std::fs::read_to_string(arg(args, "--key-file").expect("--key-file"))
.expect("key file")
.trim()
.to_owned();
AUTH.set(key).ok();
MODEL
.set(arg(args, "--model").unwrap_or_else(|| "qwen-iq3".into()))
.ok();
MAX_OUTPUT.store(
arg(args, "--max-output-tokens")
.and_then(|v| v.parse().ok())
.unwrap_or(48),
Ordering::Relaxed,
);
let urls: Vec<String> = targets.split(',').map(str::to_owned).collect();
let names: Vec<String> = arg(args, "--names")
.map(|v| v.split(',').map(str::to_owned).collect())
.unwrap_or_else(|| (0..urls.len()).map(|i| format!("arm{i}")).collect());
let turns: usize = arg(args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let mut conns = Vec::new();
for url in &urls {
let address = url.trim_start_matches("http://").trim_end_matches('/');
let conn = TcpStream::connect(address).await.expect("connect");
conn.set_nodelay(true).unwrap();
conns.push(conn);
}
let first = match arg(args, "--first-round").and_then(|v| v.parse::<usize>().ok()) {
Some(round) => round,
None => {
let size: usize = arg(args, "--size")
.and_then(|v| v.parse().ok())
.unwrap_or(60000);
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
while low < high {
let mid = (low + high) / 2;
if token_count(&mut conns[0], &session, mid).await < size {
low = mid + 1;
} else {
high = mid;
}
}
low
}
};
let first = first.min(session.rounds.len().saturating_sub(turns));
eprintln!("live: {turns} turns from round {first}, arms {names:?}");
for turn in 0..turns {
let round = first + turn;
if round >= session.rounds.len() {
break;
}
let arm = turn % urls.len();
let body = body_at(&session, round, true);
let reply = request(&mut conns[arm], "/v1/responses", &body, true).await;
let ms = |a: u64, b: u64| b.saturating_sub(a) as f64 / 1e6;
println!(
"LIVE {}",
json!({
"turn": turn, "round": round, "arm": names[arm], "status": reply.status, "terminal": reply.terminal,
"body_bytes": body.len(), "sent_unix_ms": reply.sent_unix_ms as u64, "done_unix_ms": reply.done_unix_ms as u64,
"first_byte_ms": ms(reply.t_sent, reply.t_first_byte), "created_ms": ms(reply.t_sent, reply.t_created),
"ttft_ms": ms(reply.t_sent, reply.t_first_delta), "total_ms": ms(reply.t_sent, reply.t_completed),
"input_tokens": reply.usage.0, "cached_tokens": reply.usage.1,
})
);
std::io::stdout().flush().ok();
}
}
/// 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<F>(tokenizer_dir: &Path, session: &Session, make: &F, args: &[String])
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
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<String> {
args.iter()
.position(|a| a == name)
.and_then(|i| args.get(i + 1).cloned())
}
#[allow(dead_code)]
#[tokio::main]
async fn main() {
run(std::env::args().collect(), async |marks| {
Box::new(InstantBackend::new(marks)) as Box<dyn Backend>
})
.await;
}
/// The replay with the engine `make` builds: the instant engine in process, or (desktop-core's `cp_replay_grpc`) the same engine
/// behind the real gRPC runtime server and `GrpcBackend`.
pub async fn run<F>(args: Vec<String>, make: F)
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
if args.len() < 3 {
eprintln!(
"usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]"
);
std::process::exit(2);
}
stage_trace::enable();
let tokenizer_dir = Path::new(&args[1]).to_owned();
let session = load_session(&args[2]);
let sizes: Vec<usize> = arg(&args, "--sizes")
.unwrap_or_else(|| "20000,60000,120000,180000".into())
.split(',')
.map(|s| s.parse().unwrap())
.collect();
let turns: usize = arg(&args, "--turns")
.and_then(|v| v.parse().ok())
.unwrap_or(24);
let stream = !args.iter().any(|a| a == "--json-response");
let label = arg(&args, "--label").unwrap_or_else(|| "run".into());
if args.iter().any(|a| a == "--store") {
STORE.store(true, Ordering::Relaxed);
}
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 let Some(targets) = arg(&args, "--live") {
live(&targets, session, &args).await;
return;
}
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;
let mut conn = TcpStream::connect(stack.addr).await.unwrap();
conn.set_nodelay(true).unwrap();
// pick the round whose prompt is closest to `size` tokens (counted by the server itself)
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
while low < high {
let mid = (low + high) / 2;
if token_count(&mut conn, &session, mid).await < size {
low = mid + 1;
} else {
high = mid;
}
}
let first = low.min(session.rounds.len().saturating_sub(turns));
let _ = stage_trace::drain();
// a new stack (cold caches) for the measured sequence
stack.stop().await;
let stack = start_stack(&tokenizer_dir, &make).await;
let mut conn = TcpStream::connect(stack.addr).await.unwrap();
conn.set_nodelay(true).unwrap();
let mut rows: Vec<Value> = Vec::new();
for turn in 0..turns {
let round = first + turn;
if round >= session.rounds.len() {
break;
}
let body = body_at(&session, round, stream);
let reply = request(&mut conn, "/v1/responses", &body, stream).await;
let marks = &stack.marks;
let received = marks.received.load(Ordering::SeqCst);
let first_delta = marks.first_delta.load(Ordering::SeqCst);
let terminal = marks.terminal.load(Ordering::SeqCst);
assert_eq!(reply.status, 200, "turn {turn}");
assert!(
reply.saw_completed && reply.saw_function_call,
"turn {turn}: incomplete reply"
);
let stages = stage_trace::drain();
let ms = |ns: u64| ns as f64 / 1e6;
let mut stage_json = serde_json::Map::new();
for (name, (total, count)) in &stages {
stage_json.insert((*name).into(), json!({"ms": total, "n": count}));
}
rows.push(json!({
"turn": turn,
"round": round,
"body_bytes": body.len(),
"prompt_bytes": marks.prompt_bytes.load(Ordering::SeqCst),
"prompt_fnv": format!("{:016x}", marks.prompt_hash.load(Ordering::SeqCst)),
"pre_engine_ms": ms(received.saturating_sub(reply.t_sent)),
"first_event_ms": ms(reply.t_first_delta.saturating_sub(first_delta)),
"tail_ms": ms(reply.t_completed.saturating_sub(terminal)),
"wall_ms": ms(reply.t_completed.saturating_sub(reply.t_sent)),
"first_byte_ms": ms(reply.t_first_byte.saturating_sub(reply.t_sent)),
"response_bytes": reply.body_len,
"stages": stage_json,
}));
}
stack.stop().await;
// summaries
let warm: Vec<&Value> = rows.iter().skip(1).collect();
let col = |key: &str, set: &[&Value]| -> Vec<f64> {
set.iter().map(|r| r[key].as_f64().unwrap()).collect()
};
let mut stage_names: BTreeMap<String, Vec<f64>> = BTreeMap::new();
for row in &warm {
for (name, value) in row["stages"].as_object().unwrap() {
stage_names
.entry(name.clone())
.or_default()
.push(value["ms"].as_f64().unwrap());
}
}
println!(
"== {label} size~{size} tokens (rounds {first}..{}) body {:.0} KB prompt {:.0} KB, {} warm turns",
first + rows.len() - 1,
rows[0]["body_bytes"].as_f64().unwrap() / 1024.0,
rows[0]["prompt_bytes"].as_f64().unwrap() / 1024.0,
warm.len()
);
println!(
"{:<22} {:>9} {:>9} {:>9}",
"metric (ms)", "cold", "p50", "p95"
);
for key in ["pre_engine_ms", "first_event_ms", "tail_ms", "wall_ms"] {
println!(
"{:<22} {:>9.2} {:>9.2} {:>9.2}",
key,
rows[0][key].as_f64().unwrap(),
percentile(&col(key, &warm), 0.5),
percentile(&col(key, &warm), 0.95)
);
}
for (name, values) in &stage_names {
println!(
" stage {:<18} {:>9.2} {:>9.2} {:>9.2}",
name,
rows[0]["stages"]
.get(name)
.map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
percentile(values, 0.5),
percentile(values, 0.95)
);
}
std::io::stdout().flush().ok();
results.push(json!({"size": size, "first_round": first, "rows": rows}));
}
if let Some(out) = arg(&args, "--out") {
let doc = json!({"label": label, "results": results});
let guard = Mutex::new(());
let _g = guard.lock().unwrap();
std::fs::write(out, serde_json::to_vec_pretty(&doc).unwrap()).unwrap();
}
}