Merge branch 'claude/e2e' into claude/port-gpu-bringup

This commit is contained in:
Pavlo Ratushnyi
2026-10-18 04:38:38 +02:00
40 changed files with 3329 additions and 71 deletions
+1 -1
View File
@@ -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
}
}
+7
View File
@@ -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();
+121 -11
View File
@@ -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<bool> = 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});
+1 -1
View File
@@ -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<f64>, default: f64) -> Result<Duration, String> {
let value = value.unwrap_or(default);
+8 -3
View File
@@ -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`.
+23
View File
@@ -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<u32>,
/// 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<WorkerStatus>,
) -> 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) => {
+42 -6
View File
@@ -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;
+7
View File
@@ -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.
+140
View File
@@ -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<String>,
order: VecDeque<String>,
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"));
}
}
+1 -1
View File
@@ -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,
}
})
}
+10 -11
View File
@@ -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<Command>,
shared: Arc<Shared>,
seen: HashSet<String>,
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"))]
@@ -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<Item = i64>| ids.map(|t| t.to_string()).collect::<Vec<_>>().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<T: std::fmt::Display>(v: Option<T>) -> 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<String> = 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<GenerationFailure> = None;
let mut timed_out = false;
let mut generated_ids: Vec<i32> = 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,
@@ -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): `<test binary> --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<PathBuf> = 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<PathBuf> = 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::<u64>().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<i32> { 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<std::time::Duration> = None;
let mut out: Vec<i32> = 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");
}
+25 -21
View File
@@ -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<api::LoadedModel>,
capabilities: api::BackendCapabilities,
operations: HashMap<String, Operation>,
requests: HashSet<String>,
requests: api::RecentIds,
lifecycle_busy: bool,
active: Option<String>,
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(),
+5 -10
View File
@@ -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;
}
+4 -3
View File
@@ -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
+191
View File
@@ -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: <client-visible message>` 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):
* `<function=shell>` with `<command>["ls"]</command>` instead of `<parameter=command>` -> `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`.
+2 -3
View File
@@ -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
+298
View File
@@ -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")
+77
View File
@@ -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);
+114
View File
@@ -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]}")
+23
View File
@@ -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
+119
View File
@@ -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)
@@ -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
@@ -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
@@ -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
+21
View File
@@ -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/<run>/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
+57
View File
@@ -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()
+25
View File
@@ -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/<r> lists all records (supports ?q=text, a case-insensitive substring filter on the name/title/email fields, and for deals also ?stage=<stage>); POST /api/<r> creates and returns 201 with the record including its integer id; GET /api/<r>/{id}; PUT /api/<r>/{id} replaces the editable fields and returns 200 with the record; DELETE /api/<r>/{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.
+10
View File
@@ -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.
+60
View File
@@ -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")" </dev/null 2>"$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"
+20
View File
@@ -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()
+12
View File
@@ -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 <out>.lct/ and <out>.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"
File diff suppressed because it is too large Load Diff
+158
View File
@@ -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 <max> [k=v...] ids`, `T <id>`, `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("<think>")
pre = "I will answer directly.\n</think>\n\n" if think_open else ""
if "<tool_response>" 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 + '<tool_call>\n<function=shell>\n<parameter=command>\n["ls","-la"]\n</parameter>\n</function>\n</tool_call>'
if tools and "read_file tool" in u:
return pre + "<tool_call>\n<function=read_file>\n<parameter=path>\nsrc/main.rs\n</parameter>\n<parameter=start_line>\n1\n</parameter>\n<parameter=end_line>\n40\n</parameter>\n</function>\n</tool_call>"
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"<tool_call>\n<function=update_plan>\n<parameter=plan>\n{plan}\n</parameter>\n</function>\n</tool_call>"
if tools and "Plan the work" in u:
return pre + '<tool_call>\n<function=update_plan>\n<parameter=plan>\n[{"step":"write tests","status":"in_progress"},{"step":"implement","status":"pending"}]\n</parameter>\n</function>\n</tool_call>'
if tools and "date" in u and "shell tool" in u:
return pre + '<tool_call>\n<function=shell>\n<parameter=command>\n["date"]\n</parameter>\n</function>\n</tool_call>'
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</think>\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()
+20
View File
@@ -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]}")
+191
View File
@@ -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/<utc>)
# 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" <<EOF
{"schema_version":1,"listen":"127.0.0.1:18080","token_env":"LELEKA_GATEWAY_TOKEN",
"runtimes":[{"id":"qwen-iq3","address":"127.0.0.1:18766","token_env":"LELEKA_RUNTIME_TOKEN",
"artifact_digest":"sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"}]}
EOF
TOK=$STATE/tokenizer-assets
cat >"$STATE/strata.json" <<EOF
{"bind":"127.0.0.1:8081","api_key_file":"$KEYFILE","model":"qwen-iq3","shutdown_grace_s":10,
"runtime":{"address":"127.0.0.1:18766","token_env":"LELEKA_RUNTIME_TOKEN","tokenizer_dir":"$TOK/tokenizer",
"model":{"family":"qwen4exp","architecture":"qwen4exp","weight_format":"gguf:iq3_s",
"artifact_digest":"sha256:80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3"},
"mode":{"type":"mtp","profile_id":"qwen4exp-kar-ple-mtp-v1"},"max_context":262144,"max_output_tokens":32768}}
EOF
PID_INF= PID_DAE= PID_STR=
alive() { [ -n "$1" ] && kill -0 "$1" 2>/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"
+29
View File
@@ -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" <<JSON
{"bind":"127.0.0.1:18081","api_key_file":"$KEY","model":"qwen-iq3","shutdown_grace_s":0,
"runtime":{"address":"$ADDR","token_env":"FAKE_RUNTIME_TOKEN","tokenizer_dir":"$TOK",
"model":{"family":"fixture_family","architecture":"fixture_arch","weight_format":"fixture:stdio","artifact_digest":"sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"},
"mode":{"type":"native"},"max_context":262144,"max_output_tokens":32768,"attach_retry_s":0.1,"health_interval_s":0.5}}
JSON
"$SN" serve --config "$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" "$@"
+17
View File
@@ -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
+22
View File
@@ -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