Files
leleka/control-plane/tests/memory_gate_http/harness.rs
T
Pavlo Ratushnyi 7610ba3568 STRA-338 size-gw: the 19 oversize files of control-plane and desktop-core split by topic (no file over 400 lines); mechanical child modules renamed
Tests become directory modules named after what they test, with a shared fixtures/harness module:
control-plane/src/{responses,ggml_bridge,gguf_f32_stream,prepare_preview}/tests/, desktop-core/src/runtime_rpc/tests/;
integration targets become tests/<name>/main.rs plus topic modules and a harness (backend_worker_http, vision_http,
memory_gate_http, tool_corpus, mcp_hub, api_over_runtime, runtime_gateway_sdet, native_tools_sdet,
native_tools_retry_sdet, managed_worker, gateway); target names are unchanged. Sources: leleka-inference.rs becomes
src/bin/leleka-inference/ (main.rs plus one module per operator option group), the cp_replay example becomes
examples/cp_replay/, and the tonic service impl of runtime_rpc delegates to session_rpc, model_rpc and generate_rpc
(bodies unchanged). impl_* modules are renamed after what they hold (base_provenance, count_tokens, manifest_fetch,
fetcher, record, capture, in_flight, tool_policy, tool_plan, server). The self-spawning tests that name themselves
(credential_child, the managed worker fixture) use the new module path or stay at the target root.

Test ids: 543 before and after in both crates (strata-control, strata-desktop-core, --all-targets), 0 missing, 0 new,
0 outcome changes; 241 ids differ only in the module path. Warnings in the two crates: 0 before and after.
Counts (strata-control / strata-desktop-core): oversize files 19 -> 0 (13 + 6). Functions over 30 lines, complexity 10,
nesting 4, wide lines, prod: 187/135/17/199 -> 187/135/17/196 and 81/59/6/54 -> 81/59/6/54; test: 214/17/30/133 ->
214/17/30/133 and 65/3/3/30 -> 65/3/3/27. The 211 functions that moved verbatim are in limits-allowlist.json (owner
STRA-338) because the diff gate treats a moved function as added; the entries fall as the functions are shortened.
2026-11-06 13:13:59 +01:00

158 lines
5.6 KiB
Rust

//! The engine stack, reports and request builders of the memory gate tests.
use crate::common;
use leleka_backend_api::scripted::{ScriptedEngine, ScriptedHandle};
use leleka_backend_api::{InferenceMode, RuntimeConfig, Usage};
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
use strata_control::app::{AppState, EngineLink, ModelView, router};
use strata_control::backend_worker::{BackendWorkerConfig, run_backend_worker};
use strata_control::memory_view::MemoryView;
use strata_control::worker::{WorkerState, WorkerStatus};
use tokio::sync::{RwLock, mpsc, watch};
pub(super) struct Stack {
pub(super) base: String,
pub(super) client: reqwest::Client,
pub(super) engine: ScriptedHandle,
pub(super) memory: Arc<MemoryView>,
pub(super) status: Arc<RwLock<WorkerStatus>>,
pub(super) stop: watch::Sender<bool>,
pub(super) worker: tokio::task::JoinHandle<()>,
pub(super) server: tokio::task::JoinHandle<()>,
}
pub(super) 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 {
pub(super) 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 {
engine: EngineLink {
worker: status.clone(),
client: Some(strata_control::adapters::ChannelEngine::shared(requests)),
control: Some(control),
..Default::default()
},
model: ModelView {
name: Some("fixture".into()),
tokenizer: Some(Arc::new(strata_control::codec::qwen_codec_shared(
tokenizer.clone(),
))),
memory: memory.clone(),
..Default::default()
},
..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.
pub(super) 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");
}
pub(super) 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()
}
pub(super) async fn finish(self) {
let _ = self.stop.send(true);
let _ = tokio::time::timeout(Duration::from_secs(10), self.worker).await;
self.server.abort();
}
}
pub(super) fn usage() -> Usage {
Usage {
input_tokens: 3,
output_tokens: 1,
reused_input_tokens: 0,
}
}
pub(super) fn request(stream: bool) -> Value {
json!({"model": "fixture", "input": "hi", "stream": stream, "reasoning": {"effort": "none"}})
}