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
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>
622 lines
22 KiB
Rust
622 lines
22 KiB
Rust
//! The complete chain without a GPU: HTTP client -> `strata-next` router -> `backend_worker` ->
|
|
//! `GrpcBackend` -> real HTTP/2 gRPC -> the real `RuntimeServer` -> a scripted engine behind the
|
|
//! `Backend` contract. Everything but the engine is the production code path of the Rust runtime
|
|
//! stack, so this is the closest thing to `leleka-inference` that runs in `cargo test`.
|
|
//!
|
|
//! The engine's output is scripted; nothing here says anything about a model.
|
|
|
|
use std::{
|
|
net::SocketAddr,
|
|
sync::Arc,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use leleka_backend_api::{
|
|
FinishReason, InferenceMode, RuntimeConfig, Usage,
|
|
scripted::{Script, ScriptedEngine, ScriptedHandle},
|
|
};
|
|
use leleka_runtime_client::{
|
|
client::RuntimeClient,
|
|
convert::{config_to_proto, descriptor_to_proto},
|
|
proto,
|
|
};
|
|
use serde_json::{Value, json};
|
|
use strata_control::{
|
|
app::{AppState, router},
|
|
backend_worker::{BackendWorkerConfig, run_backend_worker},
|
|
tokenizer::Tokenizer,
|
|
worker::{WorkerState, WorkerStatus},
|
|
};
|
|
use strata_desktop_core::runtime_rpc::RuntimeServer;
|
|
use tokio::sync::{RwLock, mpsc, watch};
|
|
|
|
const TOKEN: &str = "synthetic-api-over-runtime-token-0000";
|
|
const SPECIALS: [&str; 7] = [
|
|
"<|im_start|>",
|
|
"<|im_end|>",
|
|
"<think>",
|
|
"</think>",
|
|
"<|vision_start|>",
|
|
"<|image_pad|>",
|
|
"<|vision_end|>",
|
|
];
|
|
|
|
fn tokenizer(name: &str) -> Arc<Tokenizer> {
|
|
let root = std::env::temp_dir().join(format!("api-over-runtime-{}-{name}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
std::fs::create_dir_all(&root).unwrap();
|
|
let mut vocabulary = serde_json::Map::new();
|
|
for (id, ch) in strata_control::tokenizer::byte_alphabet()
|
|
.0
|
|
.iter()
|
|
.enumerate()
|
|
{
|
|
vocabulary.insert(ch.to_string(), json!(id));
|
|
}
|
|
for (offset, token) in SPECIALS.iter().enumerate() {
|
|
vocabulary.insert((*token).into(), json!(256 + offset));
|
|
}
|
|
let total = 256 + SPECIALS.len();
|
|
std::fs::write(
|
|
root.join("vocab.json"),
|
|
serde_json::to_vec(&vocabulary).unwrap(),
|
|
)
|
|
.unwrap();
|
|
std::fs::write(root.join("merges.txt"), "").unwrap();
|
|
let mut types = vec![1u8; total];
|
|
types[256..].fill(3);
|
|
std::fs::write(
|
|
root.join("token_type.json"),
|
|
serde_json::to_vec(&types).unwrap(),
|
|
)
|
|
.unwrap();
|
|
std::fs::write(
|
|
root.join("tokenizer.json"),
|
|
serde_json::to_vec(&json!({
|
|
"model": "gpt2", "pre": "qwen35", "vocab_size": total, "n_merges": 0,
|
|
"pre_pattern": leleka_tokenizer_pattern(),
|
|
"special_ids": {"tokenizer.ggml.eos_token_id": 257}
|
|
}))
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
Arc::new(Tokenizer::from_assets(&root).unwrap())
|
|
}
|
|
|
|
fn leleka_tokenizer_pattern() -> &'static str {
|
|
strata_control::tokenizer::QWEN35_PATTERN
|
|
}
|
|
|
|
fn runtime_config() -> RuntimeConfig {
|
|
RuntimeConfig {
|
|
load_config_version: leleka_backend_api::LOAD_CONFIG_VERSION,
|
|
inference_mode: InferenceMode::Native,
|
|
gpu_memory_limit_bytes: None,
|
|
allow_experimental: false,
|
|
}
|
|
}
|
|
|
|
/// A `RuntimeServer` over a scripted engine, listening on `address` (or a free port).
|
|
struct Runtime {
|
|
address: SocketAddr,
|
|
engine: ScriptedHandle,
|
|
stop: Option<tokio::sync::oneshot::Sender<()>>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
|
|
impl Runtime {
|
|
async fn start(address: Option<SocketAddr>) -> Self {
|
|
let (engine, handle) = ScriptedEngine::new(ScriptedEngine::fixture_descriptor());
|
|
let server = RuntimeServer::new(Box::new(engine), TOKEN.into()).unwrap();
|
|
let listener =
|
|
tokio::net::TcpListener::bind(address.unwrap_or("127.0.0.1:0".parse().unwrap()))
|
|
.await
|
|
.unwrap();
|
|
let address = listener.local_addr().unwrap();
|
|
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
|
|
let task = tokio::spawn(async move {
|
|
let _ = server
|
|
.serve(listener, async {
|
|
let _ = stopped.await;
|
|
})
|
|
.await;
|
|
});
|
|
Self {
|
|
address,
|
|
engine: handle,
|
|
stop: Some(stop),
|
|
task,
|
|
}
|
|
}
|
|
|
|
/// What `leleka-cli load` does: one Load RPC for the current epoch, then wait for readiness.
|
|
async fn operator_loads_the_model(&self) {
|
|
let mut client = RuntimeClient::connect(self.address, TOKEN.into())
|
|
.await
|
|
.unwrap();
|
|
let epoch = client.snapshot().await.unwrap().epoch;
|
|
let operation = uuid::Uuid::new_v4().to_string();
|
|
client
|
|
.load(proto::LoadRequest {
|
|
operation_id: operation.clone(),
|
|
expected_epoch: epoch,
|
|
model: Some(descriptor_to_proto(&ScriptedEngine::fixture_descriptor())),
|
|
config: Some(config_to_proto(&runtime_config())),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let deadline = Instant::now() + Duration::from_secs(10);
|
|
while !client.snapshot().await.unwrap().model_ready {
|
|
assert!(Instant::now() < deadline, "the runtime never became ready");
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
}
|
|
|
|
async fn stop(mut self) {
|
|
let _ = self.stop.take().unwrap().send(());
|
|
let _ = tokio::time::timeout(Duration::from_secs(5), &mut self.task).await;
|
|
}
|
|
}
|
|
|
|
struct Stack {
|
|
base: String,
|
|
client: reqwest::Client,
|
|
status: Arc<RwLock<WorkerStatus>>,
|
|
stop: watch::Sender<bool>,
|
|
worker: tokio::task::JoinHandle<()>,
|
|
server: tokio::task::JoinHandle<()>,
|
|
}
|
|
|
|
impl Stack {
|
|
async fn start(name: &str, address: SocketAddr) -> Self {
|
|
let tokenizer = tokenizer(name);
|
|
let prefix_view = Arc::new(strata_control::prefix_view::PrefixView::default());
|
|
let config = BackendWorkerConfig {
|
|
tokenizer: tokenizer.clone(),
|
|
model: ScriptedEngine::fixture_descriptor(),
|
|
runtime: runtime_config(),
|
|
max_context: 262_144,
|
|
max_output_tokens: 4096,
|
|
generation_timeout: None,
|
|
stall_timeout: None,
|
|
attach_retry: Duration::from_millis(50),
|
|
health_interval: Duration::from_millis(50),
|
|
cancel_drain_timeout: Duration::from_secs(5),
|
|
prefix_view: Some(prefix_view.clone()),
|
|
memory_view: None,
|
|
};
|
|
let backend = leleka_runtime_client::backend::GrpcBackend::new(
|
|
tokio::runtime::Handle::current(),
|
|
address,
|
|
TOKEN.into(),
|
|
);
|
|
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(backend),
|
|
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),
|
|
prefix_cache: prefix_view,
|
|
..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;
|
|
});
|
|
Self {
|
|
base,
|
|
client: reqwest::Client::new(),
|
|
status,
|
|
stop,
|
|
worker,
|
|
server,
|
|
}
|
|
}
|
|
|
|
async fn wait_state(&self, wanted: WorkerState) {
|
|
tokio::time::timeout(Duration::from_secs(20), async {
|
|
while self.status.read().await.state != wanted {
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap_or_else(|_| panic!("worker never reached {wanted:?}"));
|
|
}
|
|
|
|
async fn post(&self, path: &str, body: &Value) -> (u16, String) {
|
|
let response = self
|
|
.client
|
|
.post(format!("{}{path}", self.base))
|
|
.header("content-type", "application/json")
|
|
.body(body.to_string())
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
(response.status().as_u16(), response.text().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 sse_events(body: &str) -> Vec<Value> {
|
|
body.split("\n\n")
|
|
.filter(|frame| !frame.trim().is_empty() && !frame.starts_with(':'))
|
|
.filter_map(|frame| {
|
|
let data = frame
|
|
.lines()
|
|
.filter_map(|line| line.strip_prefix("data:"))
|
|
.map(str::trim_start)
|
|
.collect::<Vec<_>>()
|
|
.join("\n");
|
|
(data != "[DONE]").then(|| serde_json::from_str(&data).unwrap())
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn body(extra: Value) -> Value {
|
|
let mut value = json!({"model": "fixture", "input": "hi", "reasoning": {"effort": "none"}});
|
|
for (key, item) in extra.as_object().unwrap() {
|
|
value[key] = item.clone();
|
|
}
|
|
value
|
|
}
|
|
|
|
fn usage(input: u64, output: u64) -> Usage {
|
|
Usage {
|
|
input_tokens: input,
|
|
output_tokens: output,
|
|
reused_input_tokens: 0,
|
|
}
|
|
}
|
|
|
|
fn assert_one_terminal(events: &[Value]) {
|
|
for (index, event) in events.iter().enumerate() {
|
|
assert_eq!(event["sequence_number"], json!(index));
|
|
}
|
|
let terminals = events
|
|
.iter()
|
|
.filter(|e| {
|
|
matches!(
|
|
e["type"].as_str().unwrap(),
|
|
"response.completed" | "response.failed" | "response.incomplete"
|
|
)
|
|
})
|
|
.count();
|
|
assert_eq!(terminals, 1);
|
|
assert!(
|
|
matches!(
|
|
events.last().unwrap()["type"].as_str().unwrap(),
|
|
"response.completed" | "response.failed" | "response.incomplete"
|
|
),
|
|
"the terminal event is last"
|
|
);
|
|
}
|
|
|
|
fn text_of(response: &Value) -> String {
|
|
response["output"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.filter(|item| item["type"] == "message")
|
|
.flat_map(|item| item["content"].as_array().unwrap().clone())
|
|
.filter_map(|part| part["text"].as_str().map(str::to_owned))
|
|
.collect()
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn responses_over_real_grpc_stream_and_complete_with_the_engines_usage() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let stack = Stack::start("chain-basic", runtime.address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
|
|
runtime
|
|
.engine
|
|
.push(Script::stop_with(&["hel", "lo ", "жук"], usage(11, 3)));
|
|
let (status, text) = stack
|
|
.post("/v1/responses", &body(json!({"stream": true})))
|
|
.await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let events = sse_events(&text);
|
|
assert_one_terminal(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.completed");
|
|
let deltas: String = events
|
|
.iter()
|
|
.filter(|e| e["type"] == "response.output_text.delta")
|
|
.map(|e| e["delta"].as_str().unwrap())
|
|
.collect();
|
|
assert_eq!(deltas, "hello жук");
|
|
|
|
runtime
|
|
.engine
|
|
.push(Script::stop_with(&["done"], usage(11, 1)));
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let response: Value = serde_json::from_str(&text).unwrap();
|
|
assert_eq!(text_of(&response), "done");
|
|
assert_eq!(response["usage"]["input_tokens"], 11);
|
|
|
|
// The prompt the engine got through gRPC is the rendered template, and the sampling defaults
|
|
// stayed unset.
|
|
let seen = runtime.engine.requests();
|
|
assert_eq!(
|
|
seen[0].prompt,
|
|
"<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
|
|
);
|
|
assert_eq!(seen[0].max_output_tokens, 4096);
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn length_tool_call_and_stop_marker_over_real_grpc() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let stack = Stack::start("chain-finish", runtime.address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
|
|
runtime.engine.push(Script::finishing(
|
|
&["cut"],
|
|
FinishReason::Length,
|
|
usage(5, 1),
|
|
));
|
|
let (_, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&body(json!({"stream": true, "max_output_tokens": 1})),
|
|
)
|
|
.await;
|
|
let events = sse_events(&text);
|
|
assert_one_terminal(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.incomplete");
|
|
|
|
let markup = "<tool_call>\n<function=lookup>\n<parameter=key>\nvalue\n</parameter>\n</function>\n</tool_call>";
|
|
let pieces: Vec<String> = markup
|
|
.chars()
|
|
.collect::<Vec<_>>()
|
|
.chunks(9)
|
|
.map(|c| c.iter().collect())
|
|
.collect();
|
|
let refs: Vec<&str> = pieces.iter().map(String::as_str).collect();
|
|
runtime.engine.push(Script::stop_with(&refs, usage(30, 20)));
|
|
let (status, text) = stack
|
|
.post(
|
|
"/v1/responses",
|
|
&body(json!({"tools": [{"type": "function", "name": "lookup",
|
|
"parameters": {"type": "object", "properties": {"key": {"type": "string"}},
|
|
"required": ["key"], "additionalProperties": false}}]})),
|
|
)
|
|
.await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let response: Value = serde_json::from_str(&text).unwrap();
|
|
let call = response["output"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.find(|item| item["type"] == "function_call")
|
|
.unwrap();
|
|
assert_eq!(call["name"], "lookup");
|
|
assert_eq!(
|
|
serde_json::from_str::<Value>(call["arguments"].as_str().unwrap()).unwrap(),
|
|
json!({"key": "value"})
|
|
);
|
|
|
|
// The model ends its turn with a marker; the engine would keep going, the marker stops it.
|
|
runtime
|
|
.engine
|
|
.push(Script::hanging_after(&["ok", "<|im_end|>", "junk"]));
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
assert_eq!(
|
|
text_of(&serde_json::from_str(&text).unwrap()),
|
|
"ok",
|
|
"{text}"
|
|
);
|
|
let ids = runtime.engine.cancels();
|
|
assert_eq!(ids.len(), 1, "the marker cancelled the runtime generation");
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_client_disconnect_cancels_through_grpc_and_the_next_request_is_served() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let stack = Stack::start("chain-cancel", runtime.address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
|
|
runtime.engine.push(Script::hanging_after(&["start"]));
|
|
let mut response = stack
|
|
.client
|
|
.post(format!("{}/v1/responses", stack.base))
|
|
.header("content-type", "application/json")
|
|
.body(body(json!({"stream": true})).to_string())
|
|
.send()
|
|
.await
|
|
.unwrap();
|
|
let mut seen = String::new();
|
|
while !seen.contains("response.output_text.delta") {
|
|
let chunk = tokio::time::timeout(Duration::from_secs(10), response.chunk())
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
.expect("stream ended early");
|
|
seen.push_str(&String::from_utf8_lossy(&chunk));
|
|
}
|
|
drop(response);
|
|
tokio::time::timeout(Duration::from_secs(10), async {
|
|
while runtime.engine.is_generating() {
|
|
tokio::time::sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.expect("the engine generation was cancelled");
|
|
assert_eq!(runtime.engine.cancels().len(), 1);
|
|
|
|
runtime
|
|
.engine
|
|
.push(Script::stop_with(&["again"], usage(2, 1)));
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn an_engine_failure_and_a_dying_engine_both_end_the_sse_stream_with_response_failed() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let stack = Stack::start("chain-faults", runtime.address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
|
|
runtime.engine.push(Script::failing_after(
|
|
&["par"],
|
|
leleka_backend_api::ErrorCode::Internal,
|
|
"scripted failure",
|
|
));
|
|
let (_, text) = stack
|
|
.post("/v1/responses", &body(json!({"stream": true})))
|
|
.await;
|
|
let events = sse_events(&text);
|
|
assert_one_terminal(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.failed");
|
|
|
|
// The engine behind the runtime vanishes mid-generation.
|
|
runtime.engine.push(Script::dying_after(&["half"]));
|
|
let (status, text) = stack
|
|
.post("/v1/responses", &body(json!({"stream": true})))
|
|
.await;
|
|
assert_eq!(status, 200, "{text}");
|
|
let events = sse_events(&text);
|
|
assert_one_terminal(&events);
|
|
assert_eq!(events.last().unwrap()["type"], "response.failed");
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|
|
|
|
/// The runtime process restarts (new epoch, no model): readiness drops by itself, requests are
|
|
/// refused, and once the operator loads the model again the API serves without a restart.
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn a_restarted_runtime_flips_readiness_and_is_reattached_after_the_operator_reloads() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let address = runtime.address;
|
|
let stack = Stack::start("chain-restart", address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
|
|
runtime.stop().await;
|
|
stack.wait_state(WorkerState::Restarting).await;
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 503, "{text}");
|
|
|
|
// Same port, new process: new epoch, nothing loaded until the operator says so.
|
|
let reborn = Runtime::start(Some(address)).await;
|
|
tokio::time::sleep(Duration::from_millis(300)).await;
|
|
assert_ne!(stack.status.read().await.state, WorkerState::Ready);
|
|
reborn.operator_loads_the_model().await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
reborn
|
|
.engine
|
|
.push(Script::stop_with(&["back"], usage(2, 1)));
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 200, "{text}");
|
|
assert_eq!(text_of(&serde_json::from_str(&text).unwrap()), "back");
|
|
stack.finish().await;
|
|
reborn.stop().await;
|
|
}
|
|
|
|
/// 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 serves_more_than_256_generations_in_one_runtime_epoch() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
runtime
|
|
.engine
|
|
.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..300 {
|
|
let (status, text) = stack.post("/v1/responses", &body(json!({}))).await;
|
|
assert_eq!(status, 200, "request {index}: {text}");
|
|
}
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread")]
|
|
async fn the_engines_prefix_summary_reaches_v1_status_and_answers_prefix_match() {
|
|
let runtime = Runtime::start(None).await;
|
|
runtime.operator_loads_the_model().await;
|
|
let stack = Stack::start("chain-prefix", runtime.address).await;
|
|
stack.wait_state(WorkerState::Ready).await;
|
|
let get_status = || async {
|
|
let text = stack.client.get(format!("{}/v1/status", stack.base)).send().await.unwrap().text().await.unwrap();
|
|
serde_json::from_str::<Value>(&text).unwrap()
|
|
};
|
|
|
|
// an engine without a prefix cache reports none
|
|
assert_eq!(get_status().await["prefix_cache"], Value::Null);
|
|
|
|
// the engine's cache summary travels runtime -> snapshot (gRPC) -> worker health tick -> /v1/status
|
|
let summary = json!({
|
|
"version": 1, "chain_version": 1, "namespace": "00000000000000ab", "block_tokens": 2048,
|
|
"budget_bytes": 1u64 << 30, "used_bytes": 1u64 << 20, "nodes": 2, "blocks": 6, "truncated": false,
|
|
"heads": [{"h": "00000000000000a1", "tokens": 4096}, {"h": "00000000000000a2", "tokens": 12288}],
|
|
"stats": {"requests": 3, "hits": 1, "shared_hits": 1, "misses": 2, "reused_tokens": 4096, "prompt_tokens": 9000, "admitted": 2, "rejected": 0, "evicted": 0},
|
|
});
|
|
runtime.engine.set_prefix_summary(Some(summary.to_string()));
|
|
let deadline = Instant::now() + Duration::from_secs(10);
|
|
let status = loop {
|
|
let status = get_status().await;
|
|
if status["prefix_cache"].is_object() {
|
|
break status;
|
|
}
|
|
assert!(Instant::now() < deadline, "the summary never reached /v1/status");
|
|
tokio::time::sleep(Duration::from_millis(20)).await;
|
|
};
|
|
assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab");
|
|
assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2);
|
|
|
|
let (code, text) = stack
|
|
.post(
|
|
"/v1/prefix_match",
|
|
&json!({"namespace": "00000000000000ab", "block_hashes": ["00000000000000a1", "00000000000000aa", "00000000000000a2"]}),
|
|
)
|
|
.await;
|
|
assert_eq!(code, 200, "{text}");
|
|
let answer: Value = serde_json::from_str(&text).unwrap();
|
|
assert_eq!((answer["cached_tokens"].as_u64(), answer["block_tokens"].as_u64()), (Some(12288), Some(2048)));
|
|
|
|
// the cache goes away (the engine restarted without it): the view clears
|
|
runtime.engine.set_prefix_summary(None);
|
|
let deadline = Instant::now() + Duration::from_secs(10);
|
|
while !get_status().await["prefix_cache"].is_null() {
|
|
assert!(Instant::now() < deadline, "the summary never cleared");
|
|
tokio::time::sleep(Duration::from_millis(20)).await;
|
|
}
|
|
stack.finish().await;
|
|
runtime.stop().await;
|
|
}
|