Files
leleka/control-plane/examples/cp_replay/main.rs
T

331 lines
11 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 leleka-control-plane --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).
mod instant_backend;
pub use instant_backend::*;
mod stack;
use stack::*;
mod client;
use client::*;
mod live;
use live::*;
mod verify;
use verify::*;
use std::{
collections::BTreeMap,
io::Write as _,
path::Path,
sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use leleka_control_plane::app::{EngineLink, ModelView};
use leleka_backend_api::{
Backend, BackendCapabilities, BackendError, BackendIdentity, FinishReason, GenerationEvent,
GenerationRequest, GenerationSink, GenerationStream, InferenceMode, LoadedModel, RuntimeConfig,
SupportedModelTuple, Usage,
};
use serde_json::{Value, json};
use leleka_control_plane::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, WorkerInbox, run_backend_worker},
stage_trace,
tokenizer::Tokenizer,
worker::{WorkerState, WorkerStatus},
};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
sync::{RwLock, mpsc, watch},
};
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 command-line choices of the plain replay.
struct ReplayPlan {
sizes: Vec<usize>,
turns: usize,
stream: bool,
label: String,
}
fn replay_plan(args: &[String]) -> ReplayPlan {
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());
ReplayPlan {
sizes,
turns,
stream,
label,
}
}
/// `--store`, `--engine-delay-ms` and `--delta-gap-us` reach the client and the instant engine through statics.
fn set_load_flags(args: &[String]) {
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);
}
}
fn exit_with_usage() -> ! {
eprintln!(
"usage: cp_replay TOKENIZER_DIR SESSION.json [--sizes a,b] [--turns n] [--out file] [--json-response]"
);
std::process::exit(2);
}
/// 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 {
exit_with_usage();
}
stage_trace::enable();
let tokenizer_dir = Path::new(&args[1]).to_owned();
let session = load_session(&args[2]);
let plan = replay_plan(&args);
set_load_flags(&args);
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 &plan.sizes {
results.push(replay_size(&tokenizer_dir, &session, &make, &plan, size).await);
}
if let Some(out) = arg(&args, "--out") {
write_results(&out, &plan.label, results);
}
}
fn write_results(out: &str, label: &str, results: Vec<Value>) {
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();
}
async fn connect(addr: std::net::SocketAddr) -> TcpStream {
let conn = TcpStream::connect(addr).await.unwrap();
conn.set_nodelay(true).unwrap();
conn
}
/// Replays one history size: finds its round, then measures `turns` consecutive rounds on a fresh stack.
async fn replay_size<F>(
tokenizer_dir: &Path,
session: &Session,
make: &F,
plan: &ReplayPlan,
size: usize,
) -> Value
where
F: AsyncFn(Arc<EngineMarks>) -> Box<dyn Backend>,
{
let stack = start_stack(tokenizer_dir, make).await;
let mut conn = connect(stack.addr).await;
let first = closest_round(&mut conn, session, size, plan.turns).await;
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 = connect(stack.addr).await;
let rows = replay_turns(&mut conn, &stack, session, first, plan).await;
stack.stop().await;
print_summary(&plan.label, size, first, &rows);
std::io::stdout().flush().ok();
json!({"size": size, "first_round": first, "rows": rows})
}
/// Picks the round whose prompt is closest to `size` tokens (counted by the server itself).
async fn closest_round(
conn: &mut TcpStream,
session: &Session,
size: usize,
turns: usize,
) -> usize {
let (mut low, mut high) = (0usize, session.rounds.len() - 1);
while low < high {
let mid = (low + high) / 2;
if token_count(conn, session, mid).await < size {
low = mid + 1;
} else {
high = mid;
}
}
low.min(session.rounds.len().saturating_sub(turns))
}
async fn replay_turns(
conn: &mut TcpStream,
stack: &Stack,
session: &Session,
first: usize,
plan: &ReplayPlan,
) -> Vec<Value> {
let mut rows: Vec<Value> = Vec::new();
for turn in 0..plan.turns {
let round = first + turn;
if round >= session.rounds.len() {
break;
}
let body = body_at(session, round, plan.stream);
let reply = request(conn, "/v1/responses", &body, plan.stream).await;
assert_eq!(reply.status, 200, "turn {turn}");
assert!(
reply.saw_completed && reply.saw_function_call,
"turn {turn}: incomplete reply"
);
rows.push(turn_row((turn, round), body.len(), &stack.marks, &reply));
}
rows
}
/// The stage spans recorded since the last drain, as `{name: {ms, n}}`.
fn stages_json() -> serde_json::Map<String, Value> {
let mut stage_json = serde_json::Map::new();
for (name, (total, count)) in &stage_trace::drain() {
stage_json.insert((*name).into(), json!({"ms": total, "n": count}));
}
stage_json
}
fn turn_row(
(turn, round): (usize, usize),
body_len: usize,
marks: &EngineMarks,
reply: &Reply,
) -> Value {
let received = marks.received.load(Ordering::SeqCst);
let first_delta = marks.first_delta.load(Ordering::SeqCst);
let terminal = marks.terminal.load(Ordering::SeqCst);
let stage_json = stages_json();
let ms = |ns: u64| ns as f64 / 1e6;
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,
})
}
fn column(key: &str, set: &[&Value]) -> Vec<f64> {
set.iter().map(|r| r[key].as_f64().unwrap()).collect()
}
fn print_summary(label: &str, size: usize, first: usize, rows: &[Value]) {
let warm: Vec<&Value> = rows.iter().skip(1).collect();
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(&column(key, &warm), 0.5),
percentile(&column(key, &warm), 0.95)
);
}
print_stage_rows(&rows[0], &warm);
}
fn print_stage_rows(cold: &Value, warm: &[&Value]) {
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());
}
}
for (name, values) in &stage_names {
println!(
" stage {:<18} {:>9.2} {:>9.2} {:>9.2}",
name,
cold["stages"]
.get(name)
.map_or(f64::NAN, |v| v["ms"].as_f64().unwrap()),
percentile(values, 0.5),
percentile(values, 0.95)
);
}
}