diff --git a/control-plane/config.runtime.example.json b/control-plane/config.runtime.example.json index 3c86e4ab..3fda5c5c 100644 --- a/control-plane/config.runtime.example.json +++ b/control-plane/config.runtime.example.json @@ -15,6 +15,6 @@ }, "mode": {"type": "mtp", "profile_id": "qwen4exp-kar-ple-mtp-v1"}, "max_context": 262144, - "max_output_tokens": 4096 + "max_output_tokens": 32768 } } diff --git a/control-plane/src/backend_worker.rs b/control-plane/src/backend_worker.rs index b62bd6b1..bff3047e 100644 --- a/control-plane/src/backend_worker.rs +++ b/control-plane/src/backend_worker.rs @@ -287,6 +287,7 @@ pub async fn run_backend_worker( attached_before = true; update(&status, WorkerState::Ready, Some(config.max_context)).await; status.write().await.output_cap = Some(config.max_output_tokens); + status.write().await.text_level_engine = true; status.write().await.last_activity = Some(Instant::now()); for reply in waiting.drain(..) { let _ = reply.send(Ok(())); @@ -389,6 +390,12 @@ 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 + ); let started = Instant::now(); let start = { let model = loaded.clone(); diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index aeeba520..188baf4d 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -1087,6 +1087,21 @@ pub async fn count_input_tokens( } } +/// Every failed generation leaves one line in the log (the message is the one the client gets: no prompt or output text). +/// With `STRATA_DEBUG_FAILED_OUTPUT=1` the generated text of a failed streaming tool turn is logged too: operator debugging +/// only, because it is model output. +fn log_generation_failure(message: &str) { + crate::elog!("generation failed: {message}"); +} + +fn debug_failed_output() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("STRATA_DEBUG_FAILED_OUTPUT").is_some_and(|v| v == "1")) +} + +/// The engines refuse a request unless `prompt + max_new + 8 <= context`. +const CONTEXT_MARGIN_TOKENS: usize = 8; + fn queue_error(error: crate::queue::Error) -> Response { match error { crate::queue::Error::Expired => api_error( @@ -1153,18 +1168,59 @@ pub async fn create( Ok(prepared) => prepared, Err(error) => return *error, }; - let (remaining, output_cap) = { + let (max_context, output_cap, text_level_engine) = { let worker = state.worker.read().await; - let remaining = worker - .max_context - .map(|context| { - context - .saturating_sub(token_ids.len()) - .min(u32::MAX as usize) as u32 - }) - .unwrap_or(32768); - (remaining, worker.output_cap.unwrap_or(u32::MAX)) + ( + worker.max_context, + worker.output_cap.unwrap_or(u32::MAX), + worker.text_level_engine, + ) }; + // The worker refuses `prompt + max_new + 8 > context` and an output budget above the runtime's cap, but only after the + // request was queued, as a 502. These are client errors: answer them here, as 400, before anything is queued. + let prompt_tokens = token_ids.len(); + let remaining = max_context + .map(|context| { + context + .saturating_sub(prompt_tokens) + .saturating_sub(CONTEXT_MARGIN_TOKENS) + .min(u32::MAX as usize) as u32 + }) + .unwrap_or(32768); + if let Some(context) = max_context + && (remaining == 0 + || request + .max_output_tokens + .is_some_and(|new| u64::from(new) > u64::from(remaining))) + { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "context_length_exceeded", + Some("input"), + &format!( + "the prompt has {prompt_tokens} tokens and the output budget is {}; the model's context is {context} tokens (prompt + output budget + {CONTEXT_MARGIN_TOKENS} tokens of margin must fit)", + request + .max_output_tokens + .map_or_else(|| "unset".to_owned(), |n| n.to_string()), + ), + ); + } + if request + .max_output_tokens + .is_some_and(|new| new > output_cap) + { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_output_limit", + Some("max_output_tokens"), + &format!( + "max_output_tokens {} exceeds the runtime's limit of {output_cap}", + request.max_output_tokens.unwrap_or_default() + ), + ); + } let generate = Generate { token_ids, max_new: request @@ -1177,6 +1233,37 @@ pub async fn create( keep, reasoning: reasoning_plan(&request, &state, tokenizer), }; + if text_level_engine { + // What the text-level engine contract cannot carry is the client's error to hear about now, not a 502 after queueing. + let unsupported = if generate.reasoning.is_some() { + Some(("reasoning_budget_tokens", "reasoning_budget_tokens needs token-level continuation, which the text-level engine contract does not provide")) + } else if generate.tune.is_some() { + Some(("strata_tune", "strata_tune is an engine-process setting and is not part of the engine contract")) + } else if generate.cvec.is_some() { + Some(("experimental_speed_projection", "experimental_speed_projection (control vectors) is not part of the engine contract")) + } else { + None + }; + if let Some((param, message)) = unsupported { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "unsupported_request_field", + Some(param), + message, + ); + } + // The text contract carries sampling as thousandths / millionths; anything finer cannot be served as asked. + if let Err(error) = leleka_serving_policy::fixed::to_fixed_point(&generate.sampling) { + return api_error( + StatusCode::BAD_REQUEST, + "invalid_request_error", + "invalid_sampling_precision", + None, + &format!("sampling: {error}"), + ); + } + } if request.stream { let (events, received) = mpsc::channel(16); if let Err(error) = crate::queue::enqueue( @@ -1213,6 +1300,7 @@ pub async fn create( let events = match received.await { Ok(Ok(events)) => events, Ok(Err(message)) => { + log_generation_failure(&message); return api_error( StatusCode::BAD_GATEWAY, "server_error", @@ -1301,9 +1389,20 @@ pub async fn create( now.as_nanos(), NEXT_RESPONSE_ID.fetch_add(1, Ordering::Relaxed) ); + let debug_copy = debug_failed_output().then(|| { + format!( + "reasoning={:?} answer={:?}", + output.reasoning.as_ref().map(|(text, _)| text), + output.answer + ) + }); let (items, reasoning_tokens) = match decoded_items(&request, output, &id) { Ok(items) => items, Err(message) => { + log_generation_failure(&message); + if let Some(text) = &debug_copy { + crate::elog!("failed output (STRATA_DEBUG_FAILED_OUTPUT): {text:?}"); + } return api_error( StatusCode::BAD_GATEWAY, "server_error", @@ -2138,6 +2237,7 @@ fn stream_live_text( } let message = failure .unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned()); + log_generation_failure(&message); let mut failed = pending_response; failed["status"] = json!("failed"); failed["error"] = json!({"code": "generation_failed", "message": message}); @@ -2322,9 +2422,11 @@ fn stream_live_buffered( Err(error) => failure = Some(error), } } + let failure = failure.unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned()); + log_generation_failure(&failure); let mut failed = pending; failed["status"] = json!("failed"); - failed["error"] = json!({"code":"generation_failed", "message":failure.unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned())}); + failed["error"] = json!({"code":"generation_failed", "message":failure}); let _ = send_stream_event( &sender, &mut sequence, @@ -2509,6 +2611,7 @@ fn stream_live_tools( ]; let catalog = Catalog::new(&request.tools).expect("validated tools"); let mut parser = Incremental::new(&catalog.flat); + let mut debug_text = debug_failed_output().then(String::new); let mut pending_bytes = Vec::new(); let mut text_ended = false; let mut done = None; @@ -2532,6 +2635,9 @@ fn stream_live_tools( pending_bytes.extend_from_slice(&bytes); let delta = drain_utf8(&mut pending_bytes, false); if !delta.is_empty() { + if let Some(text) = debug_text.as_mut() { + text.push_str(&delta); + } match parser.feed(&delta) { Ok(segments) => { for segment in segments { @@ -2645,6 +2751,10 @@ fn stream_live_tools( } let message = failure .unwrap_or_else(|| "the worker stopped without a supported DONE event".to_owned()); + log_generation_failure(&message); + if let Some(text) = &debug_text { + crate::elog!("failed output (STRATA_DEBUG_FAILED_OUTPUT): {text:?}"); + } let mut failed = pending_response; failed["status"] = json!("failed"); failed["error"] = json!({"code":"generation_failed","message":message}); diff --git a/control-plane/src/runtime_config.rs b/control-plane/src/runtime_config.rs index 99912d54..66c24187 100644 --- a/control-plane/src/runtime_config.rs +++ b/control-plane/src/runtime_config.rs @@ -81,7 +81,7 @@ impl std::fmt::Debug for RuntimeBackend { } /// The output limit of the runtime gRPC facade today (`RuntimeServer::generate`). -pub const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 4096; +pub const DEFAULT_MAX_OUTPUT_TOKENS: u32 = leleka_backend_api::MAX_OUTPUT_TOKENS; fn seconds(name: &str, value: Option, default: f64) -> Result { let value = value.unwrap_or(default); diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index e2b9525a..cad040dd 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -325,7 +325,7 @@ async fn status_value(state: &AppState) -> Value { value["at"] = json!(now_s()); value }); - json!({ + let mut body = json!({ "service": "strata", "model": state.model, "loaded": is_loaded(&worker), "auto_load": state.control.is_some(), "structured_output": {"formats": ["json_object", "json_schema"], "method": "prompt_and_validate", @@ -342,8 +342,13 @@ async fn status_value(state: &AppState) -> Value { "last_request_at": last_at}, "last_timings": timings, "machine": {"at": now_s(), "gpu": null, "ram": null}, - "prefix_cache": state.prefix_cache.status(), - }) + }); + // Present only when a prefix cache exists: the Python server's status has no such key (golden http_surface). + let prefix = json!(state.prefix_cache.status()); + if !prefix.is_null() { + body["prefix_cache"] = prefix; + } + body } /// `GET /settings`. diff --git a/control-plane/src/worker.rs b/control-plane/src/worker.rs index ccd93b92..ac32148d 100644 --- a/control-plane/src/worker.rs +++ b/control-plane/src/worker.rs @@ -82,6 +82,9 @@ pub struct WorkerStatus { /// runtime gRPC facade does). A default output budget never exceeds it; an explicit request above /// it is refused by the worker, not truncated. pub output_cap: Option, + /// The engine speaks the text-level contract (a runtime backend): per-request token-level features it cannot carry + /// (`reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection`) are refused with a 400 by the HTTP layer. + pub text_level_engine: bool, } impl Default for WorkerStatus { @@ -93,6 +96,7 @@ impl Default for WorkerStatus { last_activity: None, metrics: Default::default(), output_cap: None, + text_level_engine: false, } } } @@ -911,6 +915,18 @@ 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 + ); let event = Event::Done(done.clone()); match command.result.take() { GenerationResult::Buffered(sender) => { @@ -926,6 +942,13 @@ pub(crate) async fn finish( Ok(()) } +/// Wall-clock milliseconds for log lines that are joined with client-side timestamps. +pub(crate) fn unix_ms() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis()) +} + pub(crate) async fn send_failure(result: GenerationResult, message: String) { match result { GenerationResult::Buffered(sender) => { diff --git a/control-plane/tests/backend_worker_http.rs b/control-plane/tests/backend_worker_http.rs index 265ee6c8..184c2232 100644 --- a/control-plane/tests/backend_worker_http.rs +++ b/control-plane/tests/backend_worker_http.rs @@ -912,8 +912,8 @@ async fn text_the_contract_cannot_carry_is_refused_not_dropped() { &body(json!({"reasoning": {"effort": "high"}, "reasoning_budget_tokens": 5})), ) .await; - assert_eq!(status, 502, "{text}"); - assert!(text.contains("reasoning_budget_tokens"), "{text}"); + assert_eq!(status, 400, "{text}"); + assert!(text.contains("reasoning_budget_tokens") && text.contains("unsupported_request_field"), "{text}"); // Per-request engine tuning is not part of the contract. let (status, text) = stack .post( @@ -921,13 +921,13 @@ async fn text_the_contract_cannot_carry_is_refused_not_dropped() { &body(json!({"strata_tune": {"pcie_frac": 0.5}})), ) .await; - assert_eq!(status, 502, "{text}"); + assert_eq!(status, 400, "{text}"); assert!(text.contains("strata_tune"), "{text}"); // Sampling that is not exact thousandths is refused like the daemon does. let (status, text) = stack .post("/v1/responses", &body(json!({"temperature": 0.0005}))) .await; - assert_eq!(status, 502, "{text}"); + assert_eq!(status, 400, "{text}"); assert!(text.contains("temperature"), "{text}"); // None of these reached the engine. assert!(stack.engine.requests().is_empty()); @@ -1145,9 +1145,10 @@ async fn the_runtimes_output_cap_clamps_the_default_and_refuses_an_explicit_exce let (status, text) = stack .post("/v1/responses", &body(json!({"max_output_tokens": 1001}))) .await; - assert_eq!(status, 502, "{text}"); + // a client error: refused by the HTTP layer as a 400 before anything is queued (it used to surface as a 502) + assert_eq!(status, 400, "{text}"); assert!( - text.contains("exceeds the runtime's limit of 1000"), + text.contains("exceeds the runtime's limit of 1000") && text.contains("invalid_output_limit"), "{text}" ); assert_eq!( @@ -1165,6 +1166,41 @@ async fn the_runtimes_output_cap_clamps_the_default_and_refuses_an_explicit_exce stack.finish().await; } +/// A prompt that cannot fit the context is the client's error: 400 `context_length_exceeded` from the HTTP layer +/// (found by the e2e run: it used to be a 502 `generation_failed` after queueing), and a default output budget leaves +/// the engine's 8-token margin so a prompt that just fits is served instead of refused. +#[tokio::test] +async fn a_prompt_that_cannot_fit_the_context_is_a_400_and_the_default_budget_keeps_the_margin() { + let stack = Stack::start_with("bw-context", |config| config.max_context = 600).await; + // explicit budget that does not fit + let (status, text) = stack + .post("/v1/responses", &body(json!({"max_output_tokens": 4000}))) + .await; + assert_eq!(status, 400, "{text}"); + assert!(text.contains("context_length_exceeded"), "{text}"); + // a prompt longer than the context + let long = "word ".repeat(2000); + let (status, text) = stack + .post("/v1/responses", &body(json!({"input": long}))) + .await; + assert_eq!(status, 400, "{text}"); + assert!(text.contains("context_length_exceeded"), "{text}"); + assert!(stack.engine.requests().is_empty(), "nothing reached the engine"); + // a request that fits, with the default budget: prompt + max_new + 8 == context at most + stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0))); + let (status, text) = stack.post("/v1/responses", &body(json!({}))).await; + assert_eq!(status, 200, "{text}"); + let seen = &stack.engine.requests()[0]; + let prompt_tokens = stack.tokenizer.encode(&seen.prompt, true).unwrap().len(); + assert!( + prompt_tokens + seen.max_output_tokens as usize + 8 <= 600, + "{} + {} + 8 > 600", + prompt_tokens, + seen.max_output_tokens + ); + stack.finish().await; +} + #[tokio::test] async fn every_sampling_control_reaches_the_engine_as_fixed_point() { let stack = Stack::start("bw-sampling").await; diff --git a/crates/backend-api/src/lib.rs b/crates/backend-api/src/lib.rs index c3531ec5..63f4a76b 100644 --- a/crates/backend-api/src/lib.rs +++ b/crates/backend-api/src/lib.rs @@ -11,9 +11,16 @@ use std::sync::{ }; mod load_mode; +mod recent_ids; #[cfg(feature = "scripted")] pub mod scripted; pub use load_mode::{InferenceMode, KarExpertLoad, KarPrefillMode, LOAD_CONFIG_VERSION}; +pub use recent_ids::{DEFAULT_RECENT_IDS, RecentIds}; + +/// The most output tokens one generation may ask for. A single agent turn that writes a whole source file in one tool call +/// needs well over the 4,096 this used to be (found by the Codex run of the e2e job 943: three 4,096-token turns in a row +/// ended the session); 32,768 is the default budget of the HTTP layer. +pub const MAX_OUTPUT_TOKENS: u32 = 32_768; /// Version understood by this crate and advertised in [`BackendIdentity`]. // Version 2 replaces independent capability axes with explicit model tuples. diff --git a/crates/backend-api/src/recent_ids.rs b/crates/backend-api/src/recent_ids.rs new file mode 100644 index 00000000..64262fcb --- /dev/null +++ b/crates/backend-api/src/recent_ids.rs @@ -0,0 +1,140 @@ +//! A bounded ledger of generation identities. +//! +//! The runtime refuses an identity it has already accepted (`generation_not_replayed`): a request id may have had visible effects, +//! so a repeated one must never run twice. Remembering every identity for the life of a runtime epoch caps the number of +//! generations a process can serve; the first deployment limit was 256, which an agent session exhausts in minutes. This ledger +//! keeps the most recent [`RecentIds::capacity`] identities and forgets the oldest first. Identities are random UUIDs minted per +//! attempt, so a repeat is only possible within a short window; the window is large enough that a client retry or a duplicated +//! delivery is always caught. + +use std::collections::{HashSet, VecDeque}; + +/// The default number of remembered identities: about two megabytes of memory, days of agent traffic. +pub const DEFAULT_RECENT_IDS: usize = 16 * 1024; + +#[derive(Debug, Clone)] +pub struct RecentIds { + set: HashSet, + order: VecDeque, + capacity: usize, +} + +impl RecentIds { + /// `capacity` must be at least 1. + pub fn new(capacity: usize) -> Self { + let capacity = capacity.max(1); + Self { + set: HashSet::new(), + order: VecDeque::new(), + capacity, + } + } + + pub fn capacity(&self) -> usize { + self.capacity + } + + pub fn len(&self) -> usize { + self.set.len() + } + + pub fn is_empty(&self) -> bool { + self.set.is_empty() + } + + pub fn contains(&self, id: &str) -> bool { + self.set.contains(id) + } + + /// Remember `id`, forgetting the oldest identity when the ledger is full. Returns false (and changes nothing) when `id` is + /// already remembered. + pub fn insert(&mut self, id: &str) -> bool { + if self.set.contains(id) { + return false; + } + while self.set.len() >= self.capacity { + match self.order.pop_front() { + Some(oldest) => { + self.set.remove(&oldest); + } + None => break, + } + } + self.set.insert(id.to_owned()); + self.order.push_back(id.to_owned()); + true + } + + /// Forget `id` (an identity proven to have produced no effects). Returns whether it was remembered. + pub fn remove(&mut self, id: &str) -> bool { + if !self.set.remove(id) { + return false; + } + // A just-rejected identity is the newest entry, so the search from the back is short. + if let Some(at) = self.order.iter().rposition(|x| x == id) { + self.order.remove(at); + } + true + } +} + +impl Default for RecentIds { + fn default() -> Self { + Self::new(DEFAULT_RECENT_IDS) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_repeated_identity_is_refused_and_does_not_age_the_ledger() { + let mut ids = RecentIds::new(3); + assert!(ids.insert("a")); + assert!(!ids.insert("a")); + assert!(ids.insert("b")); + assert_eq!(ids.len(), 2); + assert!(ids.contains("a") && ids.contains("b")); + } + + #[test] + fn the_oldest_identity_is_forgotten_first_and_the_size_stays_bounded() { + let mut ids = RecentIds::new(3); + for id in ["a", "b", "c", "d", "e"] { + ids.insert(id); + assert!(ids.len() <= 3); + } + assert!(!ids.contains("a") && !ids.contains("b")); + assert!(ids.contains("c") && ids.contains("d") && ids.contains("e")); + // A forgotten identity is new again; a remembered one is still fenced. + assert!(!ids.insert("e")); + assert!(ids.insert("a")); + assert!(!ids.contains("c")); + } + + #[test] + fn a_removed_identity_can_be_retried_and_does_not_evict_a_live_one_early() { + let mut ids = RecentIds::new(2); + ids.insert("a"); + ids.insert("b"); + assert!(ids.remove("b")); + assert!(!ids.remove("b")); + assert!(ids.insert("b")); + // ledger is [a, b]; the next insert must evict a, not the re-inserted b + ids.insert("c"); + assert!(!ids.contains("a")); + assert!(ids.contains("b") && ids.contains("c")); + assert_eq!(ids.len(), 2); + } + + #[test] + fn a_ledger_serves_far_more_generations_than_the_old_fixed_limit() { + let mut ids = RecentIds::default(); + for n in 0..(3 * 256 + 5000) { + assert!(ids.insert(&format!("req-{n}"))); + } + assert_eq!(ids.len(), 3 * 256 + 5000); + assert!(ids.contains("req-0")); + } +} diff --git a/crates/deploy/src/config.rs b/crates/deploy/src/config.rs index 698da8a3..63e6eb36 100644 --- a/crates/deploy/src/config.rs +++ b/crates/deploy/src/config.rs @@ -243,7 +243,7 @@ impl RunConfig { }, "mode": {"type": "mtp", "profile_id": MTP_PROFILE}, "max_context": self.profile.context_tokens, - "max_output_tokens": 4096, + "max_output_tokens": 32768, } }) } diff --git a/crates/leleka-runtime/src/backend.rs b/crates/leleka-runtime/src/backend.rs index 8279691b..7c73376b 100644 --- a/crates/leleka-runtime/src/backend.rs +++ b/crates/leleka-runtime/src/backend.rs @@ -31,7 +31,7 @@ use leleka_backend_api::{ BACKEND_API_VERSION, Backend, BackendCapabilities, BackendError, BackendIdentity, ContractError, ErrorCode, FinishReason, GenerationEvent, GenerationRequest, GenerationSink, GenerationStream, GenerationTerminal, InferenceMode, LOAD_CONFIG_VERSION, LoadedModel, - ModelDescriptor, RuntimeConfig, SupportedModelTuple, Usage, + ModelDescriptor, RecentIds, RuntimeConfig, SupportedModelTuple, Usage, }; use leleka_cuda_driver::Driver; use leleka_model_format::{gguf::VerifiedGgufFile, qwen4exp::Qwen4ExpArtifact}; @@ -41,7 +41,6 @@ pub use measurement::{ }; use sha2::{Digest, Sha256}; use std::{ - collections::HashSet, path::PathBuf, rc::Rc, sync::{ @@ -68,7 +67,7 @@ const INTEGER_WINDOWED_EXECUTION: &str = "experimental-native-integer-iq3-native-down-windowed256-retained-gr-native-t1"; const PROMPT_LIMIT: usize = 1024 * 1024; const FRAME_LIMIT: usize = 64 * 1024; -const OUTPUT_LIMIT: u32 = 4096; +const OUTPUT_LIMIT: u32 = leleka_backend_api::MAX_OUTPUT_TOKENS; const QUEUE: usize = 16; const REPLY_TIMEOUT: Duration = Duration::from_secs(1200); // Explicit KAR/MTP files require private copies and complete pinned admission @@ -620,7 +619,7 @@ fn spawn_backend_configured( Ok(Box::new(Proxy { tx, shared, - seen: HashSet::new(), + seen: RecentIds::default(), kar_configured, mtp_configured, kar_experts_configured, @@ -648,7 +647,7 @@ struct Shared { struct Proxy { tx: SyncSender, shared: Arc, - seen: HashSet, + seen: RecentIds, kar_configured: bool, mtp_configured: bool, kar_experts_configured: bool, @@ -797,9 +796,6 @@ impl Backend for Proxy { if self.seen.contains(&request.request_id) { return Err(invalid("generation request was already accepted")); } - if self.seen.len() == 256 { - return Err(exhausted("generation identity registry is full")); - } let cancel = Arc::new(AtomicBool::new(false)); *self .shared @@ -817,7 +813,7 @@ impl Backend for Proxy { } let result = self.wait(rx); if result.is_ok() { - self.seen.insert(id); + self.seen.insert(&id); } else { clear_active(&self.shared); } @@ -3294,7 +3290,7 @@ mod tests { fn request_caps_are_checked_before_acceptance() { let mut r = request(); assert!(validate_request(&r).is_ok()); - r.max_output_tokens = 4097; + r.max_output_tokens = OUTPUT_LIMIT + 1; assert!(validate_request(&r).is_err()); r.max_output_tokens = 1; r.temperature_milli = 2001; @@ -3425,7 +3421,7 @@ mod tests { let mut proxy = Proxy { tx, shared, - seen: HashSet::new(), + seen: RecentIds::default(), kar_configured: false, mtp_configured: false, kar_experts_configured: false, @@ -3484,6 +3480,9 @@ mod original_serve_smoke; #[path = "backend_original_serve_prefix_smoke.rs"] mod original_serve_prefix_smoke; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] +#[path = "backend_original_serve_replay.rs"] +mod original_serve_replay; +#[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] #[path = "backend_original_serve_laptop.rs"] mod original_serve_laptop; #[cfg(all(test, target_os = "linux", target_arch = "x86_64"))] diff --git a/crates/leleka-runtime/src/backend_original_serve.rs b/crates/leleka-runtime/src/backend_original_serve.rs index 34f32306..d49b4b25 100644 --- a/crates/leleka-runtime/src/backend_original_serve.rs +++ b/crates/leleka-runtime/src/backend_original_serve.rs @@ -345,6 +345,68 @@ mod runner { } } + /// `LELEKA_CAPTURE_DIR`: keep the prompt ids and the generated ids of every completed request for offline replay + /// (`original_serve_replay_smoke`). PRIVATE data (the prompt is the user's conversation): never in Git. One + /// `req-NNNNNN.json` per request plus `prompts.ids` / `generated.ids`, one comma-separated line per request. + fn capture_request(dir: &std::path::Path, prompt: &[u32], generated: &[i32], request: &GenerationRequest, rounds: u64, reused: u64) { + use std::io::Write; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + let index = NEXT.fetch_add(1, Ordering::Relaxed); + let join = |ids: &mut dyn Iterator| ids.map(|t| t.to_string()).collect::>().join(","); + let prompt_line = join(&mut prompt.iter().map(|&t| i64::from(t))); + let generated_line = join(&mut generated.iter().map(|&t| i64::from(t))); + let s = &request.sampling; + fn opt(v: Option) -> String { + v.map_or_else(|| "null".to_owned(), |v| v.to_string()) + } + let json = format!( + "{{\"index\":{index},\"max_new\":{},\"temperature_milli\":{},\"top_p_micro\":{},\"top_k\":{},\"min_p_micro\":{},\"repetition_penalty_micro\":{},\"frequency_penalty_micro\":{},\"presence_penalty_micro\":{},\"penalty_last_n\":{},\"seed\":{},\"prompt_tokens\":{},\"reused\":{reused},\"rounds\":{rounds},\"produced\":{},\"prompt_ids\":[{prompt_line}],\"generated_ids\":[{generated_line}]}} +", + request.max_output_tokens, request.temperature_milli, opt(s.top_p_micro), opt(s.top_k), opt(s.min_p_micro), opt(s.repetition_penalty_micro), + opt(s.frequency_penalty_micro), opt(s.presence_penalty_micro), opt(s.penalty_last_n), opt(s.seed), prompt.len(), generated.len() + ); + if std::fs::create_dir_all(dir).is_err() { + return; + } + let _ = std::fs::write(dir.join(format!("req-{index:06}.json")), json); + for (name, line) in [("prompts.ids", &prompt_line), ("generated.ids", &generated_line)] { + if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join(name)) { + let _ = writeln!(file, "{line}"); + } + } + } + + #[cfg(test)] + mod capture_tests { + use super::*; + + #[test] + fn a_captured_request_is_json_with_the_ids_and_one_line_per_request_in_the_id_files() { + let dir = std::env::temp_dir().join(format!("leleka-capture-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let request = GenerationRequest { + request_id: "r".into(), + prompt: String::new(), + max_output_tokens: 64, + temperature_milli: 0, + sampling: Default::default(), + }; + capture_request(&dir, &[1, 2, 3], &[7, 8], &request, 2, 1); + capture_request(&dir, &[1, 2, 3, 7, 8, 9], &[5], &request, 1, 4); + let names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + let first = names.iter().filter(|n| n.starts_with("req-")).min().cloned().unwrap(); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join(&first)).unwrap()).unwrap(); + assert_eq!(doc["prompt_ids"], serde_json::json!([1, 2, 3])); + assert_eq!(doc["generated_ids"], serde_json::json!([7, 8])); + assert_eq!(doc["max_new"], 64); + assert!(doc["top_k"].is_null()); + let prompts = std::fs::read_to_string(dir.join("prompts.ids")).unwrap(); + assert_eq!(prompts.lines().count(), 2); + assert!(prompts.lines().any(|l| l == "1,2,3,7,8,9")); + let _ = std::fs::remove_dir_all(&dir); + } + } + /// One request over the stack; the caller owns the stream/terminal bookkeeping. #[allow(clippy::too_many_arguments)] fn generate( @@ -373,8 +435,10 @@ mod runner { let mut count: u64 = 0; let mut captured: Option = None; let mut timed_out = false; + let mut generated_ids: Vec = Vec::new(); let result = { let mut emit = |tokens: &[i32]| -> Result<(), ForwardError> { + generated_ids.extend_from_slice(tokens); let mut deliver = |token: i32| -> Result<(), GenerationFailure> { count += 1; if token as u32 == eos { @@ -427,6 +491,9 @@ mod runner { return Err(unavailable("Original serve stack lost a physical owner").into()); } }; + if let Some(directory) = std::env::var_os("LELEKA_CAPTURE_DIR") { + capture_request(std::path::Path::new(&directory), prompt, &generated_ids, request, outcome.rounds as u64, stack.reused_tokens() as u64); + } let reason = match outcome.stop { ServeStop::Eos => FinishReason::Stop, ServeStop::Length | ServeStop::Context => FinishReason::Length, diff --git a/crates/leleka-runtime/src/backend_original_serve_replay.rs b/crates/leleka-runtime/src/backend_original_serve_replay.rs new file mode 100644 index 00000000..2bd5897d --- /dev/null +++ b/crates/leleka-runtime/src/backend_original_serve_replay.rs @@ -0,0 +1,149 @@ +//! Offline replay of captured agent traffic (`LELEKA_CAPTURE_DIR` of `leleka-inference`): every recorded prompt is served in +//! order on one stack, greedy, with the recorded output length as the budget, so decode tuning (window width, draft floor, +//! expert tier, caches) is measured on the real shape of an agent session without a client. It reports per request the +//! re-prefilled tokens, TTFT, decode tokens / ms, rounds, tokens per round and how far the greedy output agrees with the +//! recording, and for the whole run the weighted decode tok/s (total tokens / total decode time) and tokens per round. +//! +//! * `LELEKA_ORIGINAL_SERVE_REPLAY=yes` explicit opt-in, plus the model inputs of `backend_original_serve_smoke.rs`; +//! * `LELEKA_REPLAY_DIR` capture directory (`req-NNNNNN.json`, replayed in file-name order); +//! * optional `LELEKA_REPLAY_FIRST` / `LELEKA_REPLAY_COUNT` window of requests (default all); +//! * optional `LELEKA_REPLAY_SPEC_MIN_P` (0 = the shipped default), `LELEKA_REPLAY_CAPACITY` (2048), +//! `LELEKA_REPLAY_MAX_CONTEXT` (262144), `LELEKA_REPLAY_PREFIX_MIB` (`auto` | MiB: the prefix cache instead of the +//! conversation cache), `LELEKA_ORIGINAL_SERVE_BUDGET_GIB` (24) and the VRAM expert tier environment of the smoke. +//! +//! A recorded request with non-greedy sampling is replayed greedily (said in the output). Captures are private data +//! (the user's conversation) and stay out of Git. +//! +//! Run (inside a holder job): ` --ignored --nocapture original_serve_replay_smoke`. +use super::*; +use crate::qwen_forward::{ + original_serve_request::ServeRequest, + original_serve_stack::{OriginalServeStack, PrefixBudget, PrefixConfig, StackConfig}, +}; +use std::env; +use super::super::qwen_forward::original_serve_stack::dbg_el; + +fn required_path(name: &str) -> PathBuf { + env::var_os(name).map(PathBuf::from).unwrap_or_else(|| panic!("missing operator-owned input {name}")) +} + +#[test] +#[ignore = "one explicitly scheduled inherited KAR+MTP load and GPU; replay of captured agent traffic"] +fn original_serve_replay_smoke() { + let _ = dbg_el(); + assert!(env::var("LELEKA_ORIGINAL_SERVE_REPLAY").is_ok_and(|v| v == "yes"), "explicit replay opt-in required"); + let number = |name: &str, default: usize| -> usize { + env::var(name).ok().map(|v| v.parse().unwrap_or_else(|_| panic!("{name} must be a count"))).unwrap_or(default) + }; + let dir = required_path("LELEKA_REPLAY_DIR"); + let mut files: Vec = std::fs::read_dir(&dir) + .expect("capture directory unreadable") + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("req-") && n.ends_with(".json"))) + .collect(); + files.sort(); + let files: Vec = files.into_iter().skip(number("LELEKA_REPLAY_FIRST", 0)).take(number("LELEKA_REPLAY_COUNT", usize::MAX)).collect(); + assert!(!files.is_empty(), "no captured requests selected"); + let fd: u32 = env::var("LELEKA_STRA169_KAR_FD").expect("missing inherited sealed archive descriptor").parse().expect("invalid descriptor"); + let shard0 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD0"), SHARD0).expect("pinned shard0 verification failed"); + let shard1 = VerifiedGgufFile::open(&required_path("LELEKA_STRA169_IQ3S_SHARD1"), SHARD1).expect("pinned shard1 verification failed"); + let artifact = Qwen4ExpArtifact::bind(shard0, shard1).expect("pinned artifact binding failed"); + let eos = *artifact.tokenizer().special_ids.get("tokenizer.ggml.eos_token_id").expect("verified EOS absent"); + let inherited = InheritedKarArchive::open(fd, required_path("LELEKA_STRA169_KAR_PROVENANCE")).expect("inherited KAR admission failed"); + let mut binding = ModelBinding::from_artifact_with_inherited_kar_mtp( + artifact, + &inherited, + &required_path("LELEKA_STRA169_MTP_PACK"), + &required_path("LELEKA_STRA169_MTP_STAGING"), + ) + .expect("actual pinned KAR+MTP binding failed"); + binding.load_resident_expert_source().expect("resident expert source load failed"); + let driver = Driver::load().expect("CUDA driver load failed"); + let device = driver.device(0).expect("CUDA device 0 unavailable"); + let context = Rc::new(device.create_context(number("LELEKA_ORIGINAL_SERVE_BUDGET_GIB", 24) << 30).expect("bounded Context unavailable")); + let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64); + config.capacity = number("LELEKA_REPLAY_CAPACITY", 2048); + config.expert_tier = crate::qwen_forward::original_serve_residency::ExpertTierConfig::from_environment() + .expect("invalid LELEKA_ORIGINAL_SERVE_EXPERT_* / PCIE / ADAPT setting"); + if let Ok(mib) = env::var("LELEKA_REPLAY_PREFIX_MIB") { + config.prefix = Some(PrefixConfig { + budget: if mib == "auto" { PrefixBudget::Auto } else { PrefixBudget::Bytes(mib.parse::().expect("LELEKA_REPLAY_PREFIX_MIB: auto or MiB") << 20) }, + ..PrefixConfig::auto() + }); + } + let min_p: f32 = env::var("LELEKA_REPLAY_SPEC_MIN_P").ok().map(|v| v.parse().expect("LELEKA_REPLAY_SPEC_MIN_P")).unwrap_or(0.0); + eprintln!( + "REPLAY config: {} requests from {:?}, capacity {}, spec_min_p {min_p}, prefix cache {}, tier {:?}", + files.len(), dir, config.capacity, config.prefix.is_some(), config.expert_tier + ); + let mut stack = match OriginalServeStack::open(&binding, context.as_ref(), Rc::clone(&context), config) { + Ok(stack) => stack, + Err(failure) => panic!("the Original serve stack did not open: {}", failure.describe()), + }; + let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = (0usize, 0f64, 0usize, 0usize, 0f64); + for (n, file) in files.iter().enumerate() { + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(file).expect("capture unreadable")).expect("capture is not JSON"); + let ids = |key: &str| -> Vec { doc[key].as_array().expect("ids").iter().map(|v| v.as_i64().expect("id") as i32).collect() }; + let (prompt, recorded) = (ids("prompt_ids"), ids("generated_ids")); + let max_new = recorded.len().clamp(1, doc["max_new"].as_u64().unwrap_or(4096) as usize); + let greedy = doc["temperature_milli"].as_u64() == Some(0) + && doc["repetition_penalty_micro"].as_u64().is_none_or(|v| v == 1_000_000 || v == 0); + if !greedy { + eprintln!("REPLAY #{n}: recorded sampling is not greedy; replayed greedily"); + } + let started = std::time::Instant::now(); + let mut first: Option = None; + let mut out: Vec = Vec::new(); + let served = stack.serve( + &ServeRequest::new(prompt.clone(), max_new, None, 7, min_p, vec![eos as i32]), + &mut |round| { + if first.is_none() { + first = Some(started.elapsed()); + } + out.extend_from_slice(round); + Ok(()) + }, + &mut || false, + ); + let total = started.elapsed(); + match served { + Ok(outcome) => { + let ttft = first.unwrap_or(total); + let decode = (total - ttft).as_secs_f64() * 1e3; + let agree = out.iter().zip(&recorded).take_while(|(a, b)| a == b).count(); + let reused = stack.reused_tokens(); + let (p_ms, d_ms) = stack.last_timing(); + eprintln!( + "REPLAY #{n} file={} prompt={} reused={reused} reprefill={} ttft_ms={:.1} produced={} rounds={} tok_per_round={:.2} decode_ms={decode:.1} decode_tok_s={:.1} engine_prompt_ms={p_ms:.1} engine_decode_ms={d_ms:.1} agree={agree}/{}", + file.file_name().and_then(|f| f.to_str()).unwrap_or("?"), + prompt.len(), + prompt.len().saturating_sub(reused), + ttft.as_secs_f64() * 1e3, + out.len(), + outcome.rounds, + out.len() as f64 / outcome.rounds.max(1) as f64, + if decode > 0.0 { out.len().saturating_sub(1) as f64 * 1e3 / decode } else { 0.0 }, + recorded.len() + ); + tokens += out.len().saturating_sub(1); + decode_ms += decode; + rounds_total += outcome.rounds; + prefill_tokens += prompt.len().saturating_sub(reused); + prefill_ms += ttft.as_secs_f64() * 1e3; + if let Some(stats) = stack.expert_tier_stats() { + eprintln!("REPLAY #{n} {}", stats.describe()); + } + } + Err(e) => eprintln!("REPLAY #{n} FAILED {e:?} health={:?}", stack.health()), + } + } + eprintln!( + "REPLAY SUMMARY requests={} weighted_decode_tok_s={:.2} (tokens {tokens} / decode {:.1} s) rounds={rounds_total} reprefilled_tokens={prefill_tokens} sum_ttft_s={:.1}", + files.len(), + if decode_ms > 0.0 { tokens as f64 * 1e3 / decode_ms } else { 0.0 }, + decode_ms / 1e3, + prefill_ms / 1e3 + ); + stack.close().expect("stack cleanup failed"); + Rc::try_unwrap(context).ok().expect("context still borrowed").close().expect("context cleanup failed"); +} diff --git a/desktop-core/src/runtime_rpc.rs b/desktop-core/src/runtime_rpc.rs index 8fd5f1f5..893765f2 100644 --- a/desktop-core/src/runtime_rpc.rs +++ b/desktop-core/src/runtime_rpc.rs @@ -4,7 +4,7 @@ use leleka_backend_api as api; use prost::Message; use sha2::{Digest, Sha256}; use std::{ - collections::{HashMap, HashSet}, + collections::HashMap, pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll}, @@ -49,7 +49,7 @@ struct State { loaded: Option, capabilities: api::BackendCapabilities, operations: HashMap, - requests: HashSet, + requests: api::RecentIds, lifecycle_busy: bool, active: Option, stopping: bool, @@ -166,7 +166,7 @@ impl RuntimeServer { loaded: None, capabilities: api::BackendCapabilities::default(), operations: HashMap::new(), - requests: HashSet::new(), + requests: api::RecentIds::default(), lifecycle_busy: false, active: None, stopping: false, @@ -532,7 +532,7 @@ impl proto::runtime_server::Runtime for RuntimeServer { uuid(&command.request_id)?; if command.prompt.len() > 1024 * 1024 || command.max_output_tokens == 0 - || command.max_output_tokens > 4096 + || command.max_output_tokens > api::MAX_OUTPUT_TOKENS { return Err(refusal( tonic::Code::InvalidArgument, @@ -558,7 +558,6 @@ impl proto::runtime_server::Runtime for RuntimeServer { } if state.active.is_some() || state.lifecycle_busy - || state.requests.len() >= MAX_IDS || state.stopping || state.sequence == u64::MAX { @@ -576,7 +575,7 @@ impl proto::runtime_server::Runtime for RuntimeServer { if !state.capabilities.supports(&loaded.descriptor) { return Err(refusal(tonic::Code::FailedPrecondition, "model_not_ready")); } - state.requests.insert(command.request_id.clone()); + state.requests.insert(&command.request_id); state.active = Some(command.request_id.clone()); publish(&self.inner, &mut state); loaded @@ -1434,36 +1433,41 @@ mod tests { task.await.unwrap(); } #[tokio::test(flavor = "current_thread")] - async fn runtime_rpc_accepted_identity_never_authorizes_retry_when_capacity_is_full() { + async fn runtime_rpc_accepted_identity_stays_fenced_while_a_full_ledger_rolls_over() { let (mut client, server, stop, task, _, _, _) = fixture().await; let (epoch, handle) = load_fixture(&mut client).await; let accepted = request(&epoch, &handle, "A"); let other_active = Uuid::new_v4().to_string(); { let mut state = server.inner.state.lock().unwrap(); - state.requests.insert(accepted.request_id.clone()); - for _ in state.requests.len()..MAX_IDS { - state.requests.insert(Uuid::new_v4().to_string()); + let capacity = state.requests.capacity(); + // The accepted identity is the newest of a full ledger. + for _ in 1..capacity { + state.requests.insert(&Uuid::new_v4().to_string()); } + state.requests.insert(&accepted.request_id); + assert_eq!(state.requests.len(), capacity); } - // A full ledger and a busy slot must both retain the accepted fence. + // A busy slot or a repeated identity is refused, whatever the ledger holds. for active in [None, Some(accepted.request_id.clone()), Some(other_active)] { server.inner.state.lock().unwrap().active = active.clone(); let duplicate = client.generate(accepted.clone()).await.err().unwrap(); assert_eq!(duplicate.code(), tonic::Code::AlreadyExists); assert_eq!(duplicate.message(), "generation_not_replayed"); assert!(duplicate.metadata().get("x-leleka-accepted").is_none()); - // A new identity still receives the proven unaccepted refusal. - let fresh = client - .generate(request(&epoch, &handle, "A")) - .await - .err() - .unwrap(); - assert_eq!(fresh.code(), tonic::Code::ResourceExhausted); - assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false"); + if active.is_some() { + // A new identity meets the busy slot, not a full ledger, and is proven unaccepted. + let fresh = client + .generate(request(&epoch, &handle, "A")) + .await + .err() + .unwrap(); + assert_eq!(fresh.code(), tonic::Code::ResourceExhausted); + assert_eq!(fresh.metadata().get("x-leleka-accepted").unwrap(), "false"); + } let state = server.inner.state.lock().unwrap(); assert_eq!(state.active, active); - assert_eq!(state.requests.len(), MAX_IDS); + assert_eq!(state.requests.len(), state.requests.capacity()); assert!(state.requests.contains(&accepted.request_id)); } drop(client); @@ -1559,7 +1563,7 @@ mod tests { "epoch_mismatch" ); let mut huge = request(&epoch, &handle, "normal"); - huge.max_output_tokens = 4097; + huge.max_output_tokens = api::MAX_OUTPUT_TOKENS + 1; let rejected = client.generate(huge).await.err().unwrap(); assert_eq!( rejected.metadata().get("x-leleka-accepted").unwrap(), diff --git a/desktop-core/tests/api_over_runtime.rs b/desktop-core/tests/api_over_runtime.rs index c8145b98..4dedee02 100644 --- a/desktop-core/tests/api_over_runtime.rs +++ b/desktop-core/tests/api_over_runtime.rs @@ -542,13 +542,11 @@ async fn a_restarted_runtime_flips_readiness_and_is_reattached_after_the_operato reborn.stop().await; } -/// Known limit of the runtime today, recorded so it cannot be forgotten: `RuntimeServer` keeps every -/// request identity it has accepted (anti-replay) and refuses new work after 256 per epoch, and the -/// engine's own registry holds 256 as well. A long agent session therefore ends with -/// `generation_capacity` until the runtime restarts. When the runtime evicts old identities this -/// test must be turned around. +/// The runtime used to remember every accepted request identity for the life of an epoch and refuse new work +/// after 256, so a long agent session ended with `generation_capacity` (found by the e2e run on the 5090 design +/// review). The ledger is now a bounded window (`RecentIds`): the 257th and every later generation is served. #[tokio::test(flavor = "multi_thread")] -async fn documents_the_256_generations_per_runtime_epoch_limit() { +async fn serves_more_than_256_generations_in_one_runtime_epoch() { let runtime = Runtime::start(None).await; runtime.operator_loads_the_model().await; runtime @@ -556,13 +554,10 @@ async fn documents_the_256_generations_per_runtime_epoch_limit() { .respond_with(|_| Script::stop_with(&["x"], usage(1, 1))); let stack = Stack::start("chain-limit", runtime.address).await; stack.wait_state(WorkerState::Ready).await; - for index in 0..256 { + for index in 0..300 { let (status, text) = stack.post("/v1/responses", &body(json!({}))).await; assert_eq!(status, 200, "request {index}: {text}"); } - let (status, text) = stack.post("/v1/responses", &body(json!({}))).await; - assert_eq!(status, 502, "{text}"); - assert!(text.contains("generation_capacity"), "{text}"); stack.finish().await; runtime.stop().await; } diff --git a/docs/api-over-rust-engine.md b/docs/api-over-rust-engine.md index 83fd9ce4..4a93c645 100644 --- a/docs/api-over-rust-engine.md +++ b/docs/api-over-rust-engine.md @@ -142,9 +142,10 @@ The ten scripts are the ones whose assertions do not depend on `strata-next` own * **Output budget.** `RuntimeServer::generate` refuses `max_output_tokens > 4096`; the worker carries that cap (`runtime.max_output_tokens`), clamps default budgets to it and refuses larger explicit ones. Codex's 32768 default is therefore not reachable until the runtime's cap is raised (its value belongs to the engine owner). -* **256 generations per runtime epoch.** `RuntimeServer` (`MAX_IDS`) and the engine backend (`seen`) remember every accepted - request id and refuse new work after 256; `api_over_runtime::documents_the_256_generations_per_runtime_epoch_limit` records it. - An agent session exhausts that quickly; the runtime needs eviction or an epoch rollover before this stack can serve for hours. +* **Generation identity ledger.** Found by the e2e run: `RuntimeServer` (`MAX_IDS`) and the engine backend (`seen`) used to remember + every accepted request id for the whole epoch and refused new work after 256 (`generation_capacity`). Both now hold a bounded + window (`leleka_backend_api::RecentIds`, 16384 most recent ids, oldest forgotten first), so an agent session no longer ends the + runtime; a repeat of a recent id is still refused (`api_over_runtime::serves_more_than_256_generations_in_one_runtime_epoch`). * **Token ids.** `usage.output_tokens` is the engine's; `reasoning_tokens` is derived from re-tokenized text, approximate, and clamped to the engine total. Reasoning-budget wrap-up, images, `strata_tune` and control vectors are refused (fail closed). * **No prefix reuse and no prefill progress.** The runtime resets to position 0 per request (`original-serve.md`), and the text diff --git a/docs/e2e-run.md b/docs/e2e-run.md new file mode 100644 index 00000000..c787f895 --- /dev/null +++ b/docs/e2e-run.md @@ -0,0 +1,191 @@ +# End-to-end run of the production stack on the RTX 5090 + +Branch `claude/e2e` (cut from `claude/port-gpu-bringup`, merged with `0b0d128` = integrated head incl. `claude/deploy`), runs of +2026-10-17 on `rnr5090` (Ubuntu 26.04, kernel 7.0.0-38, RTX 5090, driver 595.99.02, 121 GB RAM). Everything below is a functional +and stability result of the **current** code, one sample per cell; it is not a performance or quality claim (charter rules: no paired +A/B, no quality gate). + +Stack under test, all four processes started inside a holder job (sealed KAR memfd inherited, `MODEL.lock` held by the holder): + +```text +python3 e2e_client.py (Codex-shaped Responses requests) -- HTTP, Bearer test key --> strata-next serve (runtime block) 127.0.0.1:8081 +strata-next -- gRPC, runtime token ----> leleka-inference --backend-mode original 127.0.0.1:18766 +leleka-cli load-mtp (through leleka-daemon 127.0.0.1:18080) loads the model; strata-next only attaches. +``` + +## 1. Binaries (built in WSL, never on the server) + +`cargo build --release --locked -p strata-desktop-core --bin leleka-inference --bin leleka-daemon --bin leleka-cli -p strata-control --bin strata-next -p leleka-deploy --bin leleka` +from tree `da187a9` (the later commits only touch the client scripts; rustc 1.99.0, WSL2 Ubuntu 24.04, `CARGO_TARGET_DIR` outside the tree). Only the first four were copied to +`rnr5090:~/work/leleka-e2e/bin-sm120/` (`scp`, mode 0755). The sm86 binaries were built, run with `--help` in WSL (RTX 3080 Laptop, cc 8.6, +`ldd`: libc, libm, libgcc_s) and not run against a model here. + +| binary | sm_120 (default) bytes | sm_120 sha256 | `--features sm86` bytes | sm86 sha256 | +| --- | ---: | --- | ---: | --- | +| leleka-inference | 68,432,360 | `2506b49ca2576a7c24220481cfb96a9d51224da8230a1b803114e83b38cae059` | 119,298,624 | `02cbbce483977e43abd22e8610b14757dda25b9c9221ffa995a2ef7233273d52` | +| leleka-daemon | 23,295,656 | `5d113eb8404fbe06f9a0f53ee9ce7fd01fe03f39d5d1e08e3bf0a0799833ba9b` | 23,295,240 | `0162f9088265b6cd3385c6fc263468a2dd0c9daa26910b5293500374ef9e8ae0` | +| leleka-cli | 10,431,080 | `f465280ed9c730cd313b481cc62efbeb6d049d90f805e69a09f3f12d814f2ba0` | 10,431,040 | `bdaa1ca5f9eec1178345e09be8c03f84fb67f38f6466e3fb40e4b2a5596e4c7c` | +| strata-next | 28,747,720 | `5eb6238e72b416f0deb945c32d9de5939b75cb6cb97b3ade3c35a97425363a4c` | 28,747,816 | `23ce07613392014dbed90bcddf166f7a41f17a065d3d0536b0b09765255178a9` | +| leleka (deploy, not copied) | 2,892,048 | `db4ce35308bdf427b062c161ebd0049e01c358a0bab6ec8252c465e775aaf6c8` | 2,892,048 | same | + +(The `strata-next` sm_120 file differs from the sm86 one although the feature does not touch it: Cargo unifies features per build, byte +identity across the two builds is not expected.) The `leleka` supervisor (native sealed memfd) is not used by these jobs: inside a holder +job a second 55 GB memfd would not fit, so `scripts/e2e/run-e2e.sh` starts the same processes with the holder's descriptor +(`--kar-archive-fd $LELEKA_STRA169_KAR_FD`), the flags of `deploy/rust-runtime/profiles/rtx5090-32g.json` (`--gpu-budget 25769803776`, +`--context-tokens 262144`, resident expert source) and the bring-up expert-tier environment of the 98x jobs. + +## 2. How to rerun + +```sh +# on the laptop: build (WSL), copy the four binaries and scripts/e2e to rnr5090:~/work/leleka-e2e/ (see section 1) +# on the server: drop a holder job, e.g. ~/work/gpu-runs/holder2/jobs/942-e2e-full.sh (template: section 8) +E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 E2E_OUT=$HOME/work/leleka-e2e/runs/NAME \ +E2E_CLIENT_ARGS="--soak-n 40 --burst 20 --xlong-tokens 24000" bash ~/work/leleka-e2e/scripts/e2e/run-e2e.sh +``` + +`run-e2e.sh` refuses to start unless it inherited a sealed memfd and `MODEL.lock` exists, nothing else holds the GPU and no stack process is +running; it generates the two service tokens and the API key into mode-0600 files (never printed), extracts the tokenizer assets, starts +`leleka-inference`, `leleka-daemon`, runs `leleka-cli load-mtp` and **fails fast** on a `leleka-load phase=` line, starts `strata-next`, waits +for `/ready`, runs `scripts/e2e/e2e_client.py` (or `E2E_RUN_CMD`, used by the Codex jobs), samples RSS/VRAM every 30 s (`env.tsv`), then stops +with SIGINT and reports left-over processes and GPU applications. Logs and `results.json` are written under `E2E_OUT` +(`inference.log`, `strata-next.log`, `daemon.log`, `client.log`, `results.json`, `env.tsv`); they stay out of Git. +`scripts/e2e/run-fake.sh` + `fake_llm_engine.py` run the identical client against a scripted engine without GPU (465 checks pass); that is how +the client's own checks were debugged. + +## 3. Runs + +| job | what | result | +| --- | --- | --- | +| 940 | first stack start | load failed: `new_original_prompt_arena: InputRead` (defect 1); job aborted by me after 10 min (the runner then had no fail-fast) | +| 941 | after fix 1, `LELEKA_BRINGUP_TRACE=1` | load 390 s, all scenarios ran in 2 min, 11 checks failed (tool-call format of the model, test expectations, defects 3-5) | +| 942 | after fixes 3-6, soak 40, burst 20, xlong 24k | load 371 s, 13 scenarios, **459 checks, 9 failed, 0 errors**; all 9 are the model's malformed tool calls (section 5); no leaked process, GPU back to 2 MiB | +| 946 | queued: `long` scenario with tools off | pending in the serial queue when this was written (section 9) | + +## 4. Results (job 942 unless noted; sm_120, `--backend-mode original`, prompt cache on (6), expert tier 2048 slots, adaptive) + +Model load through `leleka-cli load-mtp`: 371 s (942), 390 s (941). After load: `leleka-inference` RSS 53.6 GB (49.6 anon + 3.8 shmem), VRAM +13.2 GB, host MemAvailable 14.3 GB (the sealed memfd holds 52 GB of shmem outside the process RSS). + +| scenario | checks | measured | +| --- | --- | --- | +| endpoints (`/health` unauthenticated, `/ready`, `/status`, `/metrics`, `/v1/models[/id]`, `/api/health`, `/admin/lifecycle`, 401 without or with a wrong key, 404 stored id) | 12/12 | all as specified; `/status` answers in < 2 s while a generation runs | +| simple (Codex-shaped: instructions + developer + environment + user items, 4 function tools, `reasoning`, `include`, `text.verbosity`, `prompt_cache_key`) | 37/37 | 980-token prompt: TTFT 2.95 s first request (cold, graph capture), 0.36 s when repeated (973 reused); `max_output_tokens: 24` -> `response.incomplete`, `max_output_tokens`, `output_tokens == 24`; `/v1/responses/input_tokens` equals `usage.input_tokens` exactly (tokenizer agreement with the engine; no `the engine counted N input tokens, the control plane M` line in any log) | +| tools (3 tools, stream + stateless replay of the output items and `function_call_output`) | 99/102 | all three first calls valid JSON, names declared, arguments schema-valid; continuation after the tool result produced prose (59 tok/s decode); turn 2 re-prefilled 170 / 88 / 108 of 1150 / 1070 / 1100 tokens (980-992 reused); the 3 failures: forced `tool_choice`, `tool_choice: none` (section 5) | +| multiturn (`previous_response_id` and full replay) | 82/82 | turn 2/3 of 329/358 prompt tokens: 294/322 reused, 35/36 re-prefilled, TTFT 0.69/0.72 s; replay path identical numbers; GET, `input_items`, DELETE, 404 after delete, continuing from a deleted id 404 | +| long (8.5k tokens, tools declared) | 28/34 | the model answered with a malformed shell call 3 of 3 times -> `response.failed` (section 5); the cache numbers come from `xlong`, the tools-off rerun is job 946 | +| xlong (23,331-token prompt) | 25/25 | prefill 18.0 s = 1,295 tok/s, **one SSE `: keep-alive` comment** during the prefill; follow-up turn: 23,324 reused, **53 re-prefilled**, TTFT 0.88 s | +| cancel | 42/42 | disconnect mid-decode: engine idle again after **0.05 s**, `metrics.generation.cancelled` +1, next request fine; disconnect during a 6,036-token prefill: idle after **1.6 s** (cancel is polled per prefill chunk); re-sending the cancelled prompt re-prefills all 6,036 tokens (cached 0, TTFT 4.8 s) | +| parallel | 35/35 | the engine serves one generation at a time: B (stream) and C (JSON) sent while A (420 tokens, 5.3 s) ran were **queued** (`/metrics`: `active=true`, `queue_used=2`, `queue_capacity=16`), answered correctly in order, B's first text 1.26 s after A ended; a burst of 20 simultaneous requests gave 17 x 200 and 3 x 429 `runtime_overloaded` with `Retry-After` (`max_in_flight_requests` 17), all admitted ones completed (21.7 s) | +| invalid (24 bad requests) | 52/52 | 400 with `error.{message,type,code,param}` for malformed JSON, missing/empty/mistyped fields, unknown field, zero/negative/above-cap `max_output_tokens`, sampling out of range, bad tool (no name, bad name, duplicate, undeclared `tool_choice`, hosted), image, `reasoning_budget_tokens`, bad effort, `json_schema` without schema, **context overflow**; 404 for unknown model and `previous_response_id`; no half-open SSE for an invalid streaming request | +| compat (Chat Completions, Messages, tool call over Chat) | 3/3 | | +| determinism | 2/2 | greedy x3 identical; the seeded sampled pair matched in 942 and differed in 941 (`C++` vs `C`): documented envelope of the adaptive expert tier (`original-serve.md`), recorded as a note, not a failure | +| reasoning (Codex default `effort: medium`, `summary: auto`) | 26/26 | reasoning item + message, `reasoning_tokens` 14 of 19, replay of the reasoning item accepted (981 of 1027 reused) | +| soak (40 consecutive requests, alternate stream/JSON, every 4th a tool call) | 7/7 | all 40 ok (10 tool calls schema-valid), latency 1.69 / 1.87 / 2.09 s (min/p50/max), decode 60.7 tok/s mean; `leleka-inference` RSS +0 MiB, `strata-next` +0, daemon +0, **VRAM +0 MiB** after warm-up; `/metrics` delta started 40 = completed 40 | + +Whole job 942: 98 generations seen by `strata-next` (log line `generation done:`), 145,787 prompt tokens of which 30,878 reused (21 %; the +low share comes from the soak and invalid-input requests, whose ~980-token system prefix is below the cache's `--prompt-cache-root 2048` threshold +and therefore never reused across unrelated prompts), TTFT median 1.63 s (p90 1.68 s, max 18.0 s), decode median 68.4 tok/s per request +(10th-90th percentile 48.9-89.0), sum-weighted 68.5 tok/s over 1,791 tokens. Memory over the job (7 samples): inference VmRSS 53,611 -> 54,347 +MiB (+0.7 GB while the 24k prompt was served, flat in the soak), VRAM 13,192 -> 13,424 MiB, MemAvailable 14.3 -> 13.5 GB, no growth trend. + +Teardown (every job): `SIGINT` to strata-next, daemon, engine: all exited, `pgrep` empty, no GPU compute applications, `free -m` back to +avail 68.8 GB; the one forced abort (job 940) also left nothing behind. + +## 5. Findings + +### Defects fixed on this branch (each with a test) + +| # | defect | repro | fix | +| --- | --- | --- | --- | +| 1 | `leleka-inference --backend-mode original` could not load: `MoeWeightCache::new_original_prompt_arena: InputRead` (the retained routed-expert bank was never admitted on the Original path; only the serve smoke did it) | job 940 | `9b56aec`; the integrated branch carried an equivalent fix (`--expert-source resident|mapped`), my duplicate was dropped in the merge `98b7cf2`. Covered by the real load of jobs 941/942 (needs a GPU, no unit test possible) | +| 2 | at most **256 generations per runtime epoch**, then every request failed with `generation_capacity` until the engine was restarted and loaded again (`RuntimeServer` request ledger and the engine `Proxy.seen`) | `api_over_runtime::documents_the_256_generations_per_runtime_epoch_limit` (old test) | `b4d12bd`: `leleka_backend_api::RecentIds`, a FIFO window of the 16,384 most recent ids; test `serves_more_than_256_generations_in_one_runtime_epoch` (300 requests) + 4 unit tests + the rewritten RPC test | +| 3 | client errors surfaced as server errors: a context overflow or `max_output_tokens` above the runtime cap was queued and refused by the worker as **502 `generation_failed`** (SSE: `response.failed` after a 200) | `invalid[...]` rows of job 941 | `f5925f3`: 400 `context_length_exceeded` / `invalid_output_limit` before queueing; tests `a_prompt_that_cannot_fit_the_context_is_a_400...`, `the_runtimes_output_cap_...` | +| 4 | the default output budget (`context - prompt`) ignored the engine's 8-token margin, so a prompt close to the context failed at the worker | same | `f5925f3` (default leaves the margin) | +| 5 | `reasoning_budget_tokens`, `strata_tune`, `experimental_speed_projection` and sampling finer than the fixed point were 502 after queueing | `invalid[reasoning_budget_tokens]` = 502 in job 941 | `af3beab`: 400 `unsupported_request_field` / `invalid_sampling_precision` for a text-level engine; test `text_the_contract_cannot_carry_is_refused_not_dropped` | +| 6 | no operator-visible trace of why a generation failed or how a request went | `strata-next.log` had one line | `af3beab`, `da187a9`: `generation failed: ` and one `generation done: finish= prompt_tokens= reused= generated= prompt_ms= decode_ms=` line per request; `STRATA_DEBUG_FAILED_OUTPUT=1` additionally logs the generated text of a failed tool turn (operator debugging only) | + +All of `cargo test -p strata-control` (274 lib + integration, 28 in `backend_worker_http`), `-p strata-desktop-core`, `-p leleka-runtime-client`, +`-p leleka-backend-api` and the 10 runtime-stack HTTP smokes (`scripts/test-api-over-runtime.py`) pass on Linux after these changes. + +### Model-origin tool-call failures (not fixed, repro below) + +Every failed generation of job 942 (4 of 98) was a malformed tool call **produced by the model**, correctly refused by the server (the full stream +is `response.failed` with the message; nothing partial is published as a call): + +* `` with `["ls"]` instead of `` -> `tool call has an invalid parameter or is incomplete` (forced-choice test). +* `shell` with `command` a plain string (`ls /workspace/leleka`, `grep -rn "tools" ... | head -50`) where Codex's schema wants an array of strings -> + `function call arguments violate schema: "..." is not of type "array"` (3 of 3 attempts in the 8.5k-token `long` scenario; the same tool with a short + context was called correctly 5 of 5 times in `tools` and the soak). +* forced `tool_choice` to `update_plan`: the model called another tool -> `generated tool does not match forced tool choice`; there is no constrained decoding + anywhere in the stack, so forcing is only validated afterwards. + +This is the quality risk for a real Codex session (the model may emit the string form of `shell.command` once the context grows). The stack has no +repair step: a daemon-side "one regeneration on invalid output" exists only in `leleka-daemon`'s experimental tool adapter. Candidate fixes (not implemented, +need the quality gate of `AGENTS.md`): schema-driven constrained decoding for tool arguments, or a bounded retry in `backend_worker`. + +### Observations for other workstreams + +* Prefix reuse works across turns of one conversation (294/329, 322/358 tokens; 23,324 of 23,377 on the 24k prompt; engine `reused=` agrees) and across a stateless replay. It does + not help unrelated requests that share a ~1k-token system prefix (root checkpoint needs 2048 tokens), nor a re-sent prompt whose first attempt was cancelled in prefill. +* Cancel during prefill takes up to one prefill chunk (1.6 s here, chunk 2048). +* `MemAvailable` stays at 13-14 GB while serving (52 GB sealed memfd + 54 GB engine RSS on a 121 GB host): no headroom for a second large process. +* A job costs 6 min of model load before the first request; the serial holder queue (stale per-pass snapshot) delayed every job of this branch by 1-4 hours. +* The golden fixtures in `control-plane/tests/fixtures/golden` hold Python-server HTTP-surface and `GEN` line goldens produced with a fake + engine, no model-generated tool calls, so model tool-call output could not be compared with the Original server through them; tool-call integrity is checked by + parsing (JSON arguments, declared name, schema validation), by delta == done == item equality in the stream, and by the 216-case tool-policy smoke. + +## 6. Contract checks (what is verified where) + +| requirement | check | result | +| --- | --- | --- | +| tool-call JSON integrity | every call: name in the declared set, `arguments` parses as an object, schema-valid, `call_id` present; streamed argument deltas == `arguments.done` == final item | pass for all successful calls (3 + 1 forced-none excluded + 10 in soak + chat) | +| streaming event order | first `response.created`, strictly increasing consecutive `sequence_number`, `event:` name == `data.type`, every added item done, exactly one terminal event and it is last, text deltas == `output_text.done` == final message | pass for every stream of the runs (about 60 streams) | +| usage counts | `usage.total == input + output`, `input_tokens` == `/input_tokens` endpoint, `output_tokens` == engine count (24 for a 24-token limit), `cached_tokens` == engine `reused=` | pass | +| stop reasons | stop -> `completed`; length -> `incomplete` + `max_output_tokens`; cancelled -> no terminal for the closed client, `cancelled` metric | pass | +| cache reuse across turns | `usage.input_tokens_details.cached_tokens` per turn, table above | pass | +| cancel frees the engine | `/metrics` `active=false` after 0.05 s (decode) / 1.6 s (prefill) | pass | +| no leaked processes | `pgrep`, `nvidia-smi --query-compute-apps` after every job | none | +| memory stable over 40+ requests | `env.tsv`, soak samples | +0 MiB RSS, +0 MiB VRAM | + +## 7. Not done: the real Codex CLI runs (three.js tic-tac-toe, CRM) + +The coordinator asked for two long Codex CLI sessions (Three.js tic-tac-toe, then a CRM) against this stack. They were **not run**: both need files +to be downloaded (the Codex release binary, the pinned three.js build and a Playwright chromium for the browser checks; the CRM needs only the Codex binary, +it is specified as Python-stdlib + SQLite so the agent needs nothing else offline), and a download needs the user's explicit confirmation in chat, which +a relayed message does not replace. Nothing was fetched. Neither the server nor the laptop (Windows or WSL) has `codex`, `node` or a browser. + +What is ready (`scripts/e2e/codex/`, committed; the job templates are `jobs/943-e2e-codex-ttt.sh` and `jobs/945-e2e-codex-crm.sh`): + +* `config.toml.tmpl`: isolated `CODEX_HOME`, custom provider (`wire_api = "responses"`, `base_url` of strata-next, `env_key = E2E_API_KEY` filled from the job's freshly + generated test key), `approval_policy = "never"`, `sandbox_mode = "workspace-write"`, no network in the sandbox. The flags of `codex exec` (`--json --skip-git-repo-check -C`) must be checked against + `codex --help` of the downloaded version. +* fixed prompts: `prompt-threejs.txt` (sha256 `f57248412f69b4a6a76aab00c2ff33ee3ce676849768f847d412c7e9e9d8a074`; same shape as the 2026-10-03 A/B prompt, without the LeaseVibe part) and + `prompt-crm.txt` (sha256 `7def656ae6a717105cd1eb26cb7f19b9adbc6ca5c26b44935a26514b879894a8`; fixed REST API, stages, `python3 server.py`, `python3 -m unittest discover -s tests`). +* `check_ttt.mjs` (the six shared browser checks with real clicks, Playwright) and `crm_acceptance.py` (starts the server with a fresh SQLite file, drives create/list/search/update/filter/notes/pipeline/delete, runs the app's own tests). +* `run-codex.sh` (renders the config, runs the agent with a bounded timeout, runs the acceptance, writes the report) and `codex_report.py` (Codex events: tokens, command exits, errors; `strata-next.log`: per request + TTFT / decode tok/s median and sum-weighted, prompt / reused / re-prefilled tokens per request and per 10 % bucket of the session, failure causes; `env.tsv`: RSS / VRAM / MemAvailable first-max-last). Verified on the fake-engine run; untested with Codex's JSON events (the event names are read defensively). + +To run them, the operator must approve and provide (each into its own new empty directory, out of Git, checksums recorded here): + +1. the Codex CLI Linux x86_64 musl release binary from `github.com/openai/codex/releases` -> `rnr5090:~/work/codex-e2e/bin/codex` (record file name, URL, size, sha256 and the published checksum); +2. for the game: a pinned `three.module.min.js` -> `~/work/codex-e2e/vendor/`, and Node + `playwright` + chromium -> `~/work/codex-e2e/node` (`CODEX_NODE_DIR`). + +Then `cp scripts/e2e/codex/jobs/943-e2e-codex-ttt.sh ~/work/gpu-runs/holder2/jobs/` (and 945 for the CRM). If Codex cannot talk to the stack, the first things to look at are the Responses features +it sends beyond what the simple scenario already exercises (all of `reasoning`, `include`, `parallel_tool_calls`, `prompt_cache_key`, `text.verbosity`, `service_tier`, reasoning-item replay and `function_call_output` replay were accepted), custom/freeform +tools (a Lark `apply_patch` is rejected with 400, `delivery-gap-audit.md` section 4) and `local_shell`/hosted tools (rejected). + +## 8. Job template + +```sh +set -uo pipefail +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 E2E_OUT=$HOME/work/leleka-e2e/runs/942-full +export E2E_CLIENT_ARGS="--soak-n 40 --burst 20 --xlong-tokens 24000" +rm -rf $E2E_OUT; sha256sum $E2E_BIN/* +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh; echo "run-e2e rc=$?" +``` + +## 9. Open at the time of writing + +* Job 946 (`E2E_SCENARIOS=long`, tools off, plus one informational tools-on request) is queued behind other agents' jobs; its table row (8.5k-token turn-1 TTFT, suffix and shared-prefix reuse) is not in section 4. +* The Codex runs of section 7. +* Daemon-side items from `delivery-gap-audit.md` not exercised here: SIGTERM drain, engine restart/re-attach under load, `leleka up`. diff --git a/docs/rust-runtime-run.md b/docs/rust-runtime-run.md index d8d225ec..cc7e8b18 100644 --- a/docs/rust-runtime-run.md +++ b/docs/rust-runtime-run.md @@ -150,10 +150,9 @@ strata-next wait-ready --url http://127.0.0.1:8081 --model qwen-iq3 --key-file / What a client can rely on, and what it cannot (verified with a scripted engine only; no model has run through this path): -* `max_output_tokens` above `runtime.max_output_tokens` (default 4096, the runtime facade's own cap) is refused with a message; +* `max_output_tokens` above `runtime.max_output_tokens` (default 32768, the runtime facade's own cap, `leleka_backend_api::MAX_OUTPUT_TOKENS`; it was 4096 until the Codex e2e run showed single turns that write a whole file need more) is refused with a message; an omitted value is clamped to that cap instead of the usual 32768. -* The runtime accepts 256 generations per epoch; after that every request fails with `generation_capacity` until the runtime - is restarted and loaded again (`api_over_runtime::documents_the_256_generations_per_runtime_epoch_limit`). +* The runtime keeps a bounded window (16384) of recent generation identities to refuse a replayed id; it no longer ends after 256 generations. * Images, `reasoning_budget_tokens`, `strata_tune` and `experimental_speed_projection` are refused: the text contract cannot carry them. * `usage.output_tokens` is the engine's count; `reasoning_tokens` is approximate. * Credential handling: the runtime token comes from the environment variable named by `token_env`, is never printed, and the address diff --git a/scripts/e2e/analyze_session.py b/scripts/e2e/analyze_session.py new file mode 100644 index 00000000..321e7d81 --- /dev/null +++ b/scripts/e2e/analyze_session.py @@ -0,0 +1,298 @@ +#!/usr/bin/env python3 +"""Per-request trace and session analysis of a Codex (or any) run against the stack (offline helper, not shipped). + + analyze_session.py RUN_DIR [--csv trace.csv] [--top 10] + +Reads from RUN_DIR (written by run-e2e.sh / run-codex.sh): + strata-next.log `generation start:` / `generation done:` lines (t_unix_ms, prompt/reused/generated tokens, prompt_ms = time to first text, decode_ms) + inference.log engine stderr with LELEKA_SERVE_PROFILE=1 and LELEKA_BRINGUP_TRACE=1: `prefill_phase start n= resume=`, PREFILL-PROFILE, + `DBG window`, `leleka-serve request outcome=`, expert-tier counters, `prefix request:` lines + codex-events.jsonl Codex `--json` events stamped with t_unix_ms by ts_lines.py (optional) + env.tsv RSS / VRAM / MemAvailable samples (optional) +and writes one CSV row per generation plus a text report: time shares (prefill / decode / idle waiting for the agent and its tools), +context growth, prefill cost against context, reuse effectiveness, decode speed against context, the slowest requests with causes, +and what the prefill would have cost had every turn re-read only its new suffix (the ideal of a perfect prefix cache). +Requests of strata-next and prefill phases of the engine are joined by order; the prompt token counts are compared as a check. +""" +import argparse +import csv +import json +import os +import re +import statistics +import sys + +ap = argparse.ArgumentParser() +ap.add_argument("run") +ap.add_argument("--csv", default=None) +ap.add_argument("--top", type=int, default=10) +args = ap.parse_args() +RUN = args.run + + +def lines(name): + try: + with open(os.path.join(RUN, name), errors="replace") as f: + return f.read().splitlines() + except OSError: + return [] + + +def med(xs): + xs = [x for x in xs if x is not None] + return round(statistics.median(xs), 2) if xs else None + + +def pct(xs, p): + xs = sorted(x for x in xs if x is not None) + return round(xs[min(len(xs) - 1, int(p * len(xs)))], 2) if xs else None + + +# ---- strata-next ---------------------------------------------------------------------------------------------------------- +start_re = re.compile(r"generation start: t_unix_ms=(\d+) prompt_tokens=(\d+) max_new=(\d+)") +done_re = re.compile(r"generation done: (?:t_unix_ms=(\d+) )?finish=(\w+) prompt_tokens=(\d+) reused=(\d+) generated=(\d+) prompt_ms=([\d.]+) decode_ms=([\d.]+) disconnected=(\w+)") +starts, reqs, failures = [], [], [] +for l in lines("strata-next.log"): + m = start_re.search(l) + if m: + starts.append(int(m[1])) + continue + m = done_re.search(l) + if m: + reqs.append({"t_done": int(m[1]) if m[1] else None, "finish": m[2], "prompt": int(m[3]), "reused": int(m[4]), "gen": int(m[5]), + "ttft_ms": float(m[6]), "decode_ms": float(m[7]), "disc": m[8] == "true"}) + continue + if "generation failed:" in l: + failures.append((len(reqs), l.split("generation failed:", 1)[1].strip()[:160])) +n = len(reqs) +for i, r in enumerate(reqs): + r["i"] = i + r["t_start"] = starts[i] if i < len(starts) else (r["t_done"] - r["ttft_ms"] - r["decode_ms"] if r["t_done"] else None) + r["suffix"] = r["prompt"] - r["reused"] + +# ---- engine log ------------------------------------------------------------------------------------------------------------- +blocks, cur = [], None +tier_re = re.compile(r"expert tier: (\d+) layer groups, entries vram (\d+) .*? pcie (\d+) .*? cpu (\d+) .*?, (\d+) adaptations, (\d+) swaps") +for l in lines("inference.log"): + m = re.search(r"prefill_phase start n=(\d+) resume=(\d+)", l) + if m: + cur = {"n": int(m[1]), "resume": int(m[2]), "pf_tokens": 0, "pf_ms": 0.0, "pf_chunks": 0, "rounds_win": 0, "win_ms": 0.0, "produced": None, "rounds": None, + "reused": None, "tier": None, "prefix": {}, "cancelled": False} + blocks.append(cur) + continue + if cur is None: + continue + m = re.search(r"PREFILL-PROFILE first=(\d+) tokens=(\d+) total_ms=([\d.]+)", l) + if m and int(m[2]) > 16: + cur["pf_tokens"] += int(m[2]); cur["pf_ms"] += float(m[3]); cur["pf_chunks"] += 1 + continue + m = re.search(r"DBG window rows=(\d+) total=([\d.]+)", l) + if m: + cur["rounds_win"] += 1; cur["win_ms"] += float(m[2]) + continue + m = re.search(r"leleka-serve request outcome=completed produced=(\d+) rounds=(\d+) reused=(\d+)", l) + if m: + cur["produced"], cur["rounds"], cur["reused"] = int(m[1]), int(m[2]), int(m[3]) + continue + m = tier_re.search(l) + if m: + cur["tier"] = tuple(int(x) for x in m.groups()) + continue + if "serve_request err Cancelled" in l: + cur["cancelled"] = True + m = re.search(r"prefix request: (.*)", l) + if m: + cur["prefix"].update(dict(re.findall(r"(\w+)=(\S+)", m[1]))) + m = re.search(r"prefix request done: (.*)", l) + if m: + cur["prefix"].update(dict(re.findall(r"(\w+)=(\S+)", m[1]))) +prev_tier = None +for b in blocks: + t = b["tier"] + if t: + if prev_tier and t[0] >= prev_tier[0]: + groups = t[0] - prev_tier[0] + ent = [t[1] - prev_tier[1], t[2] - prev_tier[2], t[3] - prev_tier[3]] + b["vram_share"] = ent[0] / max(sum(ent), 1) + b["pcie_share"] = ent[1] / max(sum(ent), 1) + b["swaps"] = t[5] - prev_tier[5] + else: + tot = max(t[1] + t[2] + t[3], 1) + b["vram_share"], b["pcie_share"], b["swaps"] = t[1] / tot, t[2] / tot, t[5] + prev_tier = t + +# join by order; a mismatch of the prompt size marks the pair +for i, r in enumerate(reqs): + b = blocks[i] if i < len(blocks) else None + r["eng"] = b + r["join_ok"] = bool(b and abs(b["n"] - r["prompt"]) <= 1) + +# ---- codex events --------------------------------------------------------------------------------------------------------------- +events = [] +for l in lines("codex-events.jsonl"): + try: + events.append(json.loads(l)) + except ValueError: + pass +tool_spans = [] +open_items = {} +for e in events: + it = e.get("item") or {} + t = e.get("t_unix_ms") + if e.get("type") == "item.started" and it.get("type") == "command_execution": + open_items[it.get("id")] = (t, it.get("command", "")) + elif e.get("type") == "item.completed" and it.get("type") == "command_execution": + s = open_items.pop(it.get("id"), None) + if s and t: + tool_spans.append((s[0], t, s[1], it.get("exit_code"))) +turns = [e for e in events if e.get("type") == "turn.completed"] +codex_usage = {k: sum((e.get("usage") or {}).get(k, 0) for e in turns) for k in ("input_tokens", "cached_input_tokens", "output_tokens")} + +# ---- env samples --------------------------------------------------------------------------------------------------------------------- +env = [] +for l in lines("env.tsv")[1:]: + f = l.split("\t") + if len(f) >= 9 and f[1] == "inference": + env.append({"t": int(f[0]) * 1000, "rss": int(f[2]), "gpu": int(f[7]) if f[7].isdigit() else None, "avail": int(f[8]) if f[8].isdigit() else None, "shm": int(f[5])}) + + +def env_at(t): + if not env or t is None: + return {} + return min(env, key=lambda s: abs(s["t"] - t)) + + +# ---- per-request rows ---------------------------------------------------------------------------------------------------------------- +rows = [] +for i, r in enumerate(reqs): + b = r["eng"] or {} + gap = None + if i > 0 and r["t_start"] and reqs[i - 1]["t_done"]: + gap = r["t_start"] - reqs[i - 1]["t_done"] + tool_ms = 0 + if gap is not None and gap > 0: + lo, hi = reqs[i - 1]["t_done"], r["t_start"] + tool_ms = sum(max(0, min(hi, e) - max(lo, s)) for s, e, _, _ in tool_spans) + pf_rate = (b.get("pf_tokens", 0) / (b["pf_ms"] / 1000)) if b.get("pf_ms") else None + dec_rate = ((r["gen"] - 1) / (r["decode_ms"] / 1000)) if r["decode_ms"] > 50 and r["gen"] > 4 else None + e = env_at(r["t_done"]) + row = { + "idx": i, "t_start_ms": r["t_start"], "t_done_ms": r["t_done"], "finish": r["finish"], "prompt_tokens": r["prompt"], "reused_tokens": r["reused"], + "reprefilled_tokens": r["suffix"], "ttft_ms": round(r["ttft_ms"], 1), "decode_tokens": r["gen"], "decode_ms": round(r["decode_ms"], 1), + "decode_tok_s": round(dec_rate, 1) if dec_rate else "", "engine_prefill_tokens": b.get("pf_tokens", ""), "engine_prefill_ms": round(b["pf_ms"], 1) if b.get("pf_ms") else "", + "engine_prefill_tok_s": round(pf_rate, 1) if pf_rate else "", "rounds": b.get("rounds", ""), + "tokens_per_round": round(b["produced"] / b["rounds"], 2) if b.get("rounds") else "", "vram_expert_share": round(b["vram_share"], 3) if "vram_share" in b else "", + "pcie_expert_share": round(b["pcie_share"], 3) if "pcie_share" in b else "", "swaps": b.get("swaps", ""), + "prefix_hit": b.get("prefix", {}).get("hit", ""), "prefix_resume": b.get("prefix", {}).get("resume", ""), "prefix_import_ms": b.get("prefix", {}).get("import_ms", ""), + "gap_before_ms": gap if gap is not None else "", "tool_exec_in_gap_ms": tool_ms if gap is not None else "", "queue_wait_ms": 0, + "inference_rss_mib": e.get("rss", ""), "gpu_mib": e.get("gpu", ""), "mem_available_mib": e.get("avail", ""), "join_ok": r["join_ok"], + } + rows.append(row) +if args.csv: + with open(args.csv, "w", newline="") as f: + w = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else ["idx"]) + w.writeheader() + w.writerows(rows) + +# ---- report --------------------------------------------------------------------------------------------------------------------------- +print(f"== Session {os.path.basename(os.path.abspath(RUN))}: {n} generations in strata-next.log, {len(blocks)} prefill phases in inference.log, {sum(1 for r in reqs if not r['join_ok'])} join mismatches") +if failures: + print(f" {len(failures)} failed generations:") + for at, m in failures[:8]: + print(f" after request {at}: {m}") +if not reqs: + sys.exit(0) +ttft_s = sum(r["ttft_ms"] for r in reqs) / 1000 +dec_s = sum(r["decode_ms"] for r in reqs) / 1000 +gaps = [x["gap_before_ms"] for x in rows if x["gap_before_ms"] != ""] +idle_s = sum(g for g in gaps if g > 0) / 1000 +tool_s = sum(x["tool_exec_in_gap_ms"] for x in rows if x["tool_exec_in_gap_ms"] != "") / 1000 +t_first = reqs[0]["t_start"]; t_last = reqs[-1]["t_done"] +wall = (t_last - t_first) / 1000 if t_first and t_last else None +print("\n== Time shares (first request start to last request end" + (f" = {wall:.0f} s)" if wall else ")")) +den = wall or (ttft_s + dec_s + idle_s) +for name, v in (("time to first text (prefill + first token)", ttft_s), ("decode after the first token", dec_s), ("between requests (agent + tools)", idle_s), (" of which command execution seen in Codex events", tool_s)): + print(f" {name:52s} {v:9.1f} s {100 * v / den:5.1f} %") +print(" queue wait: 0 by construction (one client, one generation at a time; strata-next /metrics queue_used was 0)") + +gen_tot = sum(max(r["gen"] - 1, 0) for r in reqs if r["decode_ms"] > 0) +dec_tot = sum(r["decode_ms"] for r in reqs if r["decode_ms"] > 0) / 1000 +print("\n== HEADLINE: weighted decode tok/s over the whole session") +print(f" {gen_tot / max(dec_tot, 1e-9):.1f} tok/s = {gen_tot} tokens after the first / {dec_tot:.1f} s decode time ({n} requests; per-request median {med([x['decode_tok_s'] for x in rows if x['decode_tok_s'] != ''])})") +print(" reference lines (earlier vanilla Strata Codex tic-tac-toe runs, 256K, INT8 K+V, same host): native 115.7 tok/s (about 110 at 180k fill), KAR PLE 150.1-150.3 tok/s (about 160); 98-99 % of CLI input tokens cached") +eng = [r["eng"] for r in reqs if r["eng"] and r["eng"].get("rounds")] +if eng: + print(f" engine tokens per verify round (accepted drafts + 1), all requests: {sum(e['produced'] for e in eng) / max(sum(e['rounds'] for e in eng), 1):.2f}") +print("\n== Context growth (prompt tokens per request)") +step = max(1, n // 12) +for b0 in range(0, n, step): + ch = reqs[b0:b0 + step] + print(f" requests {b0 + 1:4d}-{b0 + len(ch):4d}: prompt avg {sum(r['prompt'] for r in ch) // len(ch):7d} max {max(r['prompt'] for r in ch):7d} reused avg {sum(r['reused'] for r in ch) // len(ch):7d} re-prefilled avg {sum(r['suffix'] for r in ch) // len(ch):6d} ttft avg {sum(r['ttft_ms'] for r in ch) / len(ch) / 1000:6.2f}s") +print(f" context reached: {max(r['prompt'] for r in reqs)} tokens (request {max(range(n), key=lambda k: reqs[k]['prompt']) + 1})") + +print("\n== Reuse effectiveness") +tp, tr = sum(r["prompt"] for r in reqs), sum(r["reused"] for r in reqs) +print(f" prompt tokens {tp}, reused {tr} ({100 * tr / max(tp, 1):.1f} %), re-prefilled {tp - tr}") +full = [r for r in reqs if r["reused"] == 0 and r["prompt"] > 4000] +print(f" requests with no reuse and a prompt above 4000 tokens: {len(full)} (re-prefilled {sum(r['prompt'] for r in full)} tokens)") +print(f" codex-side usage: {json.dumps(codex_usage)}") + +print("\n== Prefill cost against re-prefilled tokens (engine PREFILL-PROFILE chunks, > 16 tokens per chunk)") +bins = [(0, 64), (64, 512), (512, 2048), (2048, 8192), (8192, 32768), (32768, 10**9)] +for lo, hi in bins: + sel = [x for x in rows if x["engine_prefill_ms"] != "" and lo <= x["reprefilled_tokens"] < hi] + if sel: + rate = sum(x["engine_prefill_tokens"] for x in sel) / (sum(x["engine_prefill_ms"] for x in sel) / 1000) + print(f" re-prefilled {lo:6d}-{hi if hi < 10**9 else 'inf'}: {len(sel):4d} requests, engine prefill {rate:7.0f} tok/s, ttft median {med([x['ttft_ms'] for x in sel]) / 1000:.2f}s") +print("\n== Decode speed against context length (requests with > 4 generated tokens)") +for lo, hi in [(0, 4000), (4000, 16000), (16000, 48000), (48000, 96000), (96000, 10**9)]: + sel = [x["decode_tok_s"] for x in rows if x["decode_tok_s"] != "" and lo <= x["prompt_tokens"] < hi] + if sel: + print(f" context {lo:6d}-{hi if hi < 10**9 else 'inf'}: {len(sel):4d} requests, decode median {med(sel)} tok/s (p10 {pct(sel, .1)}, p90 {pct(sel, .9)})") +tpr = [x["tokens_per_round"] for x in rows if x["tokens_per_round"] != ""] +if tpr: + print(f" tokens per verify round (accepted drafts + 1): median {med(tpr)}, p10 {pct(tpr, .1)}, p90 {pct(tpr, .9)}") +vs = [x["vram_expert_share"] for x in rows if x["vram_expert_share"] != ""] +if vs: + print(f" expert entries served from VRAM per request: median {100 * med(vs):.1f} %, PCIe {100 * med([x['pcie_expert_share'] for x in rows if x['pcie_expert_share'] != '']):.1f} %") + +print(f"\n== Slowest {args.top} requests (time to first text + decode)") +for r in sorted(reqs, key=lambda r: -(r["ttft_ms"] + r["decode_ms"]))[:args.top]: + why = [] + if r["suffix"] > 2000: + why.append(f"re-prefilled {r['suffix']} tokens" + (" (no reuse: cache miss)" if r["reused"] == 0 else f" after reusing {r['reused']}")) + if r["gen"] > 400: + why.append(f"{r['gen']} generated tokens") + if r["decode_ms"] > 50 and r["gen"] > 4 and (r["gen"] - 1) / (r["decode_ms"] / 1000) < 30: + why.append("slow decode " + f"{(r['gen'] - 1) / (r['decode_ms'] / 1000):.0f} tok/s") + if r["finish"] != "Stop": + why.append("finish " + r["finish"]) + print(f" #{r['i'] + 1:4d} prompt {r['prompt']:7d} reused {r['reused']:7d} ttft {r['ttft_ms'] / 1000:7.2f}s decode {r['gen']:5d} tok in {r['decode_ms'] / 1000:6.2f}s {'; '.join(why) or 'long output / ordinary'}") + +print("\n== Ideal against actual (every turn re-reads only its new suffix)") +big = [x for x in rows if x["engine_prefill_ms"] != "" and x["engine_prefill_tokens"] > 1500] +rate = (sum(x["engine_prefill_tokens"] for x in big) / (sum(x["engine_prefill_ms"] for x in big) / 1000)) if big else None +ideal_tokens = 0 +for i, r in enumerate(reqs): + prev = reqs[i - 1] if i else None + new = r["prompt"] - (prev["prompt"] + prev["gen"]) if prev and r["prompt"] >= prev["prompt"] else r["prompt"] + ideal_tokens += max(new, 0) +actual_tokens = sum(r["suffix"] for r in reqs) +print(f" re-prefilled tokens actual {actual_tokens}, ideal (new tokens only; a chain of linear turns) about {ideal_tokens}") +if rate: + print(f" at the engine's measured {rate:.0f} tok/s for large chunks: actual prefill about {actual_tokens / rate:.0f} s, ideal about {ideal_tokens / rate:.0f} s; time to first text actually spent {ttft_s:.0f} s") + +if env: + print("\n== Memory (env.tsv, inference process)") + rss = [s["rss"] for s in env] + print(f" samples {len(env)}: RSS MiB first {rss[0]} / max {max(rss)} / last {rss[-1]}; VRAM MiB first {env[0]['gpu']} / max {max(s['gpu'] for s in env if s['gpu'])} / last {env[-1]['gpu']}; MemAvailable MiB first {env[0]['avail']} / min {min(s['avail'] for s in env if s['avail'])} / last {env[-1]['avail']}") + +print("\n== Codex events") +kinds = {} +for e in events: + k = e.get("type", "?") + (("." + (e.get("item") or {}).get("type", "")) if e.get("type", "").startswith("item.") else "") + kinds[k] = kinds.get(k, 0) + 1 +print(" " + json.dumps(kinds, sort_keys=True)) +if tool_spans: + d = [(e - s) / 1000 for s, e, _, _ in tool_spans] + print(f" command executions {len(tool_spans)}, exit != 0: {sum(1 for x in tool_spans if x[3] not in (0, None))}, duration median {med(d)} s, max {max(d):.1f} s, total {sum(d):.0f} s") diff --git a/scripts/e2e/codex/check_ttt.mjs b/scripts/e2e/codex/check_ttt.mjs new file mode 100644 index 00000000..ba892b73 --- /dev/null +++ b/scripts/e2e/codex/check_ttt.mjs @@ -0,0 +1,77 @@ +// Shared browser checks for the Three.js tic-tac-toe game (offline test driver, not shipped): 6 checks, real mouse clicks. +// node check_ttt.mjs /path/to/index.html (needs `playwright` + its chromium installed in the test directory only) +import { chromium } from 'playwright'; +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { resolve, dirname, basename, extname, join } from 'node:path'; + +const file = resolve(process.argv[2] ?? 'index.html'); +// ES module imports are blocked on file:// (CORS), so the game's directory is served over local http, as any real deployment would. +const types = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png' }; +const root = dirname(file); +const server = createServer(async (req, res) => { + try { + const path = decodeURIComponent(new URL(req.url, 'http://x').pathname); + const target = path === '/' ? file : join(root, path); + if (!target.startsWith(root)) { res.writeHead(403).end(); return; } + const body = await readFile(target); + res.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' }).end(body); + } catch { res.writeHead(404).end(); } +}); +await new Promise((ok) => server.listen(0, '127.0.0.1', ok)); +const url = `http://127.0.0.1:${server.address().port}/${basename(file)}`; +const results = []; +const check = (name, ok, detail = '') => { + results.push({ name, ok: !!ok, detail }); + console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${ok ? '' : ' :: ' + detail}`); +}; + +const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] }); +const page = await browser.newPage({ viewport: { width: 900, height: 900 } }); +const errors = []; +page.on('pageerror', (e) => errors.push(String(e))); +page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); }); +await page.goto(url); +await page.waitForTimeout(1500); + +check('1 loads without page error', errors.length === 0, errors.join(' | ').slice(0, 300)); +const box = await page.evaluate(() => { + const c = document.querySelector('canvas'); + if (!c) return null; + const r = c.getBoundingClientRect(); + return { x: r.x, y: r.y, w: r.width, h: r.height }; +}); +check('2 visible WebGL canvas', box && box.w > 100 && box.h > 100, JSON.stringify(box)); + +const status = async () => (await page.evaluate(() => document.getElementById('status')?.textContent ?? '')).trim(); +// The board layout is the game's own: the nine regions of a lattice around the canvas centre must map to nine different cells. +if (!box) { await browser.close(); server.close(); console.log('SUMMARY ' + results.filter((r) => r.ok).length + '/6'); process.exit(1); } +const cx = box.x + box.w / 2, cy = box.y + box.h / 2, step = Math.min(box.w, box.h) / 6; +const pts = []; +for (let r = -1; r <= 1; r++) for (let c = -1; c <= 1; c++) pts.push([cx + c * step, cy + r * step]); +const click = async (i) => { await page.mouse.click(pts[i][0], pts[i][1]); await page.waitForTimeout(250); }; +const restart = async () => { const b = await page.$('#restart'); if (b) await b.click(); await page.waitForTimeout(200); }; + +// 3: row win via real clicks: X takes 0,1,2; O takes 3,4 +for (const i of [0, 3, 1, 4, 2]) await click(i); +const s3 = await status(); +check('3 row win via real clicks', /X/i.test(s3) && /win/i.test(s3), s3); +// 4: moves blocked after the win +const before = await status(); +await click(5); await click(6); +const after = await status(); +check('4 moves blocked after the win', before === after && /win/i.test(after), `${before} -> ${after}`); +// 5: restart to an empty board +await restart(); +const s5 = await status(); +check('5 restart to empty board (X to move)', /X/i.test(s5) && !/win|draw/i.test(s5), s5); +// 6: draw via real clicks: X O X / X O O / O X X +for (const i of [0, 1, 2, 4, 3, 5, 7, 6, 8]) await click(i); +const s6 = await status(); +check('6 draw via real clicks', /draw/i.test(s6), s6); + +await browser.close(); +server.close(); +const passed = results.filter((r) => r.ok).length; +console.log(`SUMMARY ${passed}/6`); +process.exit(passed === 6 ? 0 : 1); diff --git a/scripts/e2e/codex/codex_report.py b/scripts/e2e/codex/codex_report.py new file mode 100644 index 00000000..18a6f244 --- /dev/null +++ b/scripts/e2e/codex/codex_report.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +"""Summarize a Codex agent run against the stack (offline helper, not shipped). + + codex_report.py RUN_DIR reads codex-events.jsonl, strata-next.log (one `generation done:` line per request), + inference.log and env.tsv written by run-e2e.sh / run-codex.sh. +""" +import json +import os +import re +import statistics +import sys + +run = sys.argv[1] + + +def lines(name): + try: + with open(os.path.join(run, name), errors="replace") as f: + return f.read().splitlines() + except OSError: + return [] + + +def med(xs): + return round(statistics.median(xs), 2) if xs else None + + +def pct(xs, p): + if not xs: + return None + xs = sorted(xs) + return round(xs[min(len(xs) - 1, int(p * len(xs)))], 2) + + +# ---- Codex events ------------------------------------------------------------------------------------------------------- +kinds, usage, tool_items, exits, errors = {}, {"input": 0, "cached": 0, "output": 0, "turns": 0}, 0, [], [] +for line in lines("codex-events.jsonl"): + try: + e = json.loads(line) + except ValueError: + continue + t = e.get("type", "?") + kinds[t] = kinds.get(t, 0) + 1 + if t == "turn.completed": + u = e.get("usage") or {} + usage["input"] += u.get("input_tokens", 0) + usage["cached"] += u.get("cached_input_tokens", 0) + usage["output"] += u.get("output_tokens", 0) + usage["turns"] += 1 + if t in ("error", "turn.failed"): + errors.append(json.dumps(e)[:300]) + item = e.get("item") or {} + if t == "item.completed": + it = item.get("type", "?") + kinds["item." + it] = kinds.get("item." + it, 0) + 1 + if it == "command_execution": + exits.append(item.get("exit_code")) +print("== Codex events") +print(" event kinds:", json.dumps(kinds, sort_keys=True)) +print(" Codex usage:", json.dumps(usage)) +print(" command executions:", len(exits), "non-zero exit:", sum(1 for x in exits if x not in (0, None))) +print(" error events:", len(errors)) +for e in errors[:5]: + print(" ", e) + +# ---- per-request records from strata-next --------------------------------------------------------------------------------- +pat = re.compile(r"generation done: finish=(\w+) prompt_tokens=(\d+) reused=(\d+) generated=(\d+) prompt_ms=([\d.]+) decode_ms=([\d.]+) disconnected=(\w+)") +reqs = [] +for line in lines("strata-next.log"): + m = pat.search(line) + if m: + reqs.append({"finish": m[1], "prompt": int(m[2]), "reused": int(m[3]), "gen": int(m[4]), "ttft_s": float(m[5]) / 1000, "decode_s": float(m[6]) / 1000, "disc": m[7] == "true"}) +failed = [l for l in lines("strata-next.log") if "generation failed:" in l] +print("== Requests seen by strata-next:", len(reqs), " failures logged:", len(failed)) +causes = {} +for l in failed: + k = l.split("generation failed:", 1)[1].strip()[:90] + causes[k] = causes.get(k, 0) + 1 +for k, v in sorted(causes.items(), key=lambda x: -x[1])[:10]: + print(f" {v}x {k}") +if reqs: + ttfts = [r["ttft_s"] for r in reqs] + rates = [(r["gen"] - 1) / r["decode_s"] for r in reqs if r["gen"] > 8 and r["decode_s"] > 0.05] + pre = [r["prompt"] - r["reused"] for r in reqs] + total_p, total_r = sum(r["prompt"] for r in reqs), sum(r["reused"] for r in reqs) + print(f" TTFT s (engine first text, as seen by strata-next): median {med(ttfts)} p90 {pct(ttfts, .9)} max {max(ttfts):.2f}") + print(f" decode tok/s per request (>8 tokens): median {med(rates)} p10 {pct(rates, .1)} p90 {pct(rates, .9)}") + gen = sum(r["gen"] for r in reqs) + dec = sum(r["decode_s"] for r in reqs) + print(f" decode tokens / sum of decode time: {round(gen / dec, 2) if dec else None} tok/s ({gen} tokens)") + pt = sum(r["ttft_s"] for r in reqs) + print(f" prompt tokens / sum of time-to-first-text: {round(total_p / pt, 1) if pt else None} tok/s (includes decode of the first tokens)") + print(f" prompt tokens total {total_p}, reused {total_r} ({100 * total_r / max(total_p, 1):.1f} %), re-prefilled {total_p - total_r}") + print(f" re-prefilled tokens per request: median {med(pre)} p90 {pct(pre, .9)} max {max(pre)}") + print(f" prompt tokens per request: median {med([r['prompt'] for r in reqs])} max {max(r['prompt'] for r in reqs)}") + # growth of the conversation: re-prefill vs request index in 10 buckets + n = len(reqs) + for b in range(0, n, max(1, n // 10)): + chunk = reqs[b:b + max(1, n // 10)] + print(f" requests {b + 1}-{b + len(chunk)}: prompt avg {sum(r['prompt'] for r in chunk) // len(chunk)}, reused avg {sum(r['reused'] for r in chunk) // len(chunk)}, ttft avg {sum(r['ttft_s'] for r in chunk) / len(chunk):.2f}s") + print(" finish reasons:", {k: sum(1 for r in reqs if r["finish"] == k) for k in {r["finish"] for r in reqs}}) + +# ---- memory ------------------------------------------------------------------------------------------------------------- +rows = [l.split("\t") for l in lines("env.tsv")[1:] if l.count("\t") >= 8] +print("== Memory over the run (env.tsv)") +for name in sorted({r[1] for r in rows}): + rs = [r for r in rows if r[1] == name] + rss = [int(r[2]) for r in rs] + print(f" {name}: samples {len(rs)}, VmRSS MiB first {rss[0]} / max {max(rss)} / last {rss[-1]}, VmLck last {rs[-1][6]}, RssShmem last {rs[-1][5]}") +if rows: + gpu = [int(r[7]) for r in rows if r[7].isdigit()] + avail = [int(r[8]) for r in rows if r[8].isdigit()] + if gpu: + print(f" GPU used MiB: first {gpu[0]} / max {max(gpu)} / last {gpu[-1]}; MemAvailable MiB: first {avail[0]} / min {min(avail)} / last {avail[-1]}") diff --git a/scripts/e2e/codex/config.toml.tmpl b/scripts/e2e/codex/config.toml.tmpl new file mode 100644 index 00000000..f08af913 --- /dev/null +++ b/scripts/e2e/codex/config.toml.tmpl @@ -0,0 +1,23 @@ +# Codex CLI configuration for the e2e jobs (rendered by run-codex.sh into an isolated CODEX_HOME). No credentials here: +# the key is read from the environment variable named by env_key, set by run-e2e.sh from a freshly generated test key. +model = "@MODEL@" +model_provider = "strata" +approval_policy = "never" +sandbox_mode = "workspace-write" +model_reasoning_effort = "@EFFORT@" +model_context_window = 262144 +model_reasoning_summary = "auto" +# Codex sends the hosted web_search tool by default; strata-next refuses hosted tools (400), as the existing launcher scripts/install-qwen-native.py also configures +web_search = "disabled" + +[sandbox_workspace_write] +network_access = false + +[model_providers.strata] +name = "strata-next over leleka-inference" +base_url = "@BASE_URL@/v1" +env_key = "E2E_API_KEY" +wire_api = "responses" +request_max_retries = 2 +stream_max_retries = 2 +stream_idle_timeout_ms = 900000 diff --git a/scripts/e2e/codex/crm_acceptance.py b/scripts/e2e/codex/crm_acceptance.py new file mode 100644 index 00000000..ea46f77a --- /dev/null +++ b/scripts/e2e/codex/crm_acceptance.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Acceptance script for the CRM the agent builds (offline test driver, not shipped). + + crm_acceptance.py WORKSPACE + +Starts `python3 server.py` in WORKSPACE on a free port with a fresh database, drives the REST API of prompt-crm.txt and runs +the app's own tests. Exit status 0 when every check passed. +""" +import json +import os +import socket +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +ws = os.path.abspath(sys.argv[1]) +results = [] + + +def check(name, ok, detail=""): + results.append(bool(ok)) + print(("PASS " if ok else "FAIL ") + name + ("" if ok else f" :: {str(detail)[:300]}"), flush=True) + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +port = free_port() +db = os.path.join(tempfile.mkdtemp(prefix="crm-acc-"), "crm.db") +env = dict(os.environ, PORT=str(port), CRM_DB=db) +server = subprocess.Popen([sys.executable, "server.py"], cwd=ws, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +base = f"http://127.0.0.1:{port}" + + +def call(method, path, body=None): + data = None if body is None else json.dumps(body).encode() + req = urllib.request.Request(base + path, data=data, method=method, headers={"content-type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=10) as r: + raw = r.read() + try: + return r.status, (json.loads(raw) if raw else None) + except ValueError: + return r.status, raw + except urllib.error.HTTPError as e: + raw = e.read() + try: + return e.code, json.loads(raw) if raw else None + except ValueError: + return e.code, raw + + +try: + for _ in range(100): + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + time.sleep(0.1) + st, _ = call("GET", "/") + check("GET / serves the front-end", st == 200, st) + st, co = call("POST", "/api/companies", {"name": "Acme Corp", "website": "https://acme.test", "industry": "tools"}) + check("create company 201 with id", st == 201 and isinstance(co, dict) and isinstance(co.get("id"), int), (st, co)) + cid = co["id"] if isinstance(co, dict) and "id" in co else 0 + st, ct = call("POST", "/api/contacts", {"name": "Wile E. Coyote", "email": "wile@acme.test", "company_id": cid}) + check("create contact 201", st == 201 and isinstance(ct, dict) and ct.get("company_id") == cid, (st, ct)) + ctid = ct.get("id") if isinstance(ct, dict) else None + st, d = call("POST", "/api/deals", {"title": "Anvil order", "amount": 1500.5, "company_id": cid, "contact_id": ctid}) + check("create deal 201 default stage lead", st == 201 and isinstance(d, dict) and d.get("stage") == "lead", (st, d)) + did = d.get("id") if isinstance(d, dict) else 0 + st, lst = call("GET", "/api/companies?q=acme") + check("search companies (case-insensitive)", st == 200 and isinstance(lst, list) and any(c.get("id") == cid for c in lst), (st, lst)) + st, lst = call("GET", "/api/contacts?q=WILE@") + check("search contacts by email", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst)) + st, d2 = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "proposal", "company_id": cid, "contact_id": ctid}) + check("update deal stage", st == 200 and isinstance(d2, dict) and d2.get("stage") == "proposal" and d2.get("amount") == 2000, (st, d2)) + st, _ = call("PUT", f"/api/deals/{did}", {"title": "Anvil order", "amount": 2000, "stage": "bogus"}) + check("invalid stage is 400", st == 400, st) + st, lst = call("GET", "/api/deals?stage=proposal&q=anvil") + check("deals filter by stage and q", st == 200 and isinstance(lst, list) and len(lst) == 1, (st, lst)) + st, lst = call("GET", "/api/deals?stage=won") + check("deals filter by stage (empty)", st == 200 and lst == [], (st, lst)) + st, n = call("POST", f"/api/deals/{did}/notes", {"body": "Called, wants a quote"}) + check("add note 201", st == 201 and isinstance(n, dict) and n.get("body") == "Called, wants a quote", (st, n)) + st, ns = call("GET", f"/api/deals/{did}/notes") + check("list notes", st == 200 and isinstance(ns, list) and len(ns) == 1, (st, ns)) + st, p = call("GET", "/api/pipeline") + check("pipeline summary per stage", st == 200 and isinstance(p, dict) and set(p) == {"lead", "qualified", "proposal", "won", "lost"} + and p["proposal"]["count"] == 1 and p["proposal"]["amount"] == 2000, (st, p)) + st, _ = call("POST", "/api/companies", {"website": "x"}) + check("missing name is 400", st == 400, st) + st, _ = call("GET", "/api/deals/99999") + check("unknown id is 404", st == 404, st) + st, _ = call("DELETE", f"/api/companies/{cid}") + check("delete company 204", st == 204, st) + st, d3 = call("GET", f"/api/deals/{did}") + check("deleting the company keeps the deal and clears the reference", st == 200 and isinstance(d3, dict) and d3.get("company_id") in (None, 0), (st, d3)) + st, _ = call("DELETE", f"/api/deals/{did}") + check("delete deal 204", st == 204, st) + st, _ = call("GET", f"/api/deals/{did}") + check("deleted deal is 404", st == 404, st) +finally: + server.terminate() + try: + server.wait(10) + except subprocess.TimeoutExpired: + server.kill() + +t = subprocess.run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], cwd=ws, capture_output=True, text=True, timeout=300) +check("the app's own tests pass (unittest discover -s tests)", t.returncode == 0, t.stderr[-300:]) +check("README.md exists", os.path.exists(os.path.join(ws, "README.md"))) +print(f"SUMMARY {sum(results)}/{len(results)}") +sys.exit(0 if all(results) else 1) diff --git a/scripts/e2e/codex/jobs/943-e2e-codex-ttt.sh b/scripts/e2e/codex/jobs/943-e2e-codex-ttt.sh new file mode 100644 index 00000000..05527567 --- /dev/null +++ b/scripts/e2e/codex/jobs/943-e2e-codex-ttt.sh @@ -0,0 +1,16 @@ +set -uo pipefail +# claude/e2e: the real Codex CLI (0.163.0) writes a Three.js tic-tac-toe game against the production stack +# (leleka-inference Original serve, default conversation cache, behind strata-next). Profiling on, engine log kept. +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 +export E2E_OUT=$HOME/work/leleka-e2e/runs/943-codex-ttt +export CODEX_TIMEOUT_S=5400 +export LELEKA_BRINGUP_TRACE=1 # PREFILL-PROFILE / round lines in the engine log +export E2E_SAMPLE_S=10 +export LELEKA_CAPTURE_DIR=$HOME/work/codex-e2e/capture/943-codex-ttt # PRIVATE: prompt + generated token ids of every request, for offline replay (never in Git) # RSS / VRAM / MemAvailable every 10 s +export E2E_STATUS_FILE=$HOME/work/codex-e2e/STATUS.txt +export E2E_RUN_CMD="bash $HOME/work/leleka-e2e/scripts/e2e/codex/run-codex.sh ttt" +rm -rf $E2E_OUT $LELEKA_CAPTURE_DIR +date -u +%FT%TZ; sha256sum $E2E_BIN/* $HOME/work/codex-e2e/bin/codex $HOME/work/codex-e2e/vendor/three.module.min.js +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh +echo "run-e2e rc=$?" +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/943b-e2e-codex-ttt.sh b/scripts/e2e/codex/jobs/943b-e2e-codex-ttt.sh new file mode 100644 index 00000000..5a5945b7 --- /dev/null +++ b/scripts/e2e/codex/jobs/943b-e2e-codex-ttt.sh @@ -0,0 +1,16 @@ +set -uo pipefail +# claude/e2e: the real Codex CLI (0.163.0) writes a Three.js tic-tac-toe game (rerun after the 32768 output cap) against the production stack +# (leleka-inference Original serve, default conversation cache, behind strata-next). Profiling on, engine log kept. +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 +export E2E_OUT=$HOME/work/leleka-e2e/runs/943b-codex-ttt +export CODEX_TIMEOUT_S=5400 +export LELEKA_BRINGUP_TRACE=1 # PREFILL-PROFILE / round lines in the engine log +export E2E_SAMPLE_S=10 +export LELEKA_CAPTURE_DIR=$HOME/work/codex-e2e/capture/943b-codex-ttt # PRIVATE: prompt + generated token ids of every request, for offline replay (never in Git) # RSS / VRAM / MemAvailable every 10 s +export E2E_STATUS_FILE=$HOME/work/codex-e2e/STATUS.txt +export E2E_RUN_CMD="bash $HOME/work/leleka-e2e/scripts/e2e/codex/run-codex.sh ttt" +rm -rf $E2E_OUT $LELEKA_CAPTURE_DIR +date -u +%FT%TZ; sha256sum $E2E_BIN/* $HOME/work/codex-e2e/bin/codex $HOME/work/codex-e2e/vendor/three.module.min.js +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh +echo "run-e2e rc=$?" +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/945-e2e-codex-crm.sh b/scripts/e2e/codex/jobs/945-e2e-codex-crm.sh new file mode 100644 index 00000000..0a1a69e6 --- /dev/null +++ b/scripts/e2e/codex/jobs/945-e2e-codex-crm.sh @@ -0,0 +1,19 @@ +set -uo pipefail +# claude/e2e: the real Codex CLI (0.163.0) builds a CRM (Python stdlib + SQLite) with the PREFIX CACHE on (--prefix-cache-mib auto, +# replaces the conversation cache). Long-horizon session; profiling on, engine log kept. +export E2E_BIN=$HOME/work/leleka-e2e/bin-sm120 +export E2E_OUT=$HOME/work/leleka-e2e/runs/945-codex-crm +export E2E_ENGINE_ARGS="--prefix-cache-mib auto" +export CODEX_TIMEOUT_S=10200 +export LELEKA_BRINGUP_TRACE=1 LELEKA_PREFIX_TRACE=1 +export E2E_SAMPLE_S=10 +export LELEKA_CAPTURE_DIR=$HOME/work/codex-e2e/capture/945-codex-crm # PRIVATE: prompt + generated token ids of every request, for offline replay (never in Git) +export LELEKA_CUPTI_LIB=$HOME/work/cupti-trace/libleleka_cupti_trace.so LELEKA_CUPTI_TRIGGER=$HOME/work/codex-e2e/cupti/cupti.trigger # armed, idle until scripts/e2e/cupti_trigger.sh +mkdir -p $HOME/work/codex-e2e/cupti +export E2E_STATUS_FILE=$HOME/work/codex-e2e/STATUS.txt +export E2E_RUN_CMD="bash $HOME/work/leleka-e2e/scripts/e2e/codex/run-codex.sh crm" +rm -rf $E2E_OUT $LELEKA_CAPTURE_DIR +date -u +%FT%TZ; sha256sum $E2E_BIN/* $HOME/work/codex-e2e/bin/codex +bash $HOME/work/leleka-e2e/scripts/e2e/run-e2e.sh +echo "run-e2e rc=$?" +date -u +%FT%TZ diff --git a/scripts/e2e/codex/jobs/replay-template.sh b/scripts/e2e/codex/jobs/replay-template.sh new file mode 100644 index 00000000..2c80c555 --- /dev/null +++ b/scripts/e2e/codex/jobs/replay-template.sh @@ -0,0 +1,21 @@ +set -uo pipefail +# Template of a holder job that replays captured Codex traffic (copy to ~/work/gpu-runs/holder2/jobs/NNN-name.sh and edit). +# Captures: ~/work/codex-e2e/capture//req-NNNNNN.json (+ prompts.ids / generated.ids, one comma-separated line per request), +# written by leleka-inference when LELEKA_CAPTURE_DIR is set (the Codex jobs 943 / 945 do). PRIVATE data, never in Git. +# The replay runs the real Original serve stack in one process (no HTTP): greedy, recorded output length as the budget, +# prints one `REPLAY #n ...` line per request and `REPLAY SUMMARY ... weighted_decode_tok_s=...`. +source ~/work/gpu-runs/holder2/dec-common.sh 2>/dev/null || true # LD_LIBRARY_PATH, asset paths, expert-tier environment +A=$HOME/leleka-gates/assets; G=$HOME/work/gpu-runs +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json +export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf +export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf +export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55 +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$G/baseline/profile.bin LELEKA_GRAPH_EXEC_REUSE=off +export LELEKA_ORIGINAL_SERVE_REPLAY=yes +export LELEKA_REPLAY_DIR=${LELEKA_REPLAY_DIR:-$HOME/work/codex-e2e/capture/943-codex-ttt} +# knobs: LELEKA_REPLAY_FIRST / _COUNT (window), LELEKA_REPLAY_SPEC_MIN_P, LELEKA_REPLAY_CAPACITY, LELEKA_REPLAY_PREFIX_MIB=auto +date -u +%FT%TZ; sha256sum $HOME/work/leleka-e2e/bin-sm120/leleka-runtime-tests +$HOME/work/leleka-e2e/bin-sm120/leleka-runtime-tests --ignored --test-threads=1 --nocapture original_serve_replay_smoke 2>&1 | grep -E '^REPLAY|test result|panicked|FAILED' +date -u +%FT%TZ diff --git a/scripts/e2e/codex/mock_responses.py b/scripts/e2e/codex/mock_responses.py new file mode 100644 index 00000000..687b86f3 --- /dev/null +++ b/scripts/e2e/codex/mock_responses.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""A throw-away /v1/responses server that records what a client sends and answers with a one-line message (TEST TOOLING). + + mock_responses.py PORT CAPTURE.jsonl + +Used once to see which request shape and tool types the Codex CLI sends before a long GPU job is spent on it. No model, no GPU. +""" +import json +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +port, capture = int(sys.argv[1]), sys.argv[2] + + +class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def do_POST(self): + n = int(self.headers.get("content-length", 0)) + raw = self.rfile.read(n) + try: + body = json.loads(raw) + except ValueError: + body = {"raw": raw[:200].decode("utf-8", "replace")} + with open(capture, "a") as f: + f.write(json.dumps({"path": self.path, "headers": {k: v for k, v in self.headers.items() if k.lower() not in ("authorization", "x-api-key")}, "body": body}) + "\n") + rid = "resp_mock1" + item = {"id": "msg_1", "type": "message", "role": "assistant", "status": "completed", "content": [{"type": "output_text", "text": "OK", "annotations": []}]} + resp = {"id": rid, "object": "response", "status": "completed", "model": body.get("model", "m"), "output": [item], + "usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 2, "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 12}} + events = [ + ("response.created", {"response": {**resp, "status": "in_progress", "output": []}}), + ("response.output_item.added", {"output_index": 0, "item": {**item, "status": "in_progress", "content": []}}), + ("response.output_text.delta", {"item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": "OK"}), + ("response.output_item.done", {"output_index": 0, "item": item}), + ("response.completed", {"response": resp}), + ] + out = b"" + for i, (name, data) in enumerate(events): + data = {"type": name, "sequence_number": i, **data} + out += f"event: {name}\ndata: {json.dumps(data)}\n\n".encode() + self.send_response(200) + self.send_header("content-type", "text/event-stream") + self.send_header("content-length", str(len(out))) + self.end_headers() + self.wfile.write(out) + + def do_GET(self): + self.send_response(404) + self.send_header("content-length", "0") + self.end_headers() + + +ThreadingHTTPServer(("127.0.0.1", port), H).serve_forever() diff --git a/scripts/e2e/codex/prompt-crm.txt b/scripts/e2e/codex/prompt-crm.txt new file mode 100644 index 00000000..e49de0af --- /dev/null +++ b/scripts/e2e/codex/prompt-crm.txt @@ -0,0 +1,25 @@ +Build a small CRM web application in the current directory using ONLY Python 3 standard library modules (http.server, sqlite3, json, unittest, urllib): there is no network and no package can be installed. + +Layout and commands (fixed, an acceptance script will rely on them): +- server.py: running `python3 server.py` starts an HTTP server on the port in the environment variable PORT (default 8000), bound to 127.0.0.1, with data stored in the SQLite file given by the environment variable CRM_DB (default crm.db). It creates the tables on first start. +- tests/: a unittest suite; `python3 -m unittest discover -s tests` must run offline and pass. Cover every endpoint. +- README.md: how to run, the API, and the data model. +- static/index.html (served at GET /): a single-page front-end (plain HTML + JavaScript, no libraries) with a companies list, a contacts list, a deals board with one column per stage, a search box that filters the lists, and forms to create, edit and delete records and to add notes to a deal. + +REST API (JSON bodies and responses, Content-Type application/json): +- Resources: /api/companies (name required, website, industry), /api/contacts (name required, email, phone, company_id optional), /api/deals (title required, amount number default 0, stage, company_id optional, contact_id optional), notes: GET and POST /api/deals/{id}/notes (body required). +- For each of companies, contacts, deals: GET /api/ lists all records (supports ?q=text, a case-insensitive substring filter on the name/title/email fields, and for deals also ?stage=); POST /api/ creates and returns 201 with the record including its integer id; GET /api//{id}; PUT /api//{id} replaces the editable fields and returns 200 with the record; DELETE /api//{id} returns 204. Unknown ids return 404 with {"error": "..."}; invalid input returns 400 with {"error": "..."}. +- Deal stages are exactly: lead, qualified, proposal, won, lost (default lead). PUT with another stage value returns 400. Deleting a company or contact must not delete deals; it clears the reference. +- GET /api/deals?stage=won&q=... combines both filters. GET /api/pipeline returns {"lead": {"count": n, "amount": total}, ...} for every stage. + +Work step by step, run the tests and fix failures. When all tests pass and the server starts and answers the API, reply with a short summary. + +Phase 2 (start only after phase 1 passes; keep every phase-1 behaviour and endpoint unchanged, the acceptance script re-runs them). This phase is a long refactor-and-extend job, work through it item by item and re-run the whole test suite after every item. Before editing a file read all of it; before you change behaviour read the tests that cover it. +1. Split server.py into modules (for example db.py, models.py, handlers.py, router.py) while `python3 server.py` keeps working with the same environment variables. +2. Pagination: every list endpoint accepts ?limit=N&offset=M (defaults unchanged when absent) and returns the total count in an X-Total-Count header. +3. CSV export: GET /api/companies.csv, /api/contacts.csv, /api/deals.csv with a header row and proper quoting. +4. An activity log table written on every create, update and delete, and GET /api/activity?limit=N returning the newest entries first. +5. Input validation helpers shared by all handlers, with unit tests for every rule (types, lengths up to 200 characters for names, email shape, amount >= 0). +6. Front-end: add a deal detail panel showing notes and the activity of that deal, and a keyboard shortcut / to focus the search box. +7. Write CODE_REVIEW.md: read every source and test file once more, list the weaknesses you find, fix the three most important ones, and document them. +When everything passes, reply with a short summary. diff --git a/scripts/e2e/codex/prompt-threejs.txt b/scripts/e2e/codex/prompt-threejs.txt new file mode 100644 index 00000000..ca0fb81d --- /dev/null +++ b/scripts/e2e/codex/prompt-threejs.txt @@ -0,0 +1,10 @@ +Build a complete tic-tac-toe game as a single self-contained file named index.html in the current directory, using Three.js (WebGL) for all rendering. A vendored build of Three.js is already in this directory as three.module.min.js; import it with a relative path and do not load anything from the network. + +Requirements: +- A 3x3 board drawn in 3D with a visible WebGL canvas that fills the page; X and O are distinct 3D meshes; use real mouse clicks on the canvas (raycasting) to place marks. Two players alternate, X first. +- Detect a win (rows, columns, diagonals) and a draw. Show the status ("X's turn", "O wins", "Draw") in an element with id="status". +- After a win or a draw, further clicks on the board must not place marks. +- A button with id="restart" resets the board to empty and X to move. +- The page must load without any JavaScript error. + +Verify your work before finishing: serve or open the file, and write and run a small automated check (for example with Node or Python) if the tools are available. When you are done, reply with a short summary of what you built and how you verified it. diff --git a/scripts/e2e/codex/run-codex.sh b/scripts/e2e/codex/run-codex.sh new file mode 100644 index 00000000..a6416507 --- /dev/null +++ b/scripts/e2e/codex/run-codex.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Run one Codex CLI agent task against the stack that run-e2e.sh started (test tooling, runs inside a holder job via E2E_RUN_CMD). +# +# run-codex.sh ttt|crm +# +# Needs from the environment (run-e2e.sh sets them): E2E_BASE_URL, E2E_MODEL, E2E_OUT_DIR, E2E_API_KEY (a freshly generated test key). +# Needs on disk (never in Git): CODEX_BIN (default ~/work/codex-e2e/bin/codex), for ttt a vendored three.module.min.js +# (CODEX_VENDOR, default ~/work/codex-e2e/vendor) and optionally node + playwright (CODEX_NODE_DIR) for the browser checks. +set -uo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +TASK=${1:?ttt or crm} +W=$HOME/work/codex-e2e +CODEX_BIN=${CODEX_BIN:-$W/bin/codex} +OUT=${E2E_OUT_DIR:?run through run-e2e.sh} +TIMEOUT_S=${CODEX_TIMEOUT_S:-5400} +[ -x "$CODEX_BIN" ] || { echo "codex binary not installed at $CODEX_BIN (see docs/e2e-run.md, Codex runs)"; exit 7; } +[ -n "${E2E_API_KEY:-}" ] || { echo "E2E_API_KEY not set"; exit 7; } + +case "$TASK" in + ttt) PROMPT=$HERE/prompt-threejs.txt ;; + crm) PROMPT=$HERE/prompt-crm.txt ;; + *) echo "unknown task $TASK"; exit 2 ;; +esac +WS=$OUT/workspace-$TASK +export CODEX_HOME=$OUT/codex-home +rm -rf "$WS" "$CODEX_HOME"; mkdir -p "$WS" "$CODEX_HOME"; chmod 700 "$CODEX_HOME" +sed -e "s|@MODEL@|$E2E_MODEL|" -e "s|@BASE_URL@|$E2E_BASE_URL|" -e "s|@EFFORT@|${CODEX_EFFORT:-medium}|" "$HERE/config.toml.tmpl" >"$CODEX_HOME/config.toml" +if [ "$TASK" = ttt ]; then + VENDOR=${CODEX_VENDOR:-$W/vendor} + [ -f "$VENDOR/three.module.min.js" ] || { echo "vendored three.module.min.js missing in $VENDOR"; exit 7; } + cp "$VENDOR/three.module.min.js" "$WS/" +fi + +"$CODEX_BIN" --version | tee "$OUT/codex-version.txt" +sha256sum "$CODEX_BIN" "$PROMPT" | tee "$OUT/codex-inputs.sha256" +echo "task=$TASK start=$(date -u +%FT%TZ)" | tee "$OUT/codex-task.txt" +T0=$(date +%s) +# The agent runs for a long time; the stack, the sampler and this timeout bound the job. +# every JSONL event gets the wall-clock time it was read (t_unix_ms) so it can be joined with the engine-side log +timeout "$TIMEOUT_S" "$CODEX_BIN" exec --json --skip-git-repo-check -C "$WS" "$(cat "$PROMPT")" "$OUT/codex.err" | python3 -u "$HERE/ts_lines.py" >"$OUT/codex-events.jsonl" +RC=${PIPESTATUS[0]} +echo "codex exit status $RC after $(( $(date +%s) - T0 )) s" | tee -a "$OUT/codex-task.txt" +tail -n 5 "$OUT/codex.err" | cut -c1-300 + +VRC=0 +if [ "$TASK" = crm ]; then + python3 "$HERE/crm_acceptance.py" "$WS" 2>&1 | tee "$OUT/acceptance.log"; VRC=${PIPESTATUS[0]} +else + ls -l "$WS/index.html" 2>&1 | tee "$OUT/acceptance.log" + sha256sum "$WS/index.html" 2>&1 | tee -a "$OUT/acceptance.log" + if [ -n "${CODEX_NODE_DIR:-}" ] && [ -x "$CODEX_NODE_DIR/bin/node" ]; then + (cd "$CODEX_NODE_DIR" && PATH="$CODEX_NODE_DIR/bin:$PATH" node "$HERE/check_ttt.mjs" "$WS/index.html") 2>&1 | tee -a "$OUT/acceptance.log"; VRC=${PIPESTATUS[0]} + else + echo "no node/playwright (CODEX_NODE_DIR): the 6 browser checks were not run" | tee -a "$OUT/acceptance.log"; VRC=9 + fi +fi +echo "acceptance exit status $VRC" | tee -a "$OUT/codex-task.txt" +python3 "$HERE/codex_report.py" "$OUT" 2>&1 | tee "$OUT/report.txt" +[ "$RC" = 0 ] && exit "$VRC" +exit "$RC" diff --git a/scripts/e2e/codex/ts_lines.py b/scripts/e2e/codex/ts_lines.py new file mode 100644 index 00000000..1bccd05c --- /dev/null +++ b/scripts/e2e/codex/ts_lines.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Stamp each JSONL line read from stdin with the wall-clock time it arrived (t_unix_ms). Test tooling.""" +import json +import sys +import time + +for line in sys.stdin: + line = line.rstrip("\n") + t = int(time.time() * 1000) + try: + d = json.loads(line) + if isinstance(d, dict): + d["t_unix_ms"] = t + line = json.dumps(d, separators=(",", ":")) + else: + line = json.dumps({"t_unix_ms": t, "value": d}) + except ValueError: + line = json.dumps({"t_unix_ms": t, "raw": line}) + sys.stdout.write(line + "\n") + sys.stdout.flush() diff --git a/scripts/e2e/cupti_trigger.sh b/scripts/e2e/cupti_trigger.sh new file mode 100644 index 00000000..8180a157 --- /dev/null +++ b/scripts/e2e/cupti_trigger.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# cupti_trigger.sh SECONDS LABEL [TRIGGER_FILE] : ask the injected CUPTI tracer (tools/cupti-trace, claude/ledger) of the running +# leleka-inference to record SECONDS (max 120) of kernels/copies/syncs. Atomic write; logs the unix ms of the request to +# $(dirname TRIGGER)/windows.log so the window can be joined with strata-next.log. The tracer writes .lct/ and .done. +sec=${1:?seconds}; label=${2:?label} +trigger=${3:-$HOME/work/codex-e2e/cupti/cupti.trigger} +dir=$(dirname "$trigger"); mkdir -p "$dir" +out="$dir/win-$(date -u +%H%M%S)-$(echo "$label" | tr -c 'A-Za-z0-9' '_')" +[ -e "$trigger" ] && { echo "a trigger is already pending"; exit 1; } +printf '{"seconds": %s, "out": "%s", "label": "%s"}\n' "$sec" "$out" "$label" >"$trigger.tmp" && mv "$trigger.tmp" "$trigger" +echo "$(date +%s%3N) requested seconds=$sec out=$out label=$label" >>"$dir/windows.log" +echo "$out" diff --git a/scripts/e2e/e2e_client.py b/scripts/e2e/e2e_client.py new file mode 100644 index 00000000..f7998889 --- /dev/null +++ b/scripts/e2e/e2e_client.py @@ -0,0 +1,1201 @@ +#!/usr/bin/env python3 +"""End-to-end client for `strata-next` in front of `leleka-inference` (offline TEST DRIVER, not shipped). + +Sends Codex-shaped Responses requests and checks the wire behaviour. Standard library only. +The API key is read from --key-file and is never printed or written to the results. + + e2e_client.py --base http://127.0.0.1:8081 --key-file KEY --model qwen-iq3 --out results.json \ + [--scenarios endpoints,simple,tools,...|all] [--context-dir DIR] [--pids inference=1,strata=2] [--soak-n 40] + +Exit status 0 when every check passed, 1 otherwise. results.json holds every check, measurement and a /metrics snapshot. +""" +import argparse +import glob +import http.client +import json +import os +import socket +import subprocess +import sys +import threading +import time +import traceback +import urllib.parse + +# --------------------------------------------------------------------------------------------------------------------- +# transport + +class Client: + def __init__(self, base, key, timeout=900.0): + u = urllib.parse.urlparse(base) + self.host, self.port = u.hostname, u.port + self.key, self.timeout = key, timeout + + def conn(self, timeout=None): + return http.client.HTTPConnection(self.host, self.port, timeout=timeout or self.timeout) + + def headers(self, extra=None, auth=True): + h = {"content-type": "application/json", "accept": "application/json"} + if auth and self.key: + h["authorization"] = "Bearer " + self.key + if extra: + h.update(extra) + return h + + def call(self, method, path, body=None, auth=True, headers=None, timeout=None, raw=None): + c = self.conn(timeout) + t0 = time.monotonic() + try: + data = raw if raw is not None else (None if body is None else json.dumps(body)) + c.request(method, path, body=data, headers=self.headers(headers, auth)) + r = c.getresponse() + payload = r.read() + dt = time.monotonic() - t0 + try: + parsed = json.loads(payload) if payload else None + except ValueError: + parsed = None + return Reply(r.status, dict(r.getheaders()), payload, parsed, dt) + finally: + c.close() + + def stream(self, path, body, stop=None, timeout=None, headers=None): + """POST and read an SSE stream. `stop(event_list)` returning True closes the socket early (cancel).""" + c = self.conn(timeout) + t0 = time.monotonic() + res = Stream(t0) + try: + c.request("POST", path, body=json.dumps(body), headers=self.headers({"accept": "text/event-stream", **(headers or {})})) + r = c.getresponse() + res.status = r.status + res.headers = dict(r.getheaders()) + res.t_headers = time.monotonic() - t0 + if r.status != 200 or "text/event-stream" not in res.headers.get("Content-Type", res.headers.get("content-type", "")): + res.error_body = r.read() + try: + res.error = json.loads(res.error_body) + except ValueError: + pass + return res + event, data = None, [] + while True: + line = r.readline() + if not line: + break + now = time.monotonic() - t0 + if res.t_first_byte is None: + res.t_first_byte = now + line = line.decode("utf-8", "replace").rstrip("\r\n") + if line.startswith(":"): + res.comments.append((now, line)) + continue + if line == "": + if data: + raw = "\n".join(data) + res.add(now, event, raw) + if stop and stop(res): + res.aborted = True + break + event, data = None, [] + continue + if line.startswith("event:"): + event = line[6:].strip() + elif line.startswith("data:"): + data.append(line[5:].lstrip(" ")) + res.t_end = time.monotonic() - t0 + except (socket.timeout, ConnectionError, http.client.HTTPException, OSError) as e: + res.transport_error = repr(e) + res.t_end = time.monotonic() - t0 + finally: + try: + # closing the socket mid-stream is the cancel signal for the server + if c.sock is not None: + c.sock.shutdown(socket.SHUT_RDWR) + except OSError: + pass + c.close() + return res + + +class Reply: + def __init__(self, status, headers, payload, parsed, dt): + self.status, self.headers, self.payload, self.json, self.dt = status, headers, payload, parsed, dt + + def err(self): + e = (self.json or {}).get("error") if isinstance(self.json, dict) else None + return e if isinstance(e, dict) else {} + + +class Stream: + def __init__(self, t0): + self.t0 = t0 + self.status = None + self.headers = {} + self.t_headers = None + self.t_first_byte = None + self.t_end = None + self.events = [] # (t, name, parsed_or_raw) + self.comments = [] + self.aborted = False + self.transport_error = None + self.error = None + self.error_body = b"" + self.done_marker = False + self.bad_json = [] + + def add(self, t, name, raw): + if raw.strip() == "[DONE]": + self.done_marker = True + return + try: + d = json.loads(raw) + except ValueError: + self.bad_json.append(raw[:200]) + d = raw + self.events.append((t, name, d)) + + def types(self): + return [e[2].get("type") if isinstance(e[2], dict) else None for e in self.events] + + def first(self, typ): + for t, _, d in self.events: + if isinstance(d, dict) and d.get("type") == typ: + return t + return None + + def count(self, typ): + return sum(1 for _, _, d in self.events if isinstance(d, dict) and d.get("type") == typ) + + def terminal(self): + for t, _, d in reversed(self.events): + if isinstance(d, dict) and d.get("type") in ("response.completed", "response.incomplete", "response.failed"): + return d + return None + + def response(self): + t = self.terminal() + return (t or {}).get("response") or {} + + def text(self): + return "".join(d.get("delta", "") for _, _, d in self.events if isinstance(d, dict) and d.get("type") == "response.output_text.delta") + + def delta_times(self): + return [t for t, _, d in self.events if isinstance(d, dict) and d.get("type") == "response.output_text.delta"] + + +# --------------------------------------------------------------------------------------------------------------------- +# result bookkeeping + +class Scenario: + def __init__(self, name): + self.name, self.checks, self.metrics, self.notes = name, [], {}, [] + self.t0 = time.time() + self.error = None + + def check(self, name, ok, detail=""): + self.checks.append({"name": name, "ok": bool(ok), "detail": str(detail)[:600]}) + print((" PASS " if ok else " FAIL ") + name + ((" :: " + str(detail)[:300]) if (detail and not ok) else ""), flush=True) + return bool(ok) + + def metric(self, key, value): + self.metrics[key] = value + print(f" metric {key} = {value}", flush=True) + + def note(self, text): + self.notes.append(text) + print(" note: " + text, flush=True) + + def ok(self): + return self.error is None and all(c["ok"] for c in self.checks) + + def as_dict(self): + return {"name": self.name, "ok": self.ok(), "seconds": round(time.time() - self.t0, 2), "error": self.error, + "checks": self.checks, "metrics": self.metrics, "notes": self.notes} + + +# --------------------------------------------------------------------------------------------------------------------- +# Codex-shaped requests + +INSTRUCTIONS = ( + "You are a coding agent running in the Codex CLI, a terminal-based coding assistant. You are expected to be precise, safe, and helpful.\n" + "Your capabilities: receive user prompts and other context provided by the harness, such as files in the workspace; communicate with the user by " + "streaming thinking and responses, and by making and updating plans; emit function calls to run terminal commands and apply patches.\n" + "When the task needs a command, call the `shell` tool with the command as an array of strings. Keep answers concise." +) +DEVELOPER = ( + "\nFilesystem sandboxing defines which files can be read or written. `sandbox_mode` is `workspace-write`: " + "The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Network access is restricted.\n" + "Approval policy is currently never. Do not provide the `sandbox_permissions` for any reason, commands will be rejected.\n" +) +ENV_CONTEXT = ( + "\n /workspace/leleka\n never\n workspace-write\n" + " restricted\n bash\n" +) + + +def msg(role, text): + kind = "output_text" if role == "assistant" else "input_text" + return {"type": "message", "role": role, "content": [{"type": kind, "text": text}]} + + +TOOLS = [ + {"type": "function", "name": "shell", "strict": False, + "description": "Runs a shell command and returns its output.", + "parameters": {"type": "object", "properties": { + "command": {"type": "array", "items": {"type": "string"}, "description": "The command to execute"}, + "workdir": {"type": "string", "description": "The working directory to execute the command in"}, + "timeout_ms": {"type": "integer", "description": "The timeout for the command in milliseconds"}}, + "required": ["command"], "additionalProperties": False}}, + {"type": "function", "name": "read_file", "strict": False, + "description": "Reads a text file from the workspace and returns its contents.", + "parameters": {"type": "object", "properties": { + "path": {"type": "string", "description": "Path of the file relative to the workspace root"}, + "start_line": {"type": "integer"}, "end_line": {"type": "integer"}}, + "required": ["path"], "additionalProperties": False}}, + {"type": "function", "name": "update_plan", "strict": False, + "description": "Updates the task plan. Provide an optional explanation and a list of plan items, each with a step and status.", + "parameters": {"type": "object", "properties": { + "explanation": {"type": "string"}, + "plan": {"type": "array", "items": {"type": "object", "properties": { + "step": {"type": "string"}, + "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]}}, + "required": ["step", "status"], "additionalProperties": False}}}, + "required": ["plan"], "additionalProperties": False}}, + {"type": "function", "name": "apply_patch", "strict": False, + "description": "Edits files by applying a patch. The input is the patch text in the apply_patch format.", + "parameters": {"type": "object", "properties": {"input": {"type": "string", "description": "The entire contents of the apply_patch command"}}, + "required": ["input"], "additionalProperties": False}}, +] + + +def codex_body(model, user_text, tools=True, effort="none", stream=True, store=False, max_out=None, extra_input=None, **kw): + body = { + "model": model, + "instructions": INSTRUCTIONS, + "input": [msg("developer", DEVELOPER), msg("user", ENV_CONTEXT)] + (extra_input or []) + ([msg("user", user_text)] if user_text else []), + "tool_choice": "auto", + "parallel_tool_calls": False, + "reasoning": {"effort": effort} if effort == "none" else {"effort": effort, "summary": "auto"}, + "store": store, + "stream": stream, + "include": ["reasoning.encrypted_content"] if effort != "none" else [], + "prompt_cache_key": "019a0000-0000-7000-8000-00000000e2e0", + "text": {"verbosity": "low"}, + } + if tools: + body["tools"] = TOOLS + if max_out: + body["max_output_tokens"] = max_out + body.update(kw) + return body + + +# --------------------------------------------------------------------------------------------------------------------- +# validators + +def json_type_ok(t, v): + if t == "string": + return isinstance(v, str) + if t == "integer": + return isinstance(v, int) and not isinstance(v, bool) + if t == "number": + return isinstance(v, (int, float)) and not isinstance(v, bool) + if t == "boolean": + return isinstance(v, bool) + if t == "array": + return isinstance(v, list) + if t == "object": + return isinstance(v, dict) + if t == "null": + return v is None + return True + + +def validate(schema, v, path="$"): + errs = [] + t = schema.get("type") + if t and not json_type_ok(t, v): + return [f"{path}: expected {t}, got {type(v).__name__}"] + if "enum" in schema and v not in schema["enum"]: + errs.append(f"{path}: {v!r} not in enum") + if t == "object" and isinstance(v, dict): + props = schema.get("properties", {}) + for k in schema.get("required", []): + if k not in v: + errs.append(f"{path}: missing {k}") + for k, x in v.items(): + if k in props: + errs += validate(props[k], x, f"{path}.{k}") + elif schema.get("additionalProperties") is False: + errs.append(f"{path}: unexpected {k}") + if t == "array" and isinstance(v, list) and "items" in schema: + for i, x in enumerate(v): + errs += validate(schema["items"], x, f"{path}[{i}]") + return errs + + +TOOL_BY_NAME = {t["name"]: t for t in TOOLS} + + +def check_calls(sc, resp, label, tools=TOOLS): + """Every function_call item: known name, arguments parse as an object and satisfy the tool schema.""" + calls = [i for i in resp.get("output", []) if i.get("type") == "function_call"] + by = {t["name"]: t for t in tools} + for c in calls: + name = c.get("name") + sc.check(f"{label}: call name '{name}' is a declared tool", name in by, c) + try: + args = json.loads(c.get("arguments", "")) + parsed = isinstance(args, dict) + except ValueError as e: + args, parsed = None, False + sc.check(f"{label}: arguments of {name} parse as JSON", False, f"{e}: {c.get('arguments','')[:200]}") + if parsed and name in by: + errs = validate(by[name]["parameters"], args) + sc.check(f"{label}: arguments of {name} satisfy the schema", not errs, errs) + sc.check(f"{label}: call has call_id", bool(c.get("call_id")), c) + return calls + + +def check_stream(sc, s, label, expect_terminal="response.completed"): + """Wire-order invariants of a Responses SSE stream.""" + sc.check(f"{label}: HTTP 200 event-stream", s.status == 200 and not s.transport_error, f"status={s.status} err={s.transport_error} body={s.error_body[:200]!r}") + if s.status != 200: + return + failed = s.response().get("error") if s.terminal() and s.terminal().get("type") == "response.failed" else None + if failed: + sc.note(f"{label}: response.failed {json.dumps(failed)[:300]}") + sc.check(f"{label}: every frame is JSON", not s.bad_json, s.bad_json[:2]) + types = s.types() + evs = [d for _, _, d in s.events if isinstance(d, dict)] + sc.check(f"{label}: first event is response.created", bool(types) and types[0] == "response.created", types[:3]) + terms = [t for t in types if t in ("response.completed", "response.incomplete", "response.failed")] + sc.check(f"{label}: exactly one terminal event", len(terms) == 1, terms) + sc.check(f"{label}: terminal event is last", bool(types) and types[-1] in ("response.completed", "response.incomplete", "response.failed"), types[-3:]) + if expect_terminal: + sc.check(f"{label}: terminal is {expect_terminal}", terms[:1] == [expect_terminal], terms) + named = [(n, d.get("type")) for _, n, d in s.events if isinstance(d, dict) and n is not None] + sc.check(f"{label}: SSE event: name equals data.type", all(n == t for n, t in named), [x for x in named if x[0] != x[1]][:3]) + seq = [d.get("sequence_number") for d in evs] + sc.check(f"{label}: sequence_number present and strictly increasing", all(isinstance(x, int) for x in seq) and all(b > a for a, b in zip(seq, seq[1:])), seq[:6]) + # item bracketing + added = {d["output_index"]: d["item"].get("type") for d in evs if d.get("type") == "response.output_item.added"} + done = {d["output_index"]: d["item"] for d in evs if d.get("type") == "response.output_item.done"} + sc.check(f"{label}: every added item is done", set(added) == set(done), (added, list(done))) + resp = s.response() + final = resp.get("output", []) + if resp.get("status") != "failed": + sc.check(f"{label}: final output equals the done items", [i.get("type") for i in final] == [done[k].get("type") for k in sorted(done)], (len(final), len(done))) + # text integrity + deltas = "".join(d.get("delta", "") for d in evs if d.get("type") == "response.output_text.delta") + done_text = "".join(d.get("text", "") for d in evs if d.get("type") == "response.output_text.done") + final_text = "".join(p.get("text", "") for i in final if i.get("type") == "message" for p in i.get("content", []) if p.get("type") == "output_text") + sc.check(f"{label}: text deltas == output_text.done == final message", deltas == done_text == final_text, (len(deltas), len(done_text), len(final_text))) + # tool arguments integrity + for k, item in done.items(): + if item.get("type") == "function_call": + frag = "".join(d.get("delta", "") for d in evs if d.get("type") == "response.function_call_arguments.delta" and d.get("output_index") == k) + fin = [d.get("arguments") for d in evs if d.get("type") == "response.function_call_arguments.done" and d.get("output_index") == k] + sc.check(f"{label}: arguments deltas == done == item", fin == [item.get("arguments")] and (frag == "" or frag == item.get("arguments")), (frag[:80], fin, item.get("arguments", "")[:80])) + u = resp.get("usage") or {} + if resp.get("status") != "failed": + sc.check(f"{label}: usage present and consistent", + u.get("input_tokens", 0) > 0 and u.get("output_tokens", 0) > 0 and u.get("total_tokens") == u.get("input_tokens", 0) + u.get("output_tokens", 0), u) + + +def ttft(s): + """Time from request start to the first visible model output (text delta, else first function-call argument delta).""" + for typ in ("response.output_text.delta", "response.function_call_arguments.delta", "response.reasoning_text.delta"): + t = s.first(typ) + if t is not None: + return t + return s.first("response.output_item.done") + + +def rates(sc, s, prefix): + resp = s.response() + u = resp.get("usage") or {} + out = u.get("output_tokens", 0) + t_first = ttft(s) + sc.metric(prefix + "ttft_s", round(t_first, 3) if t_first is not None else None) + sc.metric(prefix + "created_s", round(s.first("response.created") or -1, 3)) + sc.metric(prefix + "total_s", round(s.t_end, 3) if s.t_end else None) + sc.metric(prefix + "input_tokens", u.get("input_tokens")) + sc.metric(prefix + "cached_tokens", (u.get("input_tokens_details") or {}).get("cached_tokens")) + sc.metric(prefix + "output_tokens", out) + if t_first is not None and s.t_end and out > 1 and s.t_end - t_first > 0.05: + sc.metric(prefix + "decode_tok_s", round((out - 1) / (s.t_end - t_first), 2)) + sc.metric(prefix + "keepalive_comments", len(s.comments)) + + +def output_message_items(resp): + return [i for i in resp.get("output", []) if i.get("type") in ("message", "function_call", "reasoning")] + + +def replay_items(resp): + """Items a stateless client sends back next turn (Codex replays the output items verbatim).""" + out = [] + for i in resp.get("output", []): + if i.get("type") in ("message", "function_call", "reasoning"): + out.append(i) + return out + + +# --------------------------------------------------------------------------------------------------------------------- +# environment sampling (RSS of the stack processes, GPU memory) + +def rss_kb(pid): + try: + with open(f"/proc/{pid}/status") as f: + for line in f: + if line.startswith("VmRSS:"): + return int(line.split()[1]) + except OSError: + return None + return None + + +def gpu_used_mib(): + try: + out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=20).stdout + return int(out.strip().splitlines()[0]) + except Exception: + return None + + +def mem_available_mib(): + try: + with open("/proc/meminfo") as f: + for line in f: + if line.startswith("MemAvailable:"): + return int(line.split()[1]) // 1024 + except OSError: + return None + + +def sample(ctx): + s = {"t": round(time.time() - ctx.t_start, 1), "gpu_used_mib": gpu_used_mib(), "mem_available_mib": mem_available_mib()} + for name, pid in ctx.pids.items(): + s["rss_mib_" + name] = (rss_kb(pid) or 0) // 1024 + return s + + +# --------------------------------------------------------------------------------------------------------------------- +# scenarios + +class Ctx: + pass + + +def metrics_snapshot(ctx): + r = ctx.c.call("GET", "/metrics") + return r.json if r.status == 200 else {"status": r.status} + + +def wait_idle(ctx, limit=60.0): + """Seconds until /metrics reports no active generation (None when it never does).""" + t0 = time.monotonic() + while time.monotonic() - t0 < limit: + m = ctx.c.call("GET", "/metrics").json or {} + if m.get("active") is False and (m.get("queue_used") in (0, None)): + return time.monotonic() - t0 + time.sleep(0.05) + return None + + +def sc_endpoints(ctx, sc): + c = ctx.c + r = c.call("GET", "/health", auth=False) + sc.check("GET /health without auth is 200 ok", r.status == 200 and (r.json or {}).get("status") == "ok", (r.status, r.payload[:100])) + r = c.call("GET", "/ready") + sc.check("GET /ready 200 with ready=true", r.status == 200 and (r.json or {}).get("ready") is True, (r.status, r.payload[:200])) + sc.metric("ready_body", r.json) + r = c.call("GET", "/status") + sc.check("GET /status ready, worker ready, max_context", r.status == 200 and (r.json or {}).get("ready") is True and (r.json or {}).get("worker") == "ready" and (r.json or {}).get("max_context", 0) > 0, r.payload[:200]) + r = c.call("GET", "/metrics") + sc.check("GET /metrics schema_version 1 and worker ready", r.status == 200 and (r.json or {}).get("schema_version") == 1 and (r.json or {}).get("worker") == "ready", r.payload[:300]) + sc.metric("metrics_initial", r.json) + r = c.call("GET", "/v1/models") + ids = [m.get("id") for m in ((r.json or {}).get("data") or [])] + sc.check("GET /v1/models lists the model", r.status == 200 and ctx.model in ids, r.payload[:200]) + r = c.call("GET", "/v1/models/" + ctx.model) + sc.check("GET /v1/models/{id}", r.status == 200 and (r.json or {}).get("id") == ctx.model, r.payload[:200]) + r = c.call("GET", "/v1/models/nope") + sc.check("unknown model id is 404 model_not_found", r.status == 404 and r.err().get("code") == "model_not_found", r.payload[:200]) + r = c.call("GET", "/api/health", auth=False) + sc.check("GET /api/health 200", r.status == 200, (r.status, r.payload[:200])) + r = c.call("GET", "/admin/lifecycle") + sc.check("GET /admin/lifecycle not draining", r.status == 200 and (r.json or {}).get("draining") is False, r.payload[:300]) + # auth + r = c.call("GET", "/status", auth=False) + sc.check("GET /status without key is 401", r.status == 401, (r.status, r.payload[:120])) + c2 = Client(ctx.base, "wrong-" + "x" * 40) + r = c2.call("POST", "/v1/responses", {"model": ctx.model, "input": "hi"}) + sc.check("POST /v1/responses with a wrong key is 401", r.status == 401, (r.status, r.payload[:120])) + r = c.call("GET", "/v1/responses/resp_does_not_exist") + sc.check("GET unknown stored response is 404 response_not_found", r.status == 404 and r.err().get("code") == "response_not_found", r.payload[:200]) + + +def sc_simple(ctx, sc): + # streaming, Codex-shaped, no tool needed + body = codex_body(ctx.model, "Reply with exactly the five words: the quick brown fox jumps", tools=True, max_out=64, temperature=0) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, "stream") + resp = s.response() + text = s.text() + sc.check("stream: non-empty text", len(text.strip()) > 0, text[:100]) + sc.check("stream: status completed, no incomplete_details", resp.get("status") == "completed" and not resp.get("incomplete_details"), resp.get("incomplete_details")) + sc.check("stream: finished on its own (output_tokens < max_output_tokens)", (resp.get("usage") or {}).get("output_tokens", 999) < 64, resp.get("usage")) + sc.check("stream: reply mentions the words", "quick" in text.lower() and "fox" in text.lower(), text[:200]) + sc.check("stream: response.id looks like resp_", str(resp.get("id", "")).startswith("resp_"), resp.get("id")) + sc.check("stream: store=false echoed", resp.get("store") is False, resp.get("store")) + rates(sc, s, "stream_") + sc.metric("stream_text", text[:200]) + # non-streaming same request + body = codex_body(ctx.model, "Reply with exactly the five words: the quick brown fox jumps", tools=True, max_out=64, stream=False, temperature=0) + r = ctx.c.call("POST", "/v1/responses", body) + sc.check("json: HTTP 200", r.status == 200, r.payload[:300]) + j = r.json or {} + jt = "".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", [])) + sc.check("json: status completed", j.get("status") == "completed", j.get("status")) + sc.check("json: greedy text equals the streamed text", jt == text, (jt[:100], text[:100])) + sc.metric("json_total_s", round(r.dt, 3)) + u = j.get("usage") or {} + sc.metric("json_usage", u) + # input_tokens endpoint agrees with usage + cnt = ctx.c.call("POST", "/v1/responses/input_tokens", {k: v for k, v in body.items() if k not in ("stream", "max_output_tokens", "temperature", "store", "prompt_cache_key", "include")}) + n = (cnt.json or {}).get("input_tokens") + sc.check("input_tokens endpoint == usage.input_tokens of the real generation", cnt.status == 200 and n == u.get("input_tokens"), (cnt.status, n, u.get("input_tokens"), cnt.payload[:200])) + # length stop + body = codex_body(ctx.model, "Write a long essay about the history of compilers. Make it at least 500 words.", tools=False, max_out=24, temperature=0) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, "length", expect_terminal="response.incomplete") + resp = s.response() + sc.check("length: status incomplete / max_output_tokens", resp.get("status") == "incomplete" and (resp.get("incomplete_details") or {}).get("reason") == "max_output_tokens", (resp.get("status"), resp.get("incomplete_details"))) + sc.check("length: output_tokens == 24 (engine count)", (resp.get("usage") or {}).get("output_tokens") == 24, resp.get("usage")) + # instructions-only / string input form + r = ctx.c.call("POST", "/v1/responses", {"model": ctx.model, "input": "Say OK.", "max_output_tokens": 16, "temperature": 0}) + sc.check("plain string input works", r.status == 200 and (r.json or {}).get("status") in ("completed", "incomplete"), r.payload[:200]) + + +TOOL_TASKS = [ + ("shell", "Use the shell tool to list the files in the current directory (run `ls -la`)."), + ("read_file", "Use the read_file tool to read the file src/main.rs, lines 1 to 40."), + ("update_plan", "Use the update_plan tool to record a three step plan: inspect the code (completed), fix the bug (in_progress), run the tests (pending)."), +] + +TOOL_RESULTS = { + "shell": "total 24\ndrwxr-xr-x 5 dev dev 4096 Oct 17 10:00 .\n-rw-r--r-- 1 dev dev 812 Oct 17 10:00 Cargo.toml\ndrwxr-xr-x 2 dev dev 4096 Oct 17 10:00 src\n-rw-r--r-- 1 dev dev 311 Oct 17 10:00 README.md\n", + "read_file": "fn main() {\n println!(\"hello\");\n}\n", + "update_plan": "Plan updated", +} + + +def sc_tools(ctx, sc): + for want, task in TOOL_TASKS: + label = f"tool[{want}]" + # (a) streamed, expect a function_call, then stateless replay with function_call_output + body = codex_body(ctx.model, task, max_out=512, temperature=0) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, label + " turn1") + resp = s.response() + calls = check_calls(sc, resp, label + " turn1") + sc.check(f"{label}: model emitted a function_call", len(calls) >= 1, [i.get("type") for i in resp.get("output", [])]) + sc.check(f"{label}: called {want}", any(c.get("name") == want for c in calls), [c.get("name") for c in calls]) + sc.check(f"{label}: stop reason completed", resp.get("status") == "completed", (resp.get("status"), resp.get("incomplete_details"))) + rates(sc, s, label + "_t1_") + sc.metric(label + "_call", [{"name": c.get("name"), "arguments": c.get("arguments")} for c in calls][:2]) + if not calls: + sc.note(f"{label}: no call; text={s.text()[:200]!r}") + continue + call = calls[0] + out = [msg("user", task)] if False else [] + history = replay_items(resp) + history.append({"type": "function_call_output", "call_id": call["call_id"], "output": TOOL_RESULTS.get(call["name"], "ok")}) + body2 = codex_body(ctx.model, task, max_out=512, temperature=0) + body2["input"] = body["input"] + history + s2 = ctx.c.stream("/v1/responses", body2) + check_stream(sc, s2, label + " turn2") + r2 = s2.response() + calls2 = check_calls(sc, r2, label + " turn2") + txt = s2.text().strip() + sc.check(f"{label}: continuation produced text or a further valid call", len(txt) > 0 or len(calls2) > 0, r2.get("output")) + sc.check(f"{label}: turn2 prefix reuse reported", True) + rates(sc, s2, label + "_t2_") + sc.metric(label + "_t2_text", txt[:160]) + # forced tool choice, non-streaming, nested array of objects + body = codex_body(ctx.model, "Plan the work: write tests, then implement.", max_out=400, stream=False, temperature=0, + tool_choice={"type": "function", "name": "update_plan"}) + r = ctx.c.call("POST", "/v1/responses", body) + sc.check("forced tool_choice: HTTP 200", r.status == 200, r.payload[:300]) + j = r.json or {} + calls = check_calls(sc, j, "forced") + sc.check("forced tool_choice: update_plan was called", any(c.get("name") == "update_plan" for c in calls), [i.get("type") for i in j.get("output", [])]) + # tool_choice none: must not call + body = codex_body(ctx.model, "Use the shell tool to run ls.", max_out=128, stream=False, temperature=0, tool_choice="none") + r = ctx.c.call("POST", "/v1/responses", body) + j = r.json or {} + sc.check("tool_choice none: no function_call item", r.status == 200 and not [i for i in j.get("output", []) if i.get("type") == "function_call"], r.payload[:300]) + + +def sc_multiturn(ctx, sc): + # (A) previous_response_id with store=true; only the new user message is sent + ids, usages = [], [] + qs = ["My project is called Leleka and it serves a Qwen model on one GPU. Remember the name. Reply OK.", + "What is the name of my project? Answer with one word.", + "And what does it serve, in five words or fewer?"] + prev = None + for n, q in enumerate(qs): + body = codex_body(ctx.model, q, max_out=48, store=True, temperature=0, tools=False) + if prev: + body = {"model": ctx.model, "instructions": INSTRUCTIONS, "input": [msg("user", q)], "previous_response_id": prev, "store": True, "stream": True, + "max_output_tokens": 48, "temperature": 0, "reasoning": {"effort": "none"}} + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, f"prev-id turn{n+1}") + resp = s.response() + prev = resp.get("id") + ids.append(prev) + u = resp.get("usage") or {} + usages.append(u) + rates(sc, s, f"prev_t{n+1}_") + sc.metric(f"prev_t{n+1}_text", s.text()[:120]) + if n == 1: + sc.check("prev-id: second turn remembers the project name", "leleka" in s.text().lower(), s.text()[:200]) + sc.metric("prev_ids", ids) + ctx.shared["stored_ids"] = ids + for n in (1, 2): + cached = (usages[n].get("input_tokens_details") or {}).get("cached_tokens", 0) + sc.check(f"prev-id turn{n+1}: engine reused the conversation prefix (cached_tokens > 0)", cached > 0, usages[n]) + sc.metric(f"prev_t{n+1}_prefill_tokens", usages[n].get("input_tokens", 0) - cached) + # (B) stateless full-history replay, store=false + history = [] + for n, q in enumerate(qs): + body = codex_body(ctx.model, None, max_out=48, temperature=0, tools=False, extra_input=history + [msg("user", q)]) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, f"replay turn{n+1}") + resp = s.response() + u = resp.get("usage") or {} + rates(sc, s, f"replay_t{n+1}_") + cached = (u.get("input_tokens_details") or {}).get("cached_tokens", 0) + sc.metric(f"replay_t{n+1}_prefill_tokens", u.get("input_tokens", 0) - cached) + if n >= 1: + sc.check(f"replay turn{n+1}: prefix reuse across a stateless replay (cached_tokens > 0)", cached > 0, u) + history += [msg("user", q)] + replay_items(resp) + # stored response resources + if ids and ids[0]: + r = ctx.c.call("GET", "/v1/responses/" + ids[0]) + sc.check("GET stored response", r.status == 200 and (r.json or {}).get("id") == ids[0], r.payload[:200]) + r = ctx.c.call("GET", "/v1/responses/" + ids[-1] + "/input_items") + sc.check("GET input_items lists expanded history", r.status == 200 and len((r.json or {}).get("data", [])) >= 3, r.payload[:200]) + r = ctx.c.call("DELETE", "/v1/responses/" + ids[0]) + sc.check("DELETE stored response", r.status == 200 and (r.json or {}).get("deleted") is True, r.payload[:200]) + r = ctx.c.call("GET", "/v1/responses/" + ids[0]) + sc.check("deleted response is 404", r.status == 404, r.status) + body = {"model": ctx.model, "input": [msg("user", "hi")], "previous_response_id": ids[0], "max_output_tokens": 8} + r = ctx.c.call("POST", "/v1/responses", body) + sc.check("continuing from a deleted id is 404 response_not_found", r.status == 404 and r.err().get("code") == "response_not_found", (r.status, r.payload[:200])) + + +def build_context(ctx, target_tokens): + """Repository text (sanitized: only files from --context-dir, no config/key/env files) of at least target_tokens, counted by the server.""" + files = [] + for pat in ("**/*.rs", "**/*.md"): + files += sorted(glob.glob(os.path.join(ctx.context_dir, pat), recursive=True)) + parts = [] + size = 0 + for f in files: + if any(x in f for x in (".env", "secret", "key", "token", "target/")): + continue + try: + t = open(f, encoding="utf-8").read() + except (OSError, UnicodeDecodeError): + continue + rel = os.path.relpath(f, ctx.context_dir).replace("\\", "/") + parts.append(f"=== {rel} ===\n{t}\n") + size += len(t) + if size > 6 * target_tokens and len(parts) > 4: + break + text = "".join(parts) + # trim/extend to the target by asking the server how many tokens the request has + def count(chars): + body = codex_body(ctx.model, "Context follows.\n" + text[:chars] + "\n\nQuestion: ", tools=True) + r = ctx.c.call("POST", "/v1/responses/input_tokens", {k: v for k, v in body.items() if k not in ("stream", "store", "prompt_cache_key", "include")}) + return (r.json or {}).get("input_tokens", 0) + lo, hi = 2000, len(text) + n = count(hi) + if n < target_tokens: + return text, n + while hi - lo > 400: + mid = (lo + hi) // 2 + if count(mid) >= target_tokens: + hi = mid + else: + lo = mid + return text[:hi], count(hi) + + +def sc_long(ctx, sc): + ctxt, n = build_context(ctx, ctx.long_tokens) + sc.metric("context_tokens_with_overhead", n) + sc.check(f"context built to >= {ctx.long_tokens} tokens", n >= ctx.long_tokens, n) + q1 = "Question: which Rust crate contains the Responses API worker for a text-level engine, and what file is it in? Answer in one sentence." + body = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\n" + q1, tools=False, max_out=96, temperature=0, store=False) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, "long turn1") + rates(sc, s, "long_t1_") + sc.metric("long_t1_text", s.text()[:200]) + resp = s.response() + u1 = resp.get("usage") or {} + sc.check("long: prompt >= target tokens in usage", u1.get("input_tokens", 0) >= ctx.long_tokens, u1) + # follow-up on the same context: only the suffix may be prefilled + q2 = "Question: now name one thing in the context about caching or cancellation, in one sentence." + history = replay_items(resp) + body2 = dict(body) + body2["input"] = body["input"] + history + [msg("user", q2)] + s2 = ctx_stream = ctx.c.stream("/v1/responses", body2) + check_stream(sc, s2, "long turn2") + rates(sc, s2, "long_t2_") + u2 = s2.response().get("usage") or {} + c2 = (u2.get("input_tokens_details") or {}).get("cached_tokens", 0) + sc.metric("long_t2_prefill_tokens", u2.get("input_tokens", 0) - c2) + sc.check("long turn2: re-prefilled only the suffix (cached_tokens >= 90% of turn1 prompt)", c2 >= 0.9 * u1.get("input_tokens", 1), (c2, u1.get("input_tokens"))) + if s.t_first_byte is not None and (s2.first("response.output_text.delta") or 0) > 0: + sc.metric("long_ttft_speedup_x", round((ttft(s) or 0) / max(ttft(s2) or 1e-9, 1e-9), 2)) + # a different question over the same context from scratch (root/turn checkpoint reuse) + body3 = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\nQuestion: how many tools does a Codex request declare in the e2e client? Short answer.", tools=False, max_out=48, temperature=0) + s3 = ctx.c.stream("/v1/responses", body3) + check_stream(sc, s3, "long variant") + rates(sc, s3, "long_t3_") + c3 = ((s3.response().get("usage") or {}).get("input_tokens_details") or {}).get("cached_tokens", 0) + sc.check("long variant: shared context prefix reused", c3 > 0.5 * u1.get("input_tokens", 1), c3) + if s.comments: + sc.note(f"long turn1: {len(s.comments)} keep-alive comment(s) during prefill") + # Informational: the same long context with the Codex tool list. The model decides whether to call a tool; a malformed call + # ends the stream with response.failed (the model's format error, see docs/e2e-run.md), which is recorded, not scored. + body4 = codex_body(ctx.model, "Repository context follows.\n" + ctxt + "\n\n" + q1, tools=True, max_out=256, temperature=0) + s4 = ctx.c.stream("/v1/responses", body4) + r4 = s4.response() + sc.metric("long_with_tools_status", r4.get("status")) + sc.metric("long_with_tools_types", [i.get("type") for i in r4.get("output", [])]) + sc.metric("long_with_tools_error", r4.get("error")) + rates(sc, s4, "long_t4_") + if r4.get("status") == "completed": + check_calls(sc, r4, "long with tools") + + +def sc_xlong(ctx, sc): + """A prompt long enough that prefill outlasts the 15 s SSE keep-alive, then a follow-up that must only prefill the suffix.""" + ctxt, n = build_context(ctx, ctx.xlong_tokens) + sc.metric("xlong_context_tokens_with_overhead", n) + sc.check(f"xlong context built to >= {ctx.xlong_tokens} tokens", n >= ctx.xlong_tokens, n) + q1 = "Question: name the file that implements the text-level engine worker. One sentence." + body = codex_body(ctx.model, "Repository context follows." + chr(10) + ctxt + chr(10) + chr(10) + q1, tools=False, max_out=64, temperature=0) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, "xlong turn1", expect_terminal=None) + rates(sc, s, "xlong_t1_") + u1 = s.response().get("usage") or {} + prefill_s = ttft(s) or 0 + if prefill_s > 16: + sc.check("xlong: SSE keep-alive comments flowed during the long prefill", len(s.comments) >= 1, len(s.comments)) + sc.metric("xlong_t1_prefill_tok_s", round(u1.get("input_tokens", 0) / prefill_s, 1) if prefill_s else None) + hist = replay_items(s.response()) + body2 = dict(body) + body2["input"] = body["input"] + hist + [msg("user", "Question: and what is its worker entry function called? One sentence.")] + s2 = ctx.c.stream("/v1/responses", body2) + check_stream(sc, s2, "xlong turn2", expect_terminal=None) + rates(sc, s2, "xlong_t2_") + u2 = s2.response().get("usage") or {} + c2 = (u2.get("input_tokens_details") or {}).get("cached_tokens", 0) + sc.metric("xlong_t2_prefill_tokens", u2.get("input_tokens", 0) - c2) + sc.check("xlong turn2: only the suffix was prefilled (cached >= 90%)", c2 >= 0.9 * u1.get("input_tokens", 1), (c2, u1.get("input_tokens"))) + + +def sc_cancel(ctx, sc): + # (1) disconnect mid-decode + body = codex_body(ctx.model, "Write a very long, detailed essay about the history of programming languages. Do not stop early.", tools=False, max_out=1500, temperature=0) + before = metrics_snapshot(ctx).get("generation", {}) + t_close = {} + + def stop(s): + if s.count("response.output_text.delta") >= 12: + t_close["t"] = time.monotonic() + return True + return False + s = ctx.c.stream("/v1/responses", body, stop=stop) + sc.check("cancel: stream was running and aborted client-side", s.aborted, (s.status, s.transport_error, len(s.events))) + freed = wait_idle(ctx, 60) + sc.check("cancel: engine idle again (metrics active=false, queue empty)", freed is not None, freed) + if freed is not None and "t" in t_close: + sc.metric("cancel_decode_free_s", round(time.monotonic() - t_close["t"], 3)) + after = metrics_snapshot(ctx).get("generation", {}) + sc.check("cancel: metrics count the cancelled generation", after.get("cancelled", 0) >= before.get("cancelled", 0) + 1, (before, after)) + ctx.c.call("GET", "/status") + s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with OK.", tools=False, max_out=16, temperature=0)) + check_stream(sc, s, "after cancel (decode)") + sc.check("after cancel: the next request answers", len(s.text().strip()) > 0, s.text()) + # (2) disconnect during prefill of a long prompt (before the first delta) + ctxt, n = build_context(ctx, 6000) + body = codex_body(ctx.model, "Context.\n" + ctxt + "\n\nSummarize the context in detail.", max_out=200, temperature=0) + t_close.clear() + + def stop2(s): + if s.first("response.created") is not None: + t_close["t"] = time.monotonic() + time.sleep(1.5) + return True + return False + s = ctx.c.stream("/v1/responses", body, stop=stop2) + sc.check("cancel in prefill: aborted before any text", s.aborted and s.count("response.output_text.delta") == 0, (s.aborted, s.types()[:5])) + freed = wait_idle(ctx, 120) + sc.check("cancel in prefill: engine idle again", freed is not None, freed) + if freed is not None and "t" in t_close: + sc.metric("cancel_prefill_free_s", round(time.monotonic() - t_close["t"], 3)) + s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with OK.", tools=False, max_out=16, temperature=0)) + check_stream(sc, s, "after cancel (prefill)") + st = ctx.c.call("GET", "/status").json or {} + sc.check("after cancels: still ready", st.get("ready") is True, st) + # (3) the same prompt as the cancelled one still gives a full answer + s = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Context.\n" + ctxt + "\n\nSummarize the context in one sentence.", max_out=64, temperature=0)) + check_stream(sc, s, "cancelled prompt re-sent", expect_terminal=None) + rates(sc, s, "cancel_resend_") + + +def sc_parallel(ctx, sc): + # A runs a long generation; B (stream), C (json) arrive while it runs: the engine serves one at a time. + res = {} + started = threading.Event() + + def run_a(): + body = codex_body(ctx.model, "Count from 1 to 120, one number per line, nothing else.", tools=False, max_out=420, temperature=0) + + def stop(s): + if s.count("response.output_text.delta") >= 3: + started.set() + return False + res["A"] = ctx.c.stream("/v1/responses", body, stop=stop) + res["A_end"] = time.monotonic() + t0 = time.monotonic() + ta = threading.Thread(target=run_a) + ta.start() + sc.check("parallel: A started streaming", started.wait(60), None) + m = metrics_snapshot(ctx) + sc.metric("metrics_while_A_runs", {"active": m.get("active"), "queue_used": m.get("queue_used"), "queue_capacity": m.get("queue_capacity")}) + sc.check("parallel: /metrics shows an active generation", m.get("active") is True, m) + + def run_b(): + res["B_start"] = time.monotonic() + res["B"] = ctx.c.stream("/v1/responses", codex_body(ctx.model, "Reply with the single word: BETA", tools=False, max_out=16, temperature=0)) + res["B_end"] = time.monotonic() + + def run_c(): + res["C_start"] = time.monotonic() + res["C"] = ctx.c.call("POST", "/v1/responses", codex_body(ctx.model, "Reply with the single word: GAMMA", tools=False, max_out=16, temperature=0, stream=False)) + res["C_end"] = time.monotonic() + tb, tc = threading.Thread(target=run_b), threading.Thread(target=run_c) + tb.start() + time.sleep(0.3) + tc.start() + time.sleep(0.5) + m = metrics_snapshot(ctx) + sc.metric("metrics_with_B_C_waiting", {"active": m.get("active"), "queue_used": m.get("queue_used")}) + # health endpoints stay responsive while the engine is busy + t = time.monotonic() + st = ctx.c.call("GET", "/status") + sc.check("parallel: /status answers while busy", st.status == 200 and (time.monotonic() - t) < 2.0, (st.status, round(time.monotonic() - t, 2))) + for t_ in (ta, tb, tc): + t_.join(300) + A, B, C = res.get("A"), res.get("B"), res.get("C") + check_stream(sc, A, "A") + check_stream(sc, B, "B (queued)") + sc.check("parallel: C (json, queued) answered 200", C is not None and C.status == 200 and (C.json or {}).get("status") == "completed", C and C.payload[:200]) + sc.check("parallel: B text is BETA", B is not None and "BETA" in B.text().upper(), B and B.text()) + sc.check("parallel: no request lost or merged (A has many lines)", A is not None and A.text().count("\n") > 30, A and A.text()[:80]) + # B was queued behind A: B's first text came after A's terminal + b_first_abs = (res["B_start"] - t0) + (ttft(B) or 0) + a_end_abs = res["A_end"] - t0 + sc.metric("A_total_s", round(a_end_abs, 2)) + sc.metric("B_created_s_after_start", round((res["B_start"] - t0) + (B.first("response.created") or 0), 2)) + sc.metric("B_first_text_s", round(b_first_abs, 2)) + sc.metric("B_wait_after_A_end_s", round(b_first_abs - a_end_abs, 2)) + sc.check("parallel: B queued behind A (its text starts after A finished)", b_first_abs >= a_end_abs - 0.2, (b_first_abs, a_end_abs)) + wait_idle(ctx, 30) + # overload: more simultaneous POSTs than max_in_flight_requests (17 by default) + out = [] + lock = threading.Lock() + + def tiny(i): + r = ctx.c.call("POST", "/v1/responses", codex_body(ctx.model, f"Reply with the number {i}.", tools=False, max_out=6, temperature=0, stream=False), timeout=600) + with lock: + out.append(r) + ths = [threading.Thread(target=tiny, args=(i,)) for i in range(ctx.burst)] + t0 = time.monotonic() + for t_ in ths: + t_.start() + for t_ in ths: + t_.join(900) + codes = sorted(r.status for r in out) + sc.metric("burst_status_codes", {str(k): codes.count(k) for k in set(codes)}) + sc.metric("burst_total_s", round(time.monotonic() - t0, 1)) + ok = [r for r in out if r.status == 200] + over = [r for r in out if r.status == 429] + sc.check("burst: every request got 200 or 429 runtime_overloaded", len(ok) + len(over) == len(out) and all(r.err().get("code") == "runtime_overloaded" for r in over), codes) + sc.check("burst: all admitted requests completed", all((r.json or {}).get("status") in ("completed", "incomplete") for r in ok), [r.payload[:100] for r in ok if (r.json or {}).get("status") not in ("completed", "incomplete")][:2]) + sc.check("burst: 429 carries Retry-After", all(any(k.lower() == "retry-after" for k in r.headers) for r in over), None) + wait_idle(ctx, 120) + st = ctx.c.call("GET", "/status").json or {} + sc.check("burst: still ready afterwards", st.get("ready") is True, st) + + +INVALID = [ + ("malformed JSON", None, b'{"model": "x", "input": ', 400, None), + ("missing model", {"input": "hi"}, None, 400, None), + ("unknown model", {"model": "no-such-model", "input": "hi"}, None, (400, 404), None), + ("missing input", {"model": "@M"}, None, 400, None), + ("empty input array", {"model": "@M", "input": []}, None, 400, None), + ("input of wrong type", {"model": "@M", "input": 5}, None, 400, None), + ("unknown top-level field", {"model": "@M", "input": "hi", "bogus_field": 1}, None, 400, None), + ("max_output_tokens zero", {"model": "@M", "input": "hi", "max_output_tokens": 0}, None, 400, None), + ("max_output_tokens above the runtime cap", {"model": "@M", "input": "hi", "max_output_tokens": 99999}, None, 400, None), + ("negative max_output_tokens", {"model": "@M", "input": "hi", "max_output_tokens": -3}, None, 400, None), + ("temperature out of range", {"model": "@M", "input": "hi", "temperature": 9}, None, 400, None), + ("top_p out of range", {"model": "@M", "input": "hi", "top_p": 2}, None, 400, None), + ("tool without a name", {"model": "@M", "input": "hi", "tools": [{"type": "function", "parameters": {"type": "object"}}]}, None, 400, None), + ("tool with an invalid name", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "bad name!", "parameters": {"type": "object"}}]}, None, 400, None), + ("duplicate tool names", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "a", "parameters": {"type": "object"}}, {"type": "function", "name": "a", "parameters": {"type": "object"}}]}, None, 400, None), + ("tool_choice naming an undeclared tool", {"model": "@M", "input": "hi", "tools": [{"type": "function", "name": "a", "parameters": {"type": "object"}}], "tool_choice": {"type": "function", "name": "zzz"}}, None, 400, None), + ("hosted tool", {"model": "@M", "input": "hi", "tools": [{"type": "web_search"}]}, None, 400, None), + ("unknown previous_response_id", {"model": "@M", "input": "hi", "previous_response_id": "resp_nope"}, None, 404, "response_not_found"), + ("function_call_output without a call", {"model": "@M", "input": [{"type": "function_call_output", "call_id": "call_zzz", "output": "x"}]}, None, 400, None), + ("image input", {"model": "@M", "input": [{"type": "message", "role": "user", "content": [{"type": "input_image", "image_url": "data:image/png;base64,AAAA"}]}]}, None, 400, None), + ("reasoning_budget_tokens", {"model": "@M", "input": "hi", "reasoning_budget_tokens": 10}, None, 400, "unsupported_request_field"), + ("bad reasoning effort", {"model": "@M", "input": "hi", "reasoning": {"effort": "turbo"}}, None, 400, None), + ("text.format json_schema without schema", {"model": "@M", "input": "hi", "text": {"format": {"type": "json_schema", "name": "x"}}}, None, 400, None), + ("context overflow", "OVERFLOW", None, 400, None), +] + + +def sc_invalid(ctx, sc): + for name, body, raw, expect, code in INVALID: + if body == "OVERFLOW": + body = {"model": ctx.model, "input": "hello " * 300000, "max_output_tokens": 16} + if isinstance(body, dict): + body = json.loads(json.dumps(body).replace("@M", ctx.model)) + r = ctx.c.call("POST", "/v1/responses", body, raw=raw, timeout=120) + exp = expect if isinstance(expect, tuple) else (expect,) + shape = bool(r.err().get("message")) and "type" in r.err() + sc.check(f"invalid[{name}]: status in {exp} (got {r.status}, code={r.err().get('code')})", r.status in exp, r.payload[:240]) + sc.check(f"invalid[{name}]: error body has message/type/code", shape or r.status == 200, r.payload[:200]) + if code: + sc.check(f"invalid[{name}]: code {code}", r.err().get("code") == code, r.err()) + sc.metric(f"invalid[{name}]", [r.status, r.err().get("code")]) + # same invalid requests on the streaming path never produce a half-open stream + s = ctx.c.stream("/v1/responses", {"model": ctx.model, "input": "hi", "stream": True, "max_output_tokens": 0}) + sc.check("invalid stream request answers a plain JSON 400, no SSE", s.status == 400, (s.status, s.error_body[:200])) + wait_idle(ctx, 10) + st = ctx.c.call("GET", "/status").json or {} + sc.check("invalid: server still ready", st.get("ready") is True, st) + + +def sc_compat(ctx, sc): + # Chat Completions and Messages share the worker; one small request each. + body = {"model": ctx.model, "messages": [{"role": "system", "content": "You are terse."}, {"role": "user", "content": "Say hello in three words."}], + "max_tokens": 32, "temperature": 0, "stream": False} + r = ctx.c.call("POST", "/v1/chat/completions", body) + ch = (r.json or {}).get("choices", [{}])[0] + sc.check("chat completions: 200 with content and finish_reason", r.status == 200 and ch.get("message", {}).get("content") and ch.get("finish_reason") in ("stop", "length"), r.payload[:300]) + body = {"model": ctx.model, "max_tokens": 32, "temperature": 0, "messages": [{"role": "user", "content": "Say hello in three words."}]} + r = ctx.c.call("POST", "/v1/messages", body, headers={"anthropic-version": "2023-06-01"}) + sc.check("messages: 200 with content and stop_reason", r.status == 200 and (r.json or {}).get("content") and (r.json or {}).get("stop_reason") in ("end_turn", "max_tokens"), r.payload[:300]) + body = {"model": ctx.model, "tools": [{"type": "function", "function": {"name": "shell", "description": "run", "parameters": TOOLS[0]["parameters"]}}], + "messages": [{"role": "user", "content": "Run `ls` with the shell tool."}], "max_tokens": 200, "temperature": 0} + r = ctx.c.call("POST", "/v1/chat/completions", body) + ch = (r.json or {}).get("choices", [{}])[0] + tc = ch.get("message", {}).get("tool_calls") or [] + ok = r.status == 200 and ch.get("finish_reason") == "tool_calls" and tc + if ok: + try: + a = json.loads(tc[0]["function"]["arguments"]) + ok = not validate(TOOLS[0]["parameters"], a) + except ValueError: + ok = False + sc.check("chat completions: tool call with valid arguments, finish_reason tool_calls", ok, r.payload[:400]) + + +PROMPTS = [ + "What is the capital of France? One word.", "Name three prime numbers. Short.", "Translate 'good morning' to German.", + "What does the Rust keyword `mut` do? One sentence.", "Give a one-line shell command that counts lines in all .rs files.", + "What is 17 times 23?", "Name the largest planet in the solar system.", "Is a tomato a fruit? Answer yes or no.", +] + + +def sc_soak(ctx, sc): + n = ctx.soak_n + base = sample(ctx) + sc.metric("soak_baseline", base) + samples = [base] + lat, tps, bad = [], [], 0 + gen0 = metrics_snapshot(ctx).get("generation", {}) + for i in range(n): + p = PROMPTS[i % len(PROMPTS)] + tool = (i % 4 == 3) + if tool: + p = "Use the shell tool to print the current date (run `date`)." + body = codex_body(ctx.model, p, tools=True, max_out=160 if tool else 48, temperature=0, stream=(i % 2 == 0)) + t = time.monotonic() + if body["stream"]: + s = ctx.c.stream("/v1/responses", body) + resp = s.response() + ok = s.status == 200 and s.terminal() is not None and s.types()[0] == "response.created" and resp.get("status") in ("completed", "incomplete") + tt = ttft(s) + u = resp.get("usage") or {} + if tt is not None and s.t_end and u.get("output_tokens", 0) > 4 and s.t_end - tt > 0.05: + tps.append((u["output_tokens"] - 1) / (s.t_end - tt)) + else: + r = ctx.c.call("POST", "/v1/responses", body) + resp = r.json or {} + ok = r.status == 200 and resp.get("status") in ("completed", "incomplete") + dt = time.monotonic() - t + lat.append(dt) + if tool and ok: + for c in [x for x in resp.get("output", []) if x.get("type") == "function_call"]: + try: + a = json.loads(c["arguments"]) + ok = ok and not validate(TOOL_BY_NAME[c["name"]]["parameters"], a) + except (ValueError, KeyError): + ok = False + if not ok: + bad += 1 + sc.note(f"soak request {i} failed: {str(resp)[:200]}") + if i % 5 == 4: + samples.append(sample(ctx)) + sc.check(f"soak: all {n} consecutive requests succeeded", bad == 0, f"{bad} bad") + sc.metric("soak_samples", samples) + lat_sorted = sorted(lat) + sc.metric("soak_latency_s", {"min": round(lat_sorted[0], 2), "p50": round(lat_sorted[len(lat) // 2], 2), "p90": round(lat_sorted[int(len(lat) * 0.9)], 2), "max": round(lat_sorted[-1], 2)}) + if tps: + sc.metric("soak_decode_tok_s_mean", round(sum(tps) / len(tps), 2)) + sc.check("soak: latency of the last third is not worse than 1.5x the first third", sum(lat[-n // 3:]) <= 1.5 * sum(lat[:n // 3]) + 1.0, (sum(lat[:n // 3]), sum(lat[-n // 3:]))) + for key in [k for k in base if k.startswith("rss_mib_")]: + a, b = samples[1][key] if len(samples) > 1 else base[key], samples[-1][key] + grow = b - a + sc.metric(f"soak_{key}_growth_after_first_5", grow) + sc.check(f"soak: {key} growth after warm-up < 256 MiB", grow < 256, (a, b)) + g0, g1 = (samples[1].get("gpu_used_mib") if len(samples) > 1 else None), samples[-1].get("gpu_used_mib") + if g0 is not None and g1 is not None: + sc.metric("soak_gpu_growth_mib", g1 - g0) + sc.check("soak: GPU memory growth after warm-up < 64 MiB", g1 - g0 < 64, (g0, g1)) + gen1 = metrics_snapshot(ctx).get("generation", {}) + sc.metric("soak_metrics_delta", {k: gen1.get(k, 0) - gen0.get(k, 0) for k in ("started", "completed", "cancelled", "failed_or_interrupted")}) + sc.check("soak: metrics count every generation as completed", gen1.get("completed", 0) - gen0.get("completed", 0) == n, (gen0, gen1)) + + +def sc_determinism(ctx, sc): + body = codex_body(ctx.model, "List five programming languages, comma separated, nothing else.", tools=False, max_out=40, temperature=0, stream=False) + outs = [] + for _ in range(3): + r = ctx.c.call("POST", "/v1/responses", body) + j = r.json or {} + outs.append("".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", []))) + sc.check("greedy: three identical requests give identical text", len(set(outs)) == 1, outs) + body["temperature"], body["seed"] = 0.8, 1234 + outs = [] + for _ in range(2): + r = ctx.c.call("POST", "/v1/responses", body) + j = r.json or {} + outs.append("".join(p.get("text", "") for i in j.get("output", []) if i.get("type") == "message" for p in i.get("content", []))) + if outs[0] == outs[1]: + sc.check("sampled with a fixed seed: reproducible", True) + else: + # documented envelope: with the adaptive VRAM expert tier GPU and CPU experts round differently and placement follows copy timing + sc.note(f"sampled with a fixed seed differs between two runs (adaptive expert tier envelope): {outs}") + sc.metric("sampled_text", outs[0][:120]) + + +def sc_reasoning(ctx, sc): + # Codex default: reasoning effort medium with a summary request. Thinking tokens come first, then answer. + body = codex_body(ctx.model, "What is 12 * 13? Think briefly, then answer with just the number.", effort="medium", max_out=1536, temperature=0) + s = ctx.c.stream("/v1/responses", body) + check_stream(sc, s, "reasoning", expect_terminal=None) + resp = s.response() + types = [i.get("type") for i in resp.get("output", [])] + sc.metric("reasoning_output_types", types) + sc.metric("reasoning_status", resp.get("status")) + u = resp.get("usage") or {} + sc.metric("reasoning_usage", u) + if resp.get("status") == "completed": + sc.check("reasoning: answer contains 156", "156" in s.text(), s.text()[:200]) + sc.check("reasoning: a reasoning item precedes the message", types[:1] == ["reasoning"] or "reasoning" in types, types) + sc.check("reasoning: reasoning_tokens reported and <= output_tokens", 0 <= (u.get("output_tokens_details") or {}).get("reasoning_tokens", 0) <= u.get("output_tokens", 0), u) + else: + sc.note(f"reasoning ended {resp.get('status')}: {resp.get('incomplete_details')}") + rates(sc, s, "reasoning_") + # reasoning turn replay with the reasoning item (Codex replays it) must be accepted + hist = replay_items(resp) + if hist: + body2 = codex_body(ctx.model, None, effort="medium", max_out=256, temperature=0, extra_input=[msg("user", "What is 12 * 13? Think briefly, then answer with just the number.")] + hist + [msg("user", "Now multiply that by 2. Just the number.")]) + s2 = ctx.c.stream("/v1/responses", body2) + sc.check("reasoning replay: accepted (HTTP 200)", s2.status == 200, (s2.status, s2.error_body[:300])) + if s2.status == 200: + check_stream(sc, s2, "reasoning replay", expect_terminal=None) + rates(sc, s2, "reasoning_t2_") + + +SCENARIOS = [ + ("endpoints", sc_endpoints), ("simple", sc_simple), ("tools", sc_tools), ("multiturn", sc_multiturn), ("long", sc_long), ("xlong", sc_xlong), + ("cancel", sc_cancel), ("parallel", sc_parallel), ("invalid", sc_invalid), ("compat", sc_compat), ("determinism", sc_determinism), + ("reasoning", sc_reasoning), ("soak", sc_soak), +] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base", required=True) + ap.add_argument("--key-file", required=True) + ap.add_argument("--model", required=True) + ap.add_argument("--out", required=True) + ap.add_argument("--scenarios", default="all") + ap.add_argument("--context-dir", default=None) + ap.add_argument("--long-tokens", type=int, default=8500) + ap.add_argument("--xlong-tokens", type=int, default=24000) + ap.add_argument("--soak-n", type=int, default=40) + ap.add_argument("--burst", type=int, default=20) + ap.add_argument("--pids", default="", help="name=pid,... processes whose RSS is sampled") + a = ap.parse_args() + key = open(a.key_file).read().strip() + ctx = Ctx() + ctx.c, ctx.base, ctx.model, ctx.shared = Client(a.base, key), a.base, a.model, {} + ctx.context_dir, ctx.long_tokens, ctx.soak_n, ctx.burst = a.context_dir, a.long_tokens, a.soak_n, a.burst + ctx.xlong_tokens = a.xlong_tokens + ctx.pids = {k: int(v) for k, v in (p.split("=") for p in a.pids.split(",") if p)} + ctx.t_start = time.time() + wanted = [n for n, _ in SCENARIOS] if a.scenarios == "all" else a.scenarios.split(",") + results = [] + print(f"scenarios: {wanted}", flush=True) + for name, fn in SCENARIOS: + if name not in wanted: + continue + print(f"== {name}", flush=True) + sc = Scenario(name) + try: + fn(ctx, sc) + except Exception: + sc.error = traceback.format_exc()[-1500:] + print(" ERROR " + sc.error, flush=True) + try: + sc.metrics["env_after"] = sample(ctx) + sc.metrics["server_metrics_after"] = metrics_snapshot(ctx) + except Exception: + pass + results.append(sc.as_dict()) + with open(a.out, "w") as f: + json.dump({"scenarios": results}, f, indent=1) + total = sum(len(r["checks"]) for r in results) + failed = [(r["name"], c["name"]) for r in results for c in r["checks"] if not c["ok"]] + print(f"\nSUMMARY: {len(results)} scenarios, {total} checks, {len(failed)} failed, {sum(1 for r in results if r['error'])} errors", flush=True) + for n, c in failed: + print(f" FAILED [{n}] {c}") + sys.exit(0 if not failed and not any(r["error"] for r in results) else 1) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/fake_llm_engine.py b/scripts/e2e/fake_llm_engine.py new file mode 100644 index 00000000..3a3efe18 --- /dev/null +++ b/scripts/e2e/fake_llm_engine.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""A scripted stand-in "model" for the e2e client: a stdio token engine for `fake_runtime` (TEST TOOLING ONLY, not shipped). + + fake_runtime ... --engine fake_llm_engine.py --engine-arg TOKENIZER_DIR --engine-arg STRATA_NEXT_BINARY + +It speaks the stdio wire protocol (`READY`, `GEN [k=v...] ids`, `T `, `DONE ...`, `STOP`, `QUIT`), decodes the prompt with +`strata-next model detokenize`, picks a canned reply from the last user turn and streams it token by token. It exists so the e2e +client and the API stack can be exercised without a GPU and so the client's own checks can be tested; it says nothing about the +real model. Prefix reuse is emulated as the common prefix with the previous prompt. +""" +import json +import re +import subprocess +import sys +import threading +import time + +TOK, BIN = sys.argv[2], sys.argv[3] # argv[1] is --serve +DELAY = 0.012 # seconds per token (cancel tests need a stream that lasts) + + +def run(*args): + return subprocess.run([BIN, "model", *args], capture_output=True, text=True, check=True).stdout.strip() + + +def detok(ids): + return json.loads(run("detokenize", TOK, ",".join(map(str, ids)))) + + +def tok(text): + return json.loads(run("tokenize", TOK, text, "--special")) + + +def last_user(prompt): + parts = prompt.split("<|im_start|>user\n") + return parts[-1].split("<|im_end|>")[0] if len(parts) > 1 else prompt + + +def reply(prompt, max_new): + u = last_user(prompt) + tools = "# Tools" in prompt + think_open = prompt.rstrip().endswith("") + pre = "I will answer directly.\n\n\n" if think_open else "" + if "" in u: + return pre + "The listing shows a Cargo.toml, a README.md and a src directory." + if tools and "shell tool" in u: + return pre + '\n\n\n["ls","-la"]\n\n\n' + if tools and "read_file tool" in u: + return pre + "\n\n\nsrc/main.rs\n\n\n1\n\n\n40\n\n\n" + if tools and "update_plan tool" in u: + plan = '[{"step":"inspect the code","status":"completed"},{"step":"fix the bug","status":"in_progress"},{"step":"run the tests","status":"pending"}]' + return pre + f"\n\n\n{plan}\n\n\n" + if tools and "Plan the work" in u: + return pre + '\n\n\n[{"step":"write tests","status":"in_progress"},{"step":"implement","status":"pending"}]\n\n\n' + if tools and "date" in u and "shell tool" in u: + return pre + '\n\n\n["date"]\n\n\n' + if "the quick brown fox jumps" in u: + return pre + "the quick brown fox jumps" + if "Count from 1 to 120" in u: + return pre + "\n".join(str(i) for i in range(1, 121)) + if "essay" in u: + return pre + ("Programming languages evolved from machine code to assemblers to compilers. " * 60) + if "BETA" in u: + return pre + "BETA" + if "GAMMA" in u: + return pre + "GAMMA" + if "name of my project" in u: + return pre + "Leleka" + if "what does it serve" in u.lower() or "And what does it" in u: + return pre + "A Qwen model on one GPU" + if "12 * 13" in u and "Now multiply" not in u: + return pre + "12 * 13 = 156\n\n\n156" if think_open else "156" + if "Now multiply" in u: + return pre + "312" + if "programming languages, comma" in u: + return pre + "Rust, C, Python, Go, Zig" + if "Summarize" in u or "Question:" in u: + return pre + "The worker lives in control-plane/src/backend_worker.rs in the strata-control crate." + return pre + "OK" + + +def main(): + print("READY 262144 stop", flush=True) + state = {"stop": False} + prev = [] + lines = [] + cond = threading.Condition() + + def reader(): + for line in sys.stdin: + line = line.strip() + if line == "STOP": + state["stop"] = True + else: + with cond: + lines.append(line) + cond.notify() + if line == "QUIT": + break + with cond: + lines.append("QUIT") + cond.notify() + threading.Thread(target=reader, daemon=True).start() + while True: + with cond: + while not lines: + cond.wait() + line = lines.pop(0) + if line == "QUIT": + return + if not line.startswith("GEN "): + print("ERR unexpected request", flush=True) + continue + state["stop"] = False + fields = line.split(" ") + max_new = int(fields[1]) + ids = [int(x) for x in fields[-1].split(",")] + print(f"fake-llm: GEN max_new={max_new} prompt_tokens={len(ids)}", file=sys.stderr, flush=True) + prompt = detok(ids) + text = reply(prompt, max_new) + out = tok(text) + print(f"fake-llm: reply {len(out)} tokens", file=sys.stderr, flush=True) + n = 0 + while n < len(prev) and n < len(ids) and prev[n] == ids[n]: + n += 1 + reused = max(0, n - 1) + prev = ids + t0 = time.monotonic() + # prefill takes time proportional to the non-reused prompt; emit progress for long ones + todo = len(ids) - reused + spent = 0 + while spent < todo and not state["stop"]: + step = min(2048, todo - spent) + time.sleep(0.0004 * step) + spent += step + print(f"PP {reused + spent} {len(ids)} 1 {1000 * (time.monotonic() - t0):.1f}", flush=True) + print(f"REUSED {reused}", flush=True) + t1 = time.monotonic() + produced = 0 + finish = "stop" + if state["stop"]: + finish = "cancel" + else: + for t in out: + if state["stop"]: + finish = "cancel" + break + if produced >= max_new: + finish = "length" + break + print(f"T {t}", flush=True) + produced += 1 + time.sleep(DELAY) + print(f"DONE {produced} {len(ids)} {1000 * (t1 - t0):.1f} {1000 * (time.monotonic() - t1):.1f} {finish} 0 0 {reused} 0 0", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/render_results.py b/scripts/e2e/render_results.py new file mode 100644 index 00000000..00d7a351 --- /dev/null +++ b/scripts/e2e/render_results.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Summarize an e2e results.json as text (offline helper for docs/e2e-run.md; not shipped).""" +import json +import sys + +d = json.load(open(sys.argv[1])) +for s in d["scenarios"]: + n = len(s["checks"]) + bad = [c for c in s["checks"] if not c["ok"]] + print(f"## {s['name']}: {n - len(bad)}/{n} checks passed, {s['seconds']}s" + (" ERROR" if s["error"] else "")) + for c in bad: + print(f" FAIL {c['name']} :: {c['detail'][:200]}") + if s["error"]: + print(" ERROR " + s["error"][-600:]) + for k, v in s["metrics"].items(): + if k in ("env_after", "server_metrics_after", "soak_samples"): + continue + print(f" {k} = {json.dumps(v)[:240]}") + for note in s["notes"]: + print(f" note: {note[:240]}") diff --git a/scripts/e2e/run-e2e.sh b/scripts/e2e/run-e2e.sh new file mode 100644 index 00000000..1310675e --- /dev/null +++ b/scripts/e2e/run-e2e.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Start the whole production stack on the GPU server and run the e2e client against it, then stop it and check for leaks. +# +# leleka-inference (Original serve backend, sealed KAR memfd inherited from the holder) +# leleka-daemon + leleka-cli load-mtp (explicit load; strata-next only attaches) +# strata-next serve (runtime block) <- scripts/e2e/e2e_client.py +# +# MUST run inside a holder job (it needs LELEKA_STRA169_KAR_FD, a sealed memfd). It refuses to start otherwise: the model process +# is never started outside the holder (MODEL.lock rules). Never builds anything. +# +# Environment (all optional except where noted): +# E2E_BIN directory with leleka-inference leleka-daemon leleka-cli strata-next (default ~/work/leleka-e2e/bin-sm120) +# E2E_OUT output directory for logs and results.json (default ~/work/leleka-e2e/runs/) +# E2E_CLIENT scripts/e2e/e2e_client.py (default next to this script) +# E2E_CONTEXT directory whose .rs/.md files make the long prompt (default ~/work/leleka-e2e/context) +# E2E_SCENARIOS client scenarios, comma separated or all (default all) +# E2E_CLIENT_ARGS extra client arguments (e.g. "--soak-n 40 --burst 20") +# E2E_ENGINE_ARGS extra leleka-inference arguments (e.g. "--original-prefill-capacity 4096") +set -uo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +W=$HOME/work/leleka-e2e +G=$HOME/work/gpu-runs +A=$HOME/leleka-gates/assets +BIN=${E2E_BIN:-$W/bin-sm120} +OUT=${E2E_OUT:-$W/runs/$(date -u +%Y%m%dT%H%M%SZ)} +CLIENT=${E2E_CLIENT:-$HERE/e2e_client.py} +CONTEXT=${E2E_CONTEXT:-$W/context} +STATE=$W/state +mkdir -p "$OUT" +log() { echo "[run-e2e $(date -u +%T)] $*"; } + +# ---- guards ------------------------------------------------------------------------------------------------------- +FD=${LELEKA_STRA169_KAR_FD:-} +if [ -z "$FD" ] || ! readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:'; then + echo "refusing to start: LELEKA_STRA169_KAR_FD is not a sealed memfd inherited from the holder; run this as a holder job" >&2 + exit 3 +fi +[ -d "$G/MODEL.lock" ] || { echo "refusing to start: $G/MODEL.lock is not held" >&2; exit 3; } +for b in leleka-inference leleka-daemon leleka-cli strata-next; do [ -x "$BIN/$b" ] || { echo "missing $BIN/$b" >&2; exit 3; }; done +if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then + echo "refusing to start: a stack process of this user is already running" >&2; pgrep -a -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >&2; exit 3 +fi +if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then + echo "refusing to start: something else already uses the GPU" >&2; nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader >&2; exit 3 +fi +for p in 18766 18080 8081; do + if ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN; then echo "port $p is in use" >&2; exit 3; fi +done + +# ---- environment -------------------------------------------------------------------------------------------------- +export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-} +install -d -m 0700 "$STATE" "$G/mtp-staging-own" +chmod 700 "$G/mtp-staging-own" +umask 077 +# two independent secrets and an API key; written to mode 0600 files and the environment, never printed +mkrand() { head -c 36 /dev/urandom | base64 | tr -d '\n'; } +export LELEKA_RUNTIME_TOKEN=$(mkrand) LELEKA_GATEWAY_TOKEN=$(mkrand) +KEYFILE=$STATE/api-key +rm -f "$KEYFILE" +"$BIN/strata-next" api-key init --file "$KEYFILE" >/dev/null 2>"$OUT/api-key-init.err" || { log "api-key init failed"; cat "$OUT/api-key-init.err"; exit 4; } +chmod 600 "$KEYFILE" + +# engine tuning exactly as the 98x bring-up jobs (VRAM expert tier, placeholder profile); serve profile prints one line per request +export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=${LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS:-2048} +export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=${LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER:-yes} +export LELEKA_ORIGINAL_SERVE_PCIE_FRAC=${LELEKA_ORIGINAL_SERVE_PCIE_FRAC:-0.55} +export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=${LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE:-$G/baseline/profile.bin} +export LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off RUST_BACKTRACE=1 +# synthetic prompts only: log the generated text when a streamed tool turn fails (operator debugging switch) +export STRATA_DEBUG_FAILED_OUTPUT=1 + +cat >"$STATE/daemon.json" <"$STATE/strata.json" </dev/null; } +stop_one() { # name pid grace + local name=$1 pid=$2 grace=$3 + alive "$pid" || { log "$name already gone"; return; } + kill -INT "$pid" 2>/dev/null + for _ in $(seq 1 "$grace"); do alive "$pid" || break; sleep 1; done + if alive "$pid"; then log "LEAK: $name ($pid) ignored SIGINT for ${grace}s, killing"; kill -KILL "$pid" 2>/dev/null; echo "$name ignored SIGINT" >>"$OUT/defects.txt"; fi +} +cleanup() { + log "shutting down" + stop_one strata-next "$PID_STR" 30 + stop_one leleka-daemon "$PID_DAE" 30 + stop_one leleka-inference "$PID_INF" 120 + sleep 2 + log "left over processes of this stack (expect none):" + pgrep -a -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' || echo " none" + log "GPU compute apps (expect none):" + nvidia-smi --query-compute-apps=pid,used_memory --format=csv,noheader || true + nvidia-smi --query-gpu=memory.used --format=csv,noheader || true + log "free -m: $(free -m | awk '/Mem:/{print "avail="$7" shared="$5}')" +} +trap cleanup EXIT + +# ---- tokenizer assets (offline, CPU) ------------------------------------------------------------------------------ +if [ ! -d "$TOK/tokenizer" ]; then + log "extracting tokenizer assets" + "$BIN/strata-next" model extract-tokenizer "$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf" --output "$TOK" >"$OUT/extract-tokenizer.log" 2>&1 || { log "extract-tokenizer failed"; tail -5 "$OUT/extract-tokenizer.log"; exit 4; } +fi +ls "$TOK" "$TOK/tokenizer" 2>&1 | head -5 + +# ---- engine ------------------------------------------------------------------------------------------------------ +log "starting leleka-inference (sm: $(sha256sum "$BIN/leleka-inference" | cut -c1-16))" +# The sealed KAR descriptor is inherited by the engine only: close it for the other processes started below. +# Optional on-demand kernel tracing of the live engine (tools/cupti-trace of claude/ledger): the library is injected at process +# start, idle until a trigger file appears (docs/e2e-run.md, "CUPTI hook"). Not set -> nothing changes. +if [ -n "${LELEKA_CUPTI_LIB:-}" ]; then + [ -r "$LELEKA_CUPTI_LIB" ] || { echo "LELEKA_CUPTI_LIB not readable"; exit 3; } + export CUDA_INJECTION64_PATH=$LELEKA_CUPTI_LIB LELEKA_CUPTI_TRIGGER=${LELEKA_CUPTI_TRIGGER:-$OUT/cupti.trigger} +fi +eval "\"$BIN/leleka-inference\" --listen 127.0.0.1:18766 --token-env LELEKA_RUNTIME_TOKEN \ + --shard0 \"$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf\" \ + --shard1 \"$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf\" \ + --gpu 0 --gpu-budget ${E2E_GPU_BUDGET:-25769803776} --context-tokens 262144 \ + --kar-archive-fd $FD --kar-provenance \"$A/qwen-iq3-s-l2-v4.kar.provenance.json\" \ + --mtp-pack \"$A/data/mtp-rt\" --mtp-staging \"$G/mtp-staging-own\" \ + --backend-mode original ${E2E_ENGINE_ARGS:-} >\"$OUT/inference.log\" 2>&1 &" +PID_INF=$! +unset CUDA_INJECTION64_PATH +sleep 3 +alive "$PID_INF" || { log "leleka-inference died at startup"; tail -20 "$OUT/inference.log"; exit 5; } +eval "\"$BIN/leleka-daemon\" --config \"$STATE/daemon.json\" $FD>&- >\"$OUT/daemon.log\" 2>&1 &" +PID_DAE=$! +sleep 2 +alive "$PID_DAE" || { log "leleka-daemon died at startup"; tail -20 "$OUT/daemon.log"; exit 5; } +CLI() { "$BIN/leleka-cli" --config "$STATE/daemon.json" "$@"; } +T_LOAD=$(date +%s) +log "load-mtp: $(CLI load-mtp qwen-iq3 qwen4exp-kar-ple-mtp-v1 2>&1 | tr '\n' ' ' | sed 's/"operation_id":"[^"]*",//')" +ready=0 +for i in $(seq 1 480); do + st=$(CLI status 2>&1) + if echo "$st" | grep -Eq '"model_ready" *: *true'; then ready=1; break; fi + alive "$PID_INF" || { log "leleka-inference died during load"; tail -30 "$OUT/inference.log"; exit 5; } + if grep -q '^leleka-load phase=' "$OUT/inference.log" 2>/dev/null; then + log "load failed:"; grep -E '^leleka-(load|serve)' "$OUT/inference.log" | head -10; echo "$st" | head -12; exit 5 + fi + sleep 5 +done +LOAD_S=$(( $(date +%s) - T_LOAD )) +[ "$ready" = 1 ] || { log "model did not become ready in 2400 s"; echo "$st" | head -20; tail -30 "$OUT/inference.log"; exit 5; } +log "model ready after ${LOAD_S}s" +echo "load_seconds=$LOAD_S" >"$OUT/load.txt" + +# ---- API --------------------------------------------------------------------------------------------------------- +eval "\"$BIN/strata-next\" serve --config \"$STATE/strata.json\" $FD>&- >\"$OUT/strata-next.log\" 2>&1 &" +PID_STR=$! +if ! "$BIN/strata-next" wait-ready --url http://127.0.0.1:8081 --model qwen-iq3 --key-file "$KEYFILE" --timeout-s 180 >"$OUT/wait-ready.log" 2>&1; then + log "strata-next never became ready"; tail -20 "$OUT/wait-ready.log"; tail -30 "$OUT/strata-next.log"; exit 6 +fi +log "strata-next ready" +echo "pids inference=$PID_INF daemon=$PID_DAE strata=$PID_STR" +rss() { awk '/VmRSS/{print int($2/1024)" MiB"}' /proc/$1/status; } +log "rss after load: inference $(rss "$PID_INF"), strata-next $(rss "$PID_STR"), gpu $(nvidia-smi --query-gpu=memory.used --format=csv,noheader)" + +# ---- client ------------------------------------------------------------------------------------------------------ +if [ -n "${E2E_STATUS_FILE:-}" ]; then bash "$HERE/status_writer.sh" "$OUT" "$E2E_STATUS_FILE" "${E2E_STATUS_S:-60}" >/dev/null 2>&1 & PID_STATUS=$!; fi +bash "$HERE/sample_env.sh" "$OUT/env.tsv" "${E2E_SAMPLE_S:-30}" "inference=$PID_INF" "strata=$PID_STR" "daemon=$PID_DAE" >/dev/null 2>&1 & +PID_SAMPLER=$! +if [ -n "${E2E_RUN_CMD:-}" ]; then + # an external client (the Codex CLI jobs): it gets the base URL and a key variable; the key file stays private + export E2E_BASE_URL=http://127.0.0.1:8081 E2E_MODEL=qwen-iq3 E2E_OUT_DIR="$OUT" + E2E_API_KEY=$(cat "$KEYFILE") bash -c "$E2E_RUN_CMD" 2>&1 | tee "$OUT/client.log" + RC=${PIPESTATUS[0]} +else + python3 -I "$CLIENT" --base http://127.0.0.1:8081 --key-file "$KEYFILE" --model qwen-iq3 --out "$OUT/results.json" \ + --scenarios "${E2E_SCENARIOS:-all}" --context-dir "$CONTEXT" --pids "inference=$PID_INF,strata=$PID_STR,daemon=$PID_DAE" ${E2E_CLIENT_ARGS:-} 2>&1 | tee "$OUT/client.log" + RC=${PIPESTATUS[0]} +fi +kill "$PID_SAMPLER" ${PID_STATUS:-} 2>/dev/null +log "client exit status $RC" +log "engine stderr tail (request outcome lines):" +grep -E 'leleka-serve request|panicked|ERROR|error' "$OUT/inference.log" | tail -n 15 | cut -c1-300 +log "strata-next stderr (non-empty lines, head):" +grep -v '^$' "$OUT/strata-next.log" | head -n 15 | cut -c1-300 +echo "$RC" >"$OUT/client.rc" +exit "$RC" diff --git a/scripts/e2e/run-fake.sh b/scripts/e2e/run-fake.sh new file mode 100644 index 00000000..6c7929f8 --- /dev/null +++ b/scripts/e2e/run-fake.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Run e2e_client.py against strata-next in front of a scripted fake engine (no GPU, no model): TEST TOOLING for the client itself. +# run-fake.sh STRATA_NEXT FAKE_RUNTIME TOKENIZER_DIR OUT_DIR [client args...] +# fake_runtime = `cargo build --release -p strata-desktop-core --example fake_runtime`; its engine is fake_llm_engine.py. +set -uo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +SN=$1 FAKE=$2 TOK=$3 OUT=$4; shift 4 +mkdir -p "$OUT"; chmod 700 "$OUT"; umask 077 +export FAKE_RUNTIME_TOKEN="fixture-runtime-credential-$(head -c 12 /dev/urandom | base64 | tr -d '/+=\n')" +KEY="$OUT/api-key"; rm -f "$KEY"; "$SN" api-key init --file "$KEY" >/dev/null || { echo "api-key init failed"; exit 4; } +chmod +x "$HERE/fake_llm_engine.py" +( sleep 3600 | "$FAKE" --listen 127.0.0.1:0 --token-env FAKE_RUNTIME_TOKEN --engine "$HERE/fake_llm_engine.py" --tokenizer "$TOK" \ + --engine-arg "$TOK" --engine-arg "$SN" >"$OUT/fake_runtime.out" 2>"$OUT/fake_runtime.err" ) & +for _ in $(seq 1 100); do grep -q LISTENING "$OUT/fake_runtime.out" 2>/dev/null && break; sleep 0.1; done +ADDR=$(awk '/LISTENING/{print $2}' "$OUT/fake_runtime.out") +[ -n "$ADDR" ] || { echo "fake runtime did not start"; cat "$OUT/fake_runtime.err"; exit 4; } +cat >"$OUT/strata.json" <"$OUT/strata-next.log" 2>&1 & +SPID=$! +trap 'kill -INT $SPID 2>/dev/null; pkill -P $$ 2>/dev/null; sleep 1; pkill -f fake_runtime 2>/dev/null; true' EXIT +"$SN" wait-ready --url http://127.0.0.1:18081 --model qwen-iq3 --key-file "$KEY" --timeout-s 60 >"$OUT/wait-ready.log" 2>&1 || { echo "not ready"; cat "$OUT/wait-ready.log"; tail "$OUT/strata-next.log"; exit 6; } +[ -n "${E2E_FAKE_HOLD:-}" ] && { echo "holding the stack for $E2E_FAKE_HOLD s (manual debugging)"; sleep "$E2E_FAKE_HOLD"; exit 0; } +python3 -I "$HERE/e2e_client.py" --base http://127.0.0.1:18081 --key-file "$KEY" --model qwen-iq3 --out "$OUT/results.json" \ + --context-dir "${E2E_CONTEXT:-$HERE/../../control-plane/src}" --pids "strata=$SPID" "$@" diff --git a/scripts/e2e/sample_env.sh b/scripts/e2e/sample_env.sh new file mode 100644 index 00000000..85e99426 --- /dev/null +++ b/scripts/e2e/sample_env.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# sample_env.sh OUT.tsv INTERVAL_S name=pid ... : memory/VRAM time series of a running stack (test tooling). +out=$1; every=$2; shift 2 +echo -e "epoch\tname\tvmrss_mib\tvmhwm_mib\trssanon_mib\trssshmem_mib\tvmlck_mib\tgpu_used_mib\tmem_available_mib" >"$out" +while :; do + now=$(date +%s) + gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits 2>/dev/null | head -1) + avail=$(awk '/MemAvailable/{print int($2/1024)}' /proc/meminfo) + for spec in "$@"; do + name=${spec%%=*}; pid=${spec#*=} + [ -r /proc/$pid/status ] || continue + awk -v n="$name" -v t="$now" -v g="$gpu" -v a="$avail" ' + /^VmRSS:/{rss=$2} /^VmHWM:/{hwm=$2} /^RssAnon:/{an=$2} /^RssShmem:/{sh=$2} /^VmLck:/{lck=$2} + END{printf "%s\t%s\t%d\t%d\t%d\t%d\t%d\t%s\t%s\n", t, n, rss/1024, hwm/1024, an/1024, sh/1024, lck/1024, g, a}' /proc/$pid/status >>"$out" + done + sleep "$every" +done diff --git a/scripts/e2e/status_writer.sh b/scripts/e2e/status_writer.sh new file mode 100644 index 00000000..e37a51c2 --- /dev/null +++ b/scripts/e2e/status_writer.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# status_writer.sh OUT_DIR STATUS_FILE [INTERVAL_S] : one line per interval about a running session (test tooling). +out=$1; status=$2; every=${3:-60} +t0=$(date +%s) +echo "# $(date -u +%FT%TZ) session $(basename "$out") started" >>"$status" +while :; do + sleep "$every" + log="$out/strata-next.log" + n=$(grep -c 'generation done:' "$log" 2>/dev/null) + last=$(grep 'generation done:' "$log" 2>/dev/null | tail -1) + ctx=$(echo "$last" | sed -n 's/.*prompt_tokens=\([0-9]*\).*/\1/p') + reused=$(echo "$last" | sed -n 's/.*reused=\([0-9]*\).*/\1/p') + gen=$(echo "$last" | sed -n 's/.* generated=\([0-9]*\).*/\1/p') + pms=$(echo "$last" | sed -n 's/.*prompt_ms=\([0-9.]*\).*/\1/p') + dms=$(echo "$last" | sed -n 's/.*decode_ms=\([0-9.]*\).*/\1/p') + rate=$(awk -v g="${gen:-0}" -v d="${dms:-0}" 'BEGIN{ if (d>50 && g>1) printf "%.1f", (g-1)*1000/d; else printf "-" }') + fails=$(grep -c 'generation failed:' "$log" 2>/dev/null) + cerr=$(grep -c '"type":"error"\|turn.failed' "$out/codex-events.jsonl" 2>/dev/null) + cevents=$(wc -l < "$out/codex-events.jsonl" 2>/dev/null) + mem=$(awk 'END{print $3" MiB inference-rss, gpu "$8" MiB, avail "$9" MiB"}' <(grep -P '\tinference\t' "$out/env.tsv" 2>/dev/null | tail -1)) + echo "$(date -u +%T) elapsed=$(( $(date +%s) - t0 ))s requests=$n last_ctx=${ctx:-?} reused=${reused:-?} last_ttft=$(awk -v p="${pms:-0}" 'BEGIN{printf "%.2fs", p/1000}') last_decode=${rate}tok/s gen_failed=$fails codex_events=${cevents:-0} codex_errors=${cerr:-0} $mem" >>"$status" +done