From 856d538a83c91b05fe69ece2d140e4012ab6bed5 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 17 Oct 2026 15:45:13 +0200 Subject: [PATCH] wip: HTTP-layer 400 for context/output-cap errors, fake-engine tooling for the e2e client Co-Authored-By: Claude Sonnet 5.5 --- control-plane/src/responses.rs | 60 ++++++-- control-plane/tests/backend_worker_http.rs | 40 +++++- scripts/e2e/e2e_client.py | 2 +- scripts/e2e/fake_llm_engine.py | 158 +++++++++++++++++++++ scripts/e2e/render_results.py | 20 +++ scripts/e2e/run-fake.sh | 29 ++++ 6 files changed, 296 insertions(+), 13 deletions(-) create mode 100644 scripts/e2e/fake_llm_engine.py create mode 100644 scripts/e2e/render_results.py create mode 100644 scripts/e2e/run-fake.sh diff --git a/control-plane/src/responses.rs b/control-plane/src/responses.rs index aeeba520..f62ec1cf 100644 --- a/control-plane/src/responses.rs +++ b/control-plane/src/responses.rs @@ -1087,6 +1087,9 @@ pub async fn count_input_tokens( } } +/// 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 +1156,55 @@ pub async fn create( Ok(prepared) => prepared, Err(error) => return *error, }; - let (remaining, output_cap) = { + let (max_context, output_cap) = { 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)) }; + // 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 diff --git a/control-plane/tests/backend_worker_http.rs b/control-plane/tests/backend_worker_http.rs index 5f9d1c91..c28adcc0 100644 --- a/control-plane/tests/backend_worker_http.rs +++ b/control-plane/tests/backend_worker_http.rs @@ -1143,9 +1143,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!( @@ -1163,6 +1164,41 @@ async fn the_runtimes_output_cap_clamps_the_default_and_refuses_an_explicit_exce stack.finish().await; } +/// A prompt that cannot fit the context is the client's error: 400 `context_length_exceeded` from the HTTP layer +/// (found by the e2e run: it used to be a 502 `generation_failed` after queueing), and a default output budget leaves +/// the engine's 8-token margin so a prompt that just fits is served instead of refused. +#[tokio::test] +async fn a_prompt_that_cannot_fit_the_context_is_a_400_and_the_default_budget_keeps_the_margin() { + let stack = Stack::start_with("bw-context", |config| config.max_context = 600).await; + // explicit budget that does not fit + let (status, text) = stack + .post("/v1/responses", &body(json!({"max_output_tokens": 4000}))) + .await; + assert_eq!(status, 400, "{text}"); + assert!(text.contains("context_length_exceeded"), "{text}"); + // a prompt longer than the context + let long = "word ".repeat(2000); + let (status, text) = stack + .post("/v1/responses", &body(json!({"input": long}))) + .await; + assert_eq!(status, 400, "{text}"); + assert!(text.contains("context_length_exceeded"), "{text}"); + assert!(stack.engine.requests().is_empty(), "nothing reached the engine"); + // a request that fits, with the default budget: prompt + max_new + 8 == context at most + stack.engine.push(Script::stop_with(&["a"], usage(1, 1, 0))); + let (status, text) = stack.post("/v1/responses", &body(json!({}))).await; + assert_eq!(status, 200, "{text}"); + let seen = &stack.engine.requests()[0]; + let prompt_tokens = stack.tokenizer.encode(&seen.prompt, true).unwrap().len(); + assert!( + prompt_tokens + seen.max_output_tokens as usize + 8 <= 600, + "{} + {} + 8 > 600", + prompt_tokens, + seen.max_output_tokens + ); + stack.finish().await; +} + #[tokio::test] async fn every_sampling_control_reaches_the_engine_as_fixed_point() { let stack = Stack::start("bw-sampling").await; diff --git a/scripts/e2e/e2e_client.py b/scripts/e2e/e2e_client.py index 9cd09679..1500ee17 100644 --- a/scripts/e2e/e2e_client.py +++ b/scripts/e2e/e2e_client.py @@ -79,7 +79,7 @@ class Client: return res event, data = None, [] while True: - line = r.fp.readline() + line = r.readline() if not line: break now = time.monotonic() - t0 diff --git a/scripts/e2e/fake_llm_engine.py b/scripts/e2e/fake_llm_engine.py new file mode 100644 index 00000000..3a3efe18 --- /dev/null +++ b/scripts/e2e/fake_llm_engine.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""A scripted stand-in "model" for the e2e client: a stdio token engine for `fake_runtime` (TEST TOOLING ONLY, not shipped). + + fake_runtime ... --engine fake_llm_engine.py --engine-arg TOKENIZER_DIR --engine-arg STRATA_NEXT_BINARY + +It speaks the stdio wire protocol (`READY`, `GEN [k=v...] ids`, `T `, `DONE ...`, `STOP`, `QUIT`), decodes the prompt with +`strata-next model detokenize`, picks a canned reply from the last user turn and streams it token by token. It exists so the e2e +client and the API stack can be exercised without a GPU and so the client's own checks can be tested; it says nothing about the +real model. Prefix reuse is emulated as the common prefix with the previous prompt. +""" +import json +import re +import subprocess +import sys +import threading +import time + +TOK, BIN = sys.argv[2], sys.argv[3] # argv[1] is --serve +DELAY = 0.012 # seconds per token (cancel tests need a stream that lasts) + + +def run(*args): + return subprocess.run([BIN, "model", *args], capture_output=True, text=True, check=True).stdout.strip() + + +def detok(ids): + return json.loads(run("detokenize", TOK, ",".join(map(str, ids)))) + + +def tok(text): + return json.loads(run("tokenize", TOK, text, "--special")) + + +def last_user(prompt): + parts = prompt.split("<|im_start|>user\n") + return parts[-1].split("<|im_end|>")[0] if len(parts) > 1 else prompt + + +def reply(prompt, max_new): + u = last_user(prompt) + tools = "# Tools" in prompt + think_open = prompt.rstrip().endswith("") + pre = "I will answer directly.\n\n\n" if think_open else "" + if "" in u: + return pre + "The listing shows a Cargo.toml, a README.md and a src directory." + if tools and "shell tool" in u: + return pre + '\n\n\n["ls","-la"]\n\n\n' + if tools and "read_file tool" in u: + return pre + "\n\n\nsrc/main.rs\n\n\n1\n\n\n40\n\n\n" + if tools and "update_plan tool" in u: + plan = '[{"step":"inspect the code","status":"completed"},{"step":"fix the bug","status":"in_progress"},{"step":"run the tests","status":"pending"}]' + return pre + f"\n\n\n{plan}\n\n\n" + if tools and "Plan the work" in u: + return pre + '\n\n\n[{"step":"write tests","status":"in_progress"},{"step":"implement","status":"pending"}]\n\n\n' + if tools and "date" in u and "shell tool" in u: + return pre + '\n\n\n["date"]\n\n\n' + if "the quick brown fox jumps" in u: + return pre + "the quick brown fox jumps" + if "Count from 1 to 120" in u: + return pre + "\n".join(str(i) for i in range(1, 121)) + if "essay" in u: + return pre + ("Programming languages evolved from machine code to assemblers to compilers. " * 60) + if "BETA" in u: + return pre + "BETA" + if "GAMMA" in u: + return pre + "GAMMA" + if "name of my project" in u: + return pre + "Leleka" + if "what does it serve" in u.lower() or "And what does it" in u: + return pre + "A Qwen model on one GPU" + if "12 * 13" in u and "Now multiply" not in u: + return pre + "12 * 13 = 156\n\n\n156" if think_open else "156" + if "Now multiply" in u: + return pre + "312" + if "programming languages, comma" in u: + return pre + "Rust, C, Python, Go, Zig" + if "Summarize" in u or "Question:" in u: + return pre + "The worker lives in control-plane/src/backend_worker.rs in the strata-control crate." + return pre + "OK" + + +def main(): + print("READY 262144 stop", flush=True) + state = {"stop": False} + prev = [] + lines = [] + cond = threading.Condition() + + def reader(): + for line in sys.stdin: + line = line.strip() + if line == "STOP": + state["stop"] = True + else: + with cond: + lines.append(line) + cond.notify() + if line == "QUIT": + break + with cond: + lines.append("QUIT") + cond.notify() + threading.Thread(target=reader, daemon=True).start() + while True: + with cond: + while not lines: + cond.wait() + line = lines.pop(0) + if line == "QUIT": + return + if not line.startswith("GEN "): + print("ERR unexpected request", flush=True) + continue + state["stop"] = False + fields = line.split(" ") + max_new = int(fields[1]) + ids = [int(x) for x in fields[-1].split(",")] + print(f"fake-llm: GEN max_new={max_new} prompt_tokens={len(ids)}", file=sys.stderr, flush=True) + prompt = detok(ids) + text = reply(prompt, max_new) + out = tok(text) + print(f"fake-llm: reply {len(out)} tokens", file=sys.stderr, flush=True) + n = 0 + while n < len(prev) and n < len(ids) and prev[n] == ids[n]: + n += 1 + reused = max(0, n - 1) + prev = ids + t0 = time.monotonic() + # prefill takes time proportional to the non-reused prompt; emit progress for long ones + todo = len(ids) - reused + spent = 0 + while spent < todo and not state["stop"]: + step = min(2048, todo - spent) + time.sleep(0.0004 * step) + spent += step + print(f"PP {reused + spent} {len(ids)} 1 {1000 * (time.monotonic() - t0):.1f}", flush=True) + print(f"REUSED {reused}", flush=True) + t1 = time.monotonic() + produced = 0 + finish = "stop" + if state["stop"]: + finish = "cancel" + else: + for t in out: + if state["stop"]: + finish = "cancel" + break + if produced >= max_new: + finish = "length" + break + print(f"T {t}", flush=True) + produced += 1 + time.sleep(DELAY) + print(f"DONE {produced} {len(ids)} {1000 * (t1 - t0):.1f} {1000 * (time.monotonic() - t1):.1f} {finish} 0 0 {reused} 0 0", flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/e2e/render_results.py b/scripts/e2e/render_results.py new file mode 100644 index 00000000..00d7a351 --- /dev/null +++ b/scripts/e2e/render_results.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +"""Summarize an e2e results.json as text (offline helper for docs/e2e-run.md; not shipped).""" +import json +import sys + +d = json.load(open(sys.argv[1])) +for s in d["scenarios"]: + n = len(s["checks"]) + bad = [c for c in s["checks"] if not c["ok"]] + print(f"## {s['name']}: {n - len(bad)}/{n} checks passed, {s['seconds']}s" + (" ERROR" if s["error"] else "")) + for c in bad: + print(f" FAIL {c['name']} :: {c['detail'][:200]}") + if s["error"]: + print(" ERROR " + s["error"][-600:]) + for k, v in s["metrics"].items(): + if k in ("env_after", "server_metrics_after", "soak_samples"): + continue + print(f" {k} = {json.dumps(v)[:240]}") + for note in s["notes"]: + print(f" note: {note[:240]}") diff --git a/scripts/e2e/run-fake.sh b/scripts/e2e/run-fake.sh new file mode 100644 index 00000000..8e375e2c --- /dev/null +++ b/scripts/e2e/run-fake.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Run e2e_client.py against strata-next in front of a scripted fake engine (no GPU, no model): TEST TOOLING for the client itself. +# run-fake.sh STRATA_NEXT FAKE_RUNTIME TOKENIZER_DIR OUT_DIR [client args...] +# fake_runtime = `cargo build --release -p strata-desktop-core --example fake_runtime`; its engine is fake_llm_engine.py. +set -uo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +SN=$1 FAKE=$2 TOK=$3 OUT=$4; shift 4 +mkdir -p "$OUT"; chmod 700 "$OUT"; umask 077 +export FAKE_RUNTIME_TOKEN="fixture-runtime-credential-$(head -c 12 /dev/urandom | base64 | tr -d '/+=\n')" +KEY="$OUT/api-key"; rm -f "$KEY"; "$SN" api-key init --file "$KEY" >/dev/null || { echo "api-key init failed"; exit 4; } +chmod +x "$HERE/fake_llm_engine.py" +( sleep 3600 | "$FAKE" --listen 127.0.0.1:0 --token-env FAKE_RUNTIME_TOKEN --engine "$HERE/fake_llm_engine.py" --tokenizer "$TOK" \ + --engine-arg "$TOK" --engine-arg "$SN" >"$OUT/fake_runtime.out" 2>"$OUT/fake_runtime.err" ) & +for _ in $(seq 1 100); do grep -q LISTENING "$OUT/fake_runtime.out" 2>/dev/null && break; sleep 0.1; done +ADDR=$(awk '/LISTENING/{print $2}' "$OUT/fake_runtime.out") +[ -n "$ADDR" ] || { echo "fake runtime did not start"; cat "$OUT/fake_runtime.err"; exit 4; } +cat >"$OUT/strata.json" <"$OUT/strata-next.log" 2>&1 & +SPID=$! +trap 'kill -INT $SPID 2>/dev/null; pkill -P $$ 2>/dev/null; sleep 1; pkill -f fake_runtime 2>/dev/null; true' EXIT +"$SN" wait-ready --url http://127.0.0.1:18081 --model qwen-iq3 --key-file "$KEY" --timeout-s 60 >"$OUT/wait-ready.log" 2>&1 || { echo "not ready"; cat "$OUT/wait-ready.log"; tail "$OUT/strata-next.log"; exit 6; } +[ -n "${E2E_FAKE_HOLD:-}" ] && { echo "holding the stack for $E2E_FAKE_HOLD s (manual debugging)"; sleep "$E2E_FAKE_HOLD"; exit 0; } +python3 -I "$HERE/e2e_client.py" --base http://127.0.0.1:18081 --key-file "$KEY" --model qwen-iq3 --out "$OUT/results.json" \ + --context-dir "${E2E_CONTEXT:-$HERE/../../control-plane/src}" --pids "strata=$SPID" "$@"