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

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

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

465 lines
17 KiB
Rust

//! The memory gate in front of the engine and a model-free soak of it: real axum router, real worker adapter, a scripted
//! engine whose memory-governor report the test controls. No GPU, no model, no child process.
//!
//! * a `reject` report closes the gate: `503 memory_pressure` with `Retry-After`, before the request reaches the engine;
//! * `shed` still serves; a stale report never blocks; an engine-side refusal text maps to the same 503;
//! * the soak: hundreds of mixed requests (buffered, streamed, abandoned by the client, refused by the gate) while the
//! pressure level flips; threads, file descriptors and RSS must stay flat after warm-up and the engine must end idle.
use std::{sync::Arc, time::Duration};
use leleka_backend_api::{
ErrorCode, InferenceMode, RuntimeConfig, Usage,
scripted::{Script, ScriptedEngine, ScriptedHandle},
};
use leleka_memory::{
RealProc,
census::{Census, Tolerances, check_flat},
};
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
backend_worker::{BackendWorkerConfig, run_backend_worker},
memory_view::MemoryView,
worker::{WorkerState, WorkerStatus},
};
use tokio::sync::{RwLock, mpsc, watch};
mod common;
struct Stack {
base: String,
client: reqwest::Client,
engine: ScriptedHandle,
memory: Arc<MemoryView>,
status: Arc<RwLock<WorkerStatus>>,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
}
fn report(level: &str, retry_after: u64) -> String {
json!({
"version": 1,
"gate": {"level": level, "retry_after_secs": retry_after, "reason": "available 1024 MiB below the hard floor 2048 MiB", "available_bytes": 1u64 << 30},
"counters": {"admitted": 0},
})
.to_string()
}
impl Stack {
async fn start(name: &str) -> Self {
let dir = common::scratch(name);
let tokenizer = common::tokenizer(&dir);
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
let memory = Arc::new(MemoryView::default());
let config = BackendWorkerConfig {
tokenizer: tokenizer.clone(),
model: ScriptedEngine::fixture_descriptor(),
runtime: RuntimeConfig {
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
inference_mode: InferenceMode::Native,
gpu_memory_limit_bytes: None,
allow_experimental: false,
},
max_context: 262_144,
max_output_tokens: 4096,
health_interval: Duration::from_millis(10),
generation_timeout: None,
stall_timeout: None,
attach_retry: Duration::from_millis(20),
cancel_drain_timeout: Duration::from_secs(5),
prefix_view: None,
memory_view: Some(memory.clone()),
};
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(8);
let (control, control_rx) = mpsc::channel(8);
let worker = tokio::spawn(run_backend_worker(
Box::new(engine),
config,
status.clone(),
stop_rx,
requests_rx,
control_rx,
));
let state = AppState {
model: Some("fixture".into()),
worker: status.clone(),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
generation: Some(requests),
control: Some(control),
memory: memory.clone(),
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state);
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
let stack = Self {
base,
client: reqwest::Client::new(),
engine: handle,
memory,
status,
stop,
worker,
server,
};
tokio::time::timeout(Duration::from_secs(10), async {
while stack.status.read().await.state != WorkerState::Ready {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("worker never became ready");
stack
}
/// Publish a report as the engine would and wait until the control plane has copied it.
async fn set_level(&self, level: &str) {
self.engine.set_memory_report(Some(report(level, 7)));
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if self.memory.status()["gate"]["level"] == level {
return;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the worker never copied the report");
}
async fn post(&self, body: &Value) -> reqwest::Response {
self.client
.post(format!("{}/v1/responses", self.base))
.header("content-type", "application/json")
.body(body.to_string())
.send()
.await
.unwrap()
}
async fn finish(self) {
let _ = self.stop.send(true);
let _ = tokio::time::timeout(Duration::from_secs(10), self.worker).await;
self.server.abort();
}
}
fn usage() -> Usage {
Usage {
input_tokens: 3,
output_tokens: 1,
reused_input_tokens: 0,
}
}
fn request(stream: bool) -> Value {
json!({"model": "fixture", "input": "hi", "stream": stream, "reasoning": {"effort": "none"}})
}
#[tokio::test]
async fn a_reject_report_closes_the_gate_with_503_and_retry_after_and_shed_still_serves() {
let stack = Stack::start("mg-gate").await;
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(stack.post(&request(false)).await.status(), 200);
stack.set_level("reject").await;
let refused = stack.post(&request(false)).await;
assert_eq!(refused.status(), 503);
assert_eq!(refused.headers().get("retry-after").unwrap(), "7");
let body: Value = serde_json::from_str(&refused.text().await.unwrap()).unwrap();
assert_eq!(body["error"]["code"], "memory_pressure", "{body}");
assert!(
body["error"]["message"]
.as_str()
.unwrap()
.contains("hard floor")
);
// the Chat Completions and Messages dialects get the same 503 with the same Retry-After
for (path, body) in [
(
"/v1/chat/completions",
json!({"model": "fixture", "messages": [{"role": "user", "content": "hi"}]}),
),
(
"/v1/chat/completions",
json!({"model": "fixture", "stream": true, "messages": [{"role": "user", "content": "hi"}]}),
),
(
"/v1/messages",
json!({"model": "fixture", "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}),
),
] {
let r = stack
.client
.post(format!("{}{path}", stack.base))
.header("content-type", "application/json")
.header("anthropic-version", "2023-06-01")
.body(body.to_string())
.send()
.await
.unwrap();
let status = r.status();
let retry = r
.headers()
.get("retry-after")
.map(|v| v.to_str().unwrap().to_owned());
let text = r.text().await.unwrap_or_default();
assert_eq!(status, 503, "{path}: {text}");
assert_eq!(
retry.as_deref(),
Some("7"),
"{path} keeps Retry-After: {text}"
);
}
// streaming requests are refused up front too: a proper 503, not a 200 SSE that fails inside
let refused = stack.post(&request(true)).await;
assert_eq!(refused.status(), 503);
assert_eq!(
stack.engine.requests().len(),
1,
"a refused request never reaches the engine"
);
stack.set_level("shed").await;
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(
stack.post(&request(false)).await.status(),
200,
"shedding still serves"
);
stack.set_level("normal").await;
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(stack.post(&request(false)).await.status(), 200);
let status: Value = serde_json::from_str(
&stack
.client
.get(format!("{}/v1/status", stack.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap(),
)
.unwrap();
assert_eq!(status["memory"]["gate"]["level"], "normal");
assert_eq!(status["memory"]["gate_rejections"], 5);
let metrics: Value = serde_json::from_str(
&stack
.client
.get(format!("{}/metrics", stack.base))
.send()
.await
.unwrap()
.text()
.await
.unwrap(),
)
.unwrap();
assert_eq!(metrics["memory"]["gate_rejections"], 5);
stack.finish().await;
}
#[tokio::test]
async fn an_engine_side_refusal_is_the_same_503_with_the_engines_retry_after() {
let stack = Stack::start("mg-engine-refusal").await;
stack.engine.push(Script::failing_after(&[], ErrorCode::ResourceExhausted, "memory_pressure: retry_after=9: 1.5 GiB available is within 0.25 GiB of the hard floor 2 GiB"));
let refused = stack.post(&request(false)).await;
let status = refused.status();
let retry = refused
.headers()
.get("retry-after")
.map(|v| v.to_str().unwrap().to_owned());
let text = refused.text().await.unwrap();
assert_eq!(status, 503, "{text}");
assert_eq!(retry.as_deref(), Some("9"), "{text}");
// and the worker is still fine afterwards
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(stack.post(&request(false)).await.status(), 200);
stack.finish().await;
}
#[tokio::test]
async fn reconfigure_reaches_the_engine_and_answers_with_the_effective_settings_or_the_refusal() {
let stack = Stack::start("mg-reconf").await;
let post = |body: &str| {
stack
.client
.post(format!("{}/v1/reconfigure", stack.base))
.header("content-type", "application/json")
.body(body.to_owned())
.send()
};
let ok = post(r#"{"context_tokens":65536}"#).await.unwrap();
assert_eq!(ok.status(), 200);
let body: Value = serde_json::from_str(&ok.text().await.unwrap()).unwrap();
assert_eq!(body["status"], "reconfigured");
assert_eq!(body["settings"]["context_tokens"], 65536);
let body: Value = serde_json::from_str(
&post(r#"{"prefix_cache_tail":"reply"}"#)
.await
.unwrap()
.text()
.await
.unwrap(),
)
.unwrap();
assert_eq!(body["settings"]["prefix_cache_tail"], "reply");
// a refusal carries the engine's message and leaves the settings alone
let refused = post(r#"{"bad":1}"#).await.unwrap();
assert_eq!(refused.status(), 400);
assert!(refused.text().await.unwrap().contains("bad setting"));
assert_eq!(post("[1]").await.unwrap().status(), 400);
assert_eq!(post("not json").await.unwrap().status(), 400);
// the engine keeps serving afterwards
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(stack.post(&request(false)).await.status(), 200);
stack.finish().await;
}
#[tokio::test]
async fn a_stale_or_garbage_report_never_blocks_traffic() {
let stack = Stack::start("mg-stale").await;
stack.engine.set_memory_report(Some("{not json".into()));
tokio::time::sleep(Duration::from_millis(80)).await;
stack.engine.push(Script::stop_with(&["ok"], usage()));
assert_eq!(stack.post(&request(false)).await.status(), 200);
stack.finish().await;
}
/// Deterministic mix without a random-number dependency.
fn pick(i: u64) -> u64 {
i.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407)
>> 33
}
#[tokio::test]
async fn soak_mixed_requests_with_pressure_flips_keep_threads_descriptors_and_memory_flat() {
let stack = Stack::start("mg-soak").await;
let total = 600u64;
let warmup = 20usize;
let mut series: Vec<Census> = Vec::new();
let (mut served, mut refused, mut abandoned, mut failed) = (0u64, 0u64, 0u64, 0u64);
for i in 0..total {
// the pressure level flips: reject for 12 of every 60 requests, shed for 12 more
let phase = i % 60;
let level = if phase >= 48 {
"reject"
} else if phase >= 36 {
"shed"
} else {
"normal"
};
if phase == 0 || phase == 36 || phase == 48 {
stack.set_level(level).await;
}
if level == "reject" {
// every kind of request is refused up front and never reaches the engine
let r = stack.post(&request(pick(i).is_multiple_of(2))).await;
assert_eq!(r.status().as_u16(), 503, "request {i}");
assert!(r.headers().get("retry-after").is_some());
let _ = r.bytes().await.unwrap();
refused += 1;
} else {
match pick(i) % 5 {
0 | 1 => {
stack
.engine
.push(Script::stop_with(&["ok ", "done"], usage()));
let r = stack.post(&request(false)).await;
assert_eq!(r.status().as_u16(), 200, "request {i}");
let _ = r.bytes().await.unwrap();
served += 1;
}
2 => {
stack
.engine
.push(Script::stop_with(&["ok ", "done"], usage()));
let r = stack.post(&request(true)).await;
assert_eq!(r.status().as_u16(), 200, "request {i}");
let text = r.text().await.unwrap();
assert!(text.contains("response.completed"), "request {i}: {text}");
served += 1;
}
3 => {
// the client walks away mid-stream
stack.engine.push(Script::hanging_after(&["start"]));
let mut r = stack.post(&request(true)).await;
assert_eq!(r.status().as_u16(), 200, "request {i}");
let mut seen = String::new();
while !seen.contains("response.output_text.delta") {
match tokio::time::timeout(Duration::from_secs(10), r.chunk())
.await
.unwrap()
.unwrap()
{
Some(chunk) => seen.push_str(&String::from_utf8_lossy(&chunk)),
None => break,
}
}
drop(r);
tokio::time::timeout(Duration::from_secs(10), async {
while stack.engine.is_generating() {
tokio::time::sleep(Duration::from_millis(2)).await;
}
})
.await
.expect("an abandoned stream was never cancelled in the engine");
abandoned += 1;
}
_ => {
// an engine-side failure: the request ends as a failure, the worker lives on
stack.engine.push(Script::failing_after(
&["a"],
ErrorCode::Internal,
"scripted failure",
));
let r = stack.post(&request(false)).await;
let status = r.status().as_u16();
assert!(status == 502 || status == 503, "request {i}: {status}");
let _ = r.bytes().await.unwrap();
failed += 1;
}
}
}
if i % 5 == 4 {
series.push(Census::take(&RealProc));
}
}
// drain: the engine ends idle, nothing queued
tokio::time::timeout(Duration::from_secs(10), async {
while stack.engine.is_generating() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("the engine never went idle");
let tolerances = Tolerances {
rss: 96 << 20,
threads: 3,
fds: 6,
..Tolerances::default()
};
let flat = check_flat(&series, warmup, &tolerances);
eprintln!(
"soak: served={served} refused={refused} abandoned={abandoned} failed={failed}\n{flat}"
);
assert!(
served > 100 && refused > 20 && abandoned > 20,
"the mix did not exercise every path"
);
assert!(flat.ok, "{flat}");
stack.finish().await;
}