Files
leleka/control-plane/tests/prefix_match_http.rs
T
Pavlo Ratushnyi 3530208024 STRA-338 S7: AppState in four groups, app/ routes split by role, main.rs becomes a dispatcher plus the composition root
AppState (app/state.rs) is now lifecycle + EngineLink (client port, control channel, worker status, pool,
queue timeout) + HttpPolicy (api key, CORS, trusted origins) + ModelView (name, aliases, tokenizer, template,
vision port, prefix-cache and memory views) + Services (response store, monitor, MCP port, settings, clock,
started_at). Field uses were rewritten mechanically (state.worker -> state.engine.worker, ...); no handler logic
changed. The old impl_default_for_appstate.rs, which held the route table and the admin handlers, is app/routes.rs,
app/admin_routes.rs and app/readiness.rs.

main.rs (1156 lines: an 840-line argument match, the serve function, two helpers) is now 8 lines. The argument match
is split into command groups under src/cli/ (operations, model_fetch, model_inspect, model_ensure, model_prepare,
kar_inspect, kar_verify, kar_overlay, model_text; each owns its arms in their old order and answers Ok(false) for a
line it does not own), serve() and shutdown_signal() are src/serve.rs (the composition root), the usage text is
cli/usage.rs. The binary name and every command line are unchanged.

Architecture gate: control-plane/src/main.rs leaves the oversize list (1156 -> 8). --allow-increase was used because
the type change forces the AppState struct literals in seven already-oversize test/example files to nest by group:
cp_replay.rs +7, responses/tests.rs +11, backend_worker_http.rs +14, mcp_hub.rs +3, memory_gate_http.rs +7,
vision_http.rs +6, desktop-core api_over_runtime.rs +6 (55 lines in all, against 1148 lines removed from main.rs).
Test outcomes are unchanged (597 ok / 2 ignored before and after, 14 new tests from S16).
2026-11-05 20:22:10 +01:00

104 lines
3.5 KiB
Rust

//! The pool routing surface of the prefix cache over HTTP: `GET /v1/status` carries the engine's summary and
//! `POST /v1/prefix_match` answers from it (`docs/prefix-cache.md`, "Pool protocol").
use std::sync::Arc;
use strata_control::app::ModelView;
use serde_json::{Value, json};
use strata_control::{
app::{AppState, router},
prefix_view::PrefixView,
};
fn summary() -> String {
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},
})
.to_string()
}
async fn get_json(client: &reqwest::Client, url: &str) -> Value {
serde_json::from_str(&client.get(url).send().await.unwrap().text().await.unwrap()).unwrap()
}
async fn post_json(client: &reqwest::Client, url: &str, body: Value) -> Value {
let text = client
.post(url)
.body(body.to_string())
.send()
.await
.unwrap()
.text()
.await
.unwrap();
serde_json::from_str(&text).unwrap()
}
async fn serve(view: Arc<PrefixView>) -> String {
let state = AppState {
model: ModelView {
prefix_cache: view,
..Default::default()
},
..Default::default()
};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move { axum::serve(listener, router(state)).await });
url
}
#[tokio::test]
async fn status_shows_the_summary_and_prefix_match_answers_from_it() {
let view = Arc::new(PrefixView::default());
let url = serve(view.clone()).await;
let client = reqwest::Client::new();
// no cache reported: null, and an honest "not available"
let status: Value = get_json(&client, &format!("{url}/v1/status")).await;
assert_eq!(status["prefix_cache"], Value::Null);
let none = post_json(
&client,
&format!("{url}/v1/prefix_match"),
json!({"block_hashes": ["00000000000000a1"]}),
)
.await;
assert_eq!(
(none["available"].as_bool(), none["cached_tokens"].as_u64()),
(Some(false), Some(0))
);
view.set(Some(summary()));
let status: Value = get_json(&client, &format!("{url}/v1/status")).await;
assert_eq!(status["prefix_cache"]["namespace"], "00000000000000ab");
assert_eq!(status["prefix_cache"]["heads"].as_array().unwrap().len(), 2);
let answer = post_json(
&client,
&format!("{url}/v1/prefix_match"),
json!({"namespace": "00000000000000ab", "block_hashes": ["00000000000000a1", "00000000000000ff", "00000000000000a2"]}),
)
.await;
assert_eq!(answer["cached_tokens"], 12288);
assert_eq!(answer["block_tokens"], 2048);
assert_eq!(answer["compatible"], true);
// refusals: not JSON, not hashes, a hash of the wrong shape
for body in [
"not json",
r#"{"block_hashes": 5}"#,
r#"{"block_hashes": ["zz"]}"#,
] {
let response = client
.post(format!("{url}/v1/prefix_match"))
.body(body.to_owned())
.send()
.await
.unwrap();
assert_eq!(response.status().as_u16(), 400, "{body}");
}
}