Mechanical rustfmt (control-plane, desktop-core and the runtime client had 360 hunks of drift; the CI format steps for control-plane and desktop-core were red), plus, found by running `cargo clippy -D warnings` and the tests on Linux: * control-plane/tests/log_failure_sse.rs `no_panicking_log_macros_in_the_serving_crate` was red on main since the observability merge: two test-only `eprintln!` samples (prometheus.rs, request_log.rs) trip its source scan. They now write to stderr with `write_fmt` and ignore a failed write, which is what the test asks for; the output is the same. * tool_output.rs `is_multiple_of(2)`, an unneeded `mut` in a control-plane test, a collapsible `if` in leleka-inference.rs, `#[allow(dead_code)]` on observer_adaptive_slots (compiled into leleka-inference-evaluation too). * crates/deploy/src/facts.rs: `lab_holder_running` moved above `mod tests` (clippy::items_after_test_module); code moved, not changed. Kept as its own commit so it can be redone with `cargo fmt` if other branches touch these crates first. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
209 lines
7.4 KiB
Rust
209 lines
7.4 KiB
Rust
//! The engine's prefix-cache summary as this control plane last saw it, for a front router that places requests
|
|
//! across many runtimes (`docs/prefix-cache.md`, "Pool protocol").
|
|
//!
|
|
//! The engine publishes a JSON summary of the checkpoint heads its cache holds (block-hash-chain value and tokens
|
|
//! covered, plus counters). The worker copies it here on its health tick and after every request; `GET /v1/status`
|
|
//! shows it as `prefix_cache`, and `POST /v1/prefix_match` answers "how much of this prompt do you hold" from it. The
|
|
//! answer is a hint about a snapshot, never a promise: the engine may have evicted a head since.
|
|
|
|
use std::{collections::HashMap, sync::RwLock, time::Instant};
|
|
|
|
use serde_json::{Value, json};
|
|
|
|
/// Most chain values one `prefix_match` query may carry (a 262144-token context in 256-token blocks is 1024).
|
|
pub const MAX_HASHES: usize = 16_384;
|
|
|
|
#[derive(Default)]
|
|
pub struct PrefixView {
|
|
latest: RwLock<Option<(Value, Instant)>>,
|
|
}
|
|
|
|
/// Why a query was refused.
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum QueryError {
|
|
TooManyHashes,
|
|
BadHash,
|
|
}
|
|
|
|
impl PrefixView {
|
|
/// Replace the stored summary (`None`: the engine has no prefix cache, or is unreachable).
|
|
pub fn set(&self, summary: Option<String>) {
|
|
let value = summary
|
|
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
|
|
.filter(Value::is_object);
|
|
if let Ok(mut latest) = self.latest.write() {
|
|
*latest = value.map(|value| (value, Instant::now()));
|
|
}
|
|
}
|
|
|
|
/// The summary for `GET /v1/status`, with its age; `null` when there is none.
|
|
pub fn status(&self) -> Value {
|
|
let Ok(latest) = self.latest.read() else {
|
|
return Value::Null;
|
|
};
|
|
match latest.as_ref() {
|
|
Some((value, at)) => {
|
|
let mut value = value.clone();
|
|
value["age_ms"] = json!(at.elapsed().as_millis() as u64);
|
|
value
|
|
}
|
|
None => Value::Null,
|
|
}
|
|
}
|
|
|
|
/// Tokens of the longest cached prefix of a prompt whose block chain values (hex, one per full block, in order)
|
|
/// are `hashes`. `namespace`, when given, must equal the engine's or nothing matches (a different model, block
|
|
/// size or chain version).
|
|
pub fn prefix_match(
|
|
&self,
|
|
namespace: Option<&str>,
|
|
hashes: &[String],
|
|
) -> Result<Value, QueryError> {
|
|
if hashes.len() > MAX_HASHES {
|
|
return Err(QueryError::TooManyHashes);
|
|
}
|
|
if hashes
|
|
.iter()
|
|
.any(|h| h.len() != 16 || !h.bytes().all(|b| b.is_ascii_hexdigit()))
|
|
{
|
|
return Err(QueryError::BadHash);
|
|
}
|
|
let Ok(latest) = self.latest.read() else {
|
|
return Ok(json!({"available": false, "cached_tokens": 0}));
|
|
};
|
|
let Some((summary, at)) = latest.as_ref() else {
|
|
return Ok(json!({"available": false, "cached_tokens": 0}));
|
|
};
|
|
let engine_namespace = summary["namespace"].as_str().unwrap_or_default();
|
|
let compatible =
|
|
namespace.is_none_or(|wanted| wanted.eq_ignore_ascii_case(engine_namespace));
|
|
let heads: HashMap<&str, u64> = summary["heads"]
|
|
.as_array()
|
|
.map(|heads| {
|
|
heads
|
|
.iter()
|
|
.filter_map(|h| Some((h["h"].as_str()?, h["tokens"].as_u64()?)))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
let cached = if compatible {
|
|
hashes
|
|
.iter()
|
|
.rev()
|
|
.find_map(|h| heads.get(h.to_ascii_lowercase().as_str()).copied())
|
|
.unwrap_or(0)
|
|
} else {
|
|
0
|
|
};
|
|
Ok(json!({
|
|
"available": true,
|
|
"compatible": compatible,
|
|
"namespace": engine_namespace,
|
|
"block_tokens": summary["block_tokens"],
|
|
"cached_tokens": cached,
|
|
"truncated": summary["truncated"],
|
|
"age_ms": at.elapsed().as_millis() as u64,
|
|
}))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
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()
|
|
}
|
|
fn hashes(list: &[&str]) -> Vec<String> {
|
|
list.iter().map(|h| (*h).to_owned()).collect()
|
|
}
|
|
|
|
#[test]
|
|
fn the_deepest_known_head_of_the_chain_wins() {
|
|
let view = PrefixView::default();
|
|
assert_eq!(view.status(), Value::Null);
|
|
assert_eq!(
|
|
view.prefix_match(None, &hashes(&["00000000000000a1"]))
|
|
.unwrap()["available"],
|
|
false
|
|
);
|
|
view.set(Some(summary()));
|
|
let status = view.status();
|
|
assert_eq!(status["namespace"], "00000000000000ab");
|
|
assert!(status["age_ms"].is_u64());
|
|
let chain = hashes(&[
|
|
"00000000000000a1",
|
|
"00000000000000ff",
|
|
"00000000000000a2",
|
|
"00000000000000ee",
|
|
]);
|
|
let reply = view.prefix_match(Some("00000000000000AB"), &chain).unwrap();
|
|
assert_eq!(
|
|
(
|
|
reply["cached_tokens"].as_u64(),
|
|
reply["block_tokens"].as_u64(),
|
|
reply["compatible"].as_bool()
|
|
),
|
|
(Some(12288), Some(2048), Some(true))
|
|
);
|
|
// a router that only knows the first blocks gets the shallow head
|
|
assert_eq!(
|
|
view.prefix_match(None, &chain[..2]).unwrap()["cached_tokens"],
|
|
4096
|
|
);
|
|
// an unknown prefix matches nothing
|
|
assert_eq!(
|
|
view.prefix_match(None, &hashes(&["00000000000000ee"]))
|
|
.unwrap()["cached_tokens"],
|
|
0
|
|
);
|
|
assert_eq!(view.prefix_match(None, &[]).unwrap()["cached_tokens"], 0);
|
|
}
|
|
|
|
#[test]
|
|
fn another_namespace_matches_nothing_and_malformed_queries_are_refused() {
|
|
let view = PrefixView::default();
|
|
view.set(Some(summary()));
|
|
let reply = view
|
|
.prefix_match(Some("00000000000000cd"), &hashes(&["00000000000000a2"]))
|
|
.unwrap();
|
|
assert_eq!(
|
|
(
|
|
reply["compatible"].as_bool(),
|
|
reply["cached_tokens"].as_u64()
|
|
),
|
|
(Some(false), Some(0))
|
|
);
|
|
assert_eq!(
|
|
view.prefix_match(None, &hashes(&["xyz"])),
|
|
Err(QueryError::BadHash)
|
|
);
|
|
assert_eq!(
|
|
view.prefix_match(None, &hashes(&["00000000000000gg"])),
|
|
Err(QueryError::BadHash)
|
|
);
|
|
assert_eq!(
|
|
view.prefix_match(None, &vec!["00000000000000a1".to_owned(); MAX_HASHES + 1]),
|
|
Err(QueryError::TooManyHashes)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_missing_or_malformed_summary_clears_the_view() {
|
|
let view = PrefixView::default();
|
|
view.set(Some(summary()));
|
|
assert!(view.status().is_object());
|
|
view.set(Some("not json".into()));
|
|
assert_eq!(view.status(), Value::Null);
|
|
view.set(Some(summary()));
|
|
view.set(None);
|
|
assert_eq!(view.status(), Value::Null);
|
|
}
|
|
}
|