Files
crank/crates/crank-metrics/src/exemplar.rs
T
Hermes DevOps 301dce301a [skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
2026-10-25 08:05:37 +00:00

552 lines
22 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::{
collections::BTreeMap,
sync::{Arc, Mutex, OnceLock},
};
use crate::{DURATION_BUCKETS_SECONDS, MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricService};
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExemplarTraceId([u8; 32]);
impl ExemplarTraceId {
pub fn parse(value: &str) -> Option<Self> {
if value.len() != 32
|| value
.bytes()
.any(|byte| !byte.is_ascii_digit() && !(b'a'..=b'f').contains(&byte))
|| value.bytes().all(|byte| byte == b'0')
{
return None;
}
let mut bytes = [0; 32];
bytes.copy_from_slice(value.as_bytes());
Some(Self(bytes))
}
pub fn as_str(&self) -> &str {
std::str::from_utf8(&self.0).expect("validated ASCII trace id")
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExemplarObservation {
pub metric: &'static str,
pub labels: Vec<(&'static str, &'static str)>,
pub bucket_upper_bound: Option<f64>,
pub value: f64,
pub trace_id: ExemplarTraceId,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct ExemplarKey {
metric: &'static str,
labels: Vec<(&'static str, &'static str)>,
bucket_index: usize,
}
fn store() -> &'static Mutex<BTreeMap<ExemplarKey, Arc<ExemplarObservation>>> {
static STORE: OnceLock<Mutex<BTreeMap<ExemplarKey, Arc<ExemplarObservation>>>> =
OnceLock::new();
STORE.get_or_init(|| Mutex::new(BTreeMap::new()))
}
/// Process-local capacity of the exemplar store: the projected histogram
/// capacity of the bound service, never the union capacity and never a hidden
/// `min(union, hard cap)` truncation of legitimate slots. A projection whose
/// checked arithmetic overflows fails closed (no exemplar growth) instead of
/// recording under a saturated capacity.
pub(crate) fn service_capacity(service: MetricService) -> usize {
crate::schema::checked_exemplar_capacity(service)
.unwrap_or(0)
.min(MAX_EXEMPLAR_SLOTS_PER_PROCESS)
}
/// Independent private ownership barrier. The public facade normalises before it
/// calls this helper, but the internal entry point must never rely on that: the
/// caller's service has to be the **bound** process identity, the family has to
/// belong to that service, and a family that declares a `route` domain has to
/// carry an already-normalised own/shared route. Any other input is a no-op, so
/// an unbound or foreign call can never allocate a store key.
fn ownership_allows(
service: MetricService,
metric: &'static str,
labels: &[(&'static str, &'static str)],
) -> bool {
if crate::record::bound_metric_service() != Some(service) {
return false;
}
let Some(definition) = crate::schema::service_projection(service)
.iter()
.find(|definition| definition.name == metric)
else {
return false;
};
let mut declared_route = false;
let mut supplied_route = false;
for (name, value) in labels {
if *name != "route" {
continue;
}
supplied_route = true;
if crate::record::normalize_http_route(service, crate::HttpRoute::from_matched_path(value))
.as_str()
!= *value
{
return false;
}
}
for domain in definition.label_domains {
if domain.name == "route" {
declared_route = true;
}
}
!declared_route || supplied_route
}
pub(crate) fn record_exemplar(
service: MetricService,
metric: &'static str,
labels: Vec<(&'static str, &'static str)>,
value: f64,
trace_id: Option<ExemplarTraceId>,
) {
let Some(trace_id) = trace_id else { return };
// The internal entry point enforces the already-normalised ownership: an
// unbound process, another service or an input that does not belong to the
// bound service never creates that foreign key.
if !ownership_allows(service, metric, &labels) {
return;
}
let bucket_index = DURATION_BUCKETS_SECONDS
.iter()
.position(|bound| value <= *bound)
.unwrap_or(DURATION_BUCKETS_SECONDS.len());
let observation = ExemplarObservation {
metric,
labels: labels.clone(),
bucket_upper_bound: DURATION_BUCKETS_SECONDS.get(bucket_index).copied(),
value,
trace_id,
};
let capacity = service_capacity(service);
let Ok(mut observations) = store().lock() else {
return;
};
let key = ExemplarKey {
metric,
labels,
bucket_index,
};
if observations.contains_key(&key) || observations.len() < capacity {
observations.insert(key, Arc::new(observation));
}
}
pub fn exemplar_snapshot() -> Vec<Arc<ExemplarObservation>> {
store()
.lock()
.map(|observations| observations.values().cloned().collect())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::{DURATION_BUCKETS_SECONDS, MetricKind, service_projection};
const ROLE_DIR_PREFIX: &str = "crank-metrics-exemplar-role-";
fn trace() -> ExemplarTraceId {
ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("valid trace id")
}
fn role_dir(role: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("{ROLE_DIR_PREFIX}{role}"))
}
/// Роль передаётся через рабочий каталог дочернего процесса: production
/// boundary checker запрещает чтение environment вне `crank-config`, а
/// `cfg(test)`-модуль в `src/**` под это правило попадает.
fn current_role() -> Option<String> {
std::env::current_dir()
.ok()?
.file_name()?
.to_str()?
.strip_prefix(ROLE_DIR_PREFIX)
.map(str::to_owned)
}
fn route_to_child_role(role: &str, test: &str) -> bool {
match current_role().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("nested exemplar child role {actual} for {test}"),
None => {
let directory = role_dir(role);
std::fs::create_dir_all(&directory).expect("exemplar role dir");
let output =
std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([test, "--exact", "--nocapture"])
.current_dir(&directory)
.output()
.expect("re-executed exemplar child");
assert!(
output.status.success(),
"child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
}
}
fn labelsets(
definition: &crate::schema::MetricDefinition,
) -> Vec<Vec<(&'static str, &'static str)>> {
let mut combos: Vec<Vec<(&'static str, &'static str)>> = vec![Vec::new()];
for domain in definition.label_domains {
let mut next = Vec::with_capacity(combos.len() * domain.values.len());
for combo in &combos {
for value in domain.values {
let mut extended = combo.clone();
extended.push((domain.name, *value));
next.push(extended);
}
}
combos = next;
}
combos
}
fn store_len() -> usize {
store().lock().map(|entries| entries.len()).unwrap_or(0)
}
/// TD-X3 — maximal private population: projected domain сервиса заполняет
/// ровно `capacity` slots (11508/2310) и следующий distinct key отвергается.
///
/// Родитель без роли запускает **оба** дочерних процесса (`admin_api` и
/// `mcp_server`), печатает результат каждого ребёнка и требует явный отчёт
/// `TD-X3 CHILD role=…`; дочерние прогоны различаются ролью (рабочий
/// каталог), а не глобальным reset.
#[test]
fn full_projected_domain_fills_exactly() {
match current_role().as_deref() {
Some("admin_api") => {
report_child("admin_api", fill_and_check(MetricService::AdminApi, 12_348))
}
Some("mcp_server") => report_child(
"mcp_server",
fill_and_check(MetricService::McpServer, 2_310),
),
Some(other) => panic!("unexpected exemplar role {other}"),
None => {
for role in ["admin_api", "mcp_server"] {
let directory = role_dir(role);
std::fs::create_dir_all(&directory).expect("exemplar role dir");
let output =
std::process::Command::new(std::env::current_exe().expect("test binary"))
.args([
"exemplar::tests::full_projected_domain_fills_exactly",
"--exact",
"--nocapture",
])
.current_dir(&directory)
.output()
.expect("re-executed exemplar child");
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
for line in stdout.lines().filter(|line| line.contains("TD-X3 CHILD")) {
println!("{line}");
}
assert!(
output.status.success(),
"{role} child failed:\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
assert!(
stdout.contains(&format!("TD-X3 CHILD role={role}")),
"{role} child обязан явно отчитаться своим отчётом:\n{stdout}\n{stderr}"
);
}
}
}
}
fn report_child(role: &str, counts: (usize, usize, usize)) {
let (enumerated, capacity, store_len) = counts;
println!(
"TD-X3 CHILD role={role} enumerated={enumerated} capacity={capacity} store_len={store_len}"
);
}
fn fill_and_check(service: MetricService, expected: usize) -> (usize, usize, usize) {
crate::bind_metric_service(service).expect("binding for the exemplar population");
assert_eq!(
store_len(),
0,
"fresh child обязан начинать с пустого store"
);
let mut enumerated = 0_usize;
for definition in service_projection(service) {
if definition.kind != MetricKind::Histogram {
continue;
}
for labels in labelsets(definition) {
for index in 0..=definition.buckets.len() {
let value =
definition.buckets.get(index).copied().unwrap_or_else(|| {
definition.buckets[definition.buckets.len() - 1] + 1.0
});
record_exemplar(
service,
definition.name,
labels.clone(),
value,
Some(trace()),
);
enumerated += 1;
}
}
}
assert_eq!(
enumerated, expected,
"projected domain обязан дать ровно {expected} slots"
);
assert_eq!(
service_capacity(service),
expected,
"capacity обязана совпасть с projected domain"
);
assert_eq!(
store_len(),
expected,
"все slot'ы обязаны быть заполнены без потерь"
);
// Существующий ключ принимает последнее наблюдение и не растит store.
let definition = service_projection(service)
.iter()
.find(|definition| definition.kind == MetricKind::Histogram)
.expect("histogram family");
let labels = labelsets(definition)
.into_iter()
.next()
.expect("первый label set проекции");
let refreshed = definition.buckets[0] * 0.5;
record_exemplar(
service,
definition.name,
labels.clone(),
refreshed,
Some(trace()),
);
assert_eq!(
store_len(),
expected,
"повторная запись ключа не растёт store"
);
let latest = exemplar_snapshot()
.into_iter()
.find(|observation| {
observation.metric == definition.name
&& observation.labels == labels
&& observation.bucket_upper_bound == Some(definition.buckets[0])
})
.expect("latest observation для существующего ключа");
assert_eq!(
latest.value, refreshed,
"для существующего ключа сохраняется последнее наблюдение"
);
// Бюджет исчерпан: следующий distinct key отвергается, store не растёт.
// Его `route` — own/shared и проходит ownership guard, поэтому рост
// останавливает именно capacity, а не приватная проверка владения.
record_exemplar(
service,
definition.name,
vec![("route", "/health"), ("method", "__overflow_probe__")],
definition.buckets[0],
Some(trace()),
);
assert_eq!(store_len(), expected, "store не может превысить capacity");
(enumerated, service_capacity(service), store_len())
}
/// F1 — приватный exemplar boundary независимо проверяет bound service,
/// family ownership и HTTP route ownership: unbound, чужой сервис и
/// чужой/невалидный route не создают store key при доступной capacity;
/// positive control и public normalized path сохраняются.
#[test]
fn private_exemplar_requires_bound_service_and_route_ownership() {
if route_to_child_role(
"guard",
"exemplar::tests::private_exemplar_requires_bound_service_and_route_ownership",
) {
return;
}
match current_role().as_deref() {
Some("guard") => guard_ownership_child(),
Some(other) => panic!("unexpected exemplar role {other}"),
None => unreachable!("role checked above"),
}
}
fn guard_ownership_child() {
const HTTP_HISTOGRAM: &str = "crank_http_request_duration_seconds";
assert_eq!(
store_len(),
0,
"fresh guard child обязан начинать с пустого store"
);
// 1. Unbound процесс: приватный вход не создаёт ни ключа, ни entry.
record_exemplar(
MetricService::AdminApi,
HTTP_HISTOGRAM,
vec![("route", "/health"), ("method", "GET")],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
assert_eq!(store_len(), 0, "unbound record не может аллоцировать key");
crate::bind_metric_service(MetricService::AdminApi).expect("admin binding");
// 2. Mismatched service: bound сервис — admin, вызывающий передаёт MCP.
record_exemplar(
MetricService::McpServer,
"crank_mcp_request_duration_seconds",
vec![("method", "tools_call"), ("outcome", "success")],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
// 3. Foreign HTTP route: /v1/... принадлежит MCP, а не bound admin.
record_exemplar(
MetricService::AdminApi,
HTTP_HISTOGRAM,
vec![
("route", "/v1/{workspace_slug}/{agent_slug}"),
("method", "GET"),
],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
// 4. Route label отсутствует в family, объявляющей route domain.
record_exemplar(
MetricService::AdminApi,
HTTP_HISTOGRAM,
vec![("method", "GET")],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
// 5. Неизвестный (не нормализуемый) route text.
record_exemplar(
MetricService::AdminApi,
HTTP_HISTOGRAM,
vec![("route", "/documents/{document_id}"), ("method", "GET")],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
assert_eq!(
store_len(),
0,
"invalid/unbound входы не могут аллоцировать store key"
);
assert!(exemplar_snapshot().is_empty());
// Positive control: own/shared normalised route принята.
record_exemplar(
MetricService::AdminApi,
HTTP_HISTOGRAM,
vec![("route", "/health"), ("method", "GET")],
DURATION_BUCKETS_SECONDS[0],
Some(trace()),
);
assert_eq!(store_len(), 1, "own/shared route обязан быть записан");
// Public normalized path сохранён: чужая route деградирует в unmatched,
// aggregate и exemplar записываются под нормализованным ключом.
let recorder = metrics_util::debugging::DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
crate::record_http_request_with_exemplar(
crate::HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
crate::HttpMethod::Get,
crate::HttpStatusClass::Success,
std::time::Duration::from_millis(4),
Some(trace()),
);
});
let samples = snapshotter.snapshot().into_vec();
assert!(
samples
.iter()
.any(|(key, _, _, _)| key.key().name() == "crank_http_requests_total"),
"public normalized aggregate обязан быть записан"
);
assert!(
exemplar_snapshot().iter().any(|observation| {
observation.metric == HTTP_HISTOGRAM
&& observation
.labels
.iter()
.any(|(name, value)| *name == "route" && *value == "unmatched")
}),
"public normalized exemplar обязан быть записан под unmatched"
);
assert_eq!(
store_len(),
2,
"public path добавляет ровно один normalized unmatched key"
);
}
/// TD-X5 — poisoned store никогда не ломает product path.
#[test]
fn poisoned_store_never_breaks_product_path() {
if route_to_child_role(
"poison",
"exemplar::tests::poisoned_store_never_breaks_product_path",
) {
return;
}
match current_role().as_deref() {
Some("poison") => {
crate::bind_metric_service(MetricService::AdminApi).expect("admin binding");
let _ = std::thread::spawn(|| {
let _guard = store().lock().expect("store lock");
panic!("poison the exemplar store");
})
.join();
assert!(store().is_poisoned(), "store обязан быть poisoned");
// Aggregate-путь уже записан; exemplar обязан безопасно ничего не делать.
let recorder = metrics_util::debugging::DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
crate::record_http_request_with_exemplar(
crate::HttpRoute::from_matched_path("/health"),
crate::HttpMethod::Get,
crate::HttpStatusClass::Success,
std::time::Duration::from_millis(4),
Some(trace()),
);
});
let samples = snapshotter.snapshot().into_vec();
assert!(
samples
.iter()
.any(|(key, _, _, _)| key.key().name() == "crank_http_requests_total"),
"aggregate обязан быть записан несмотря на poisoned store"
);
assert_eq!(store_len(), 0, "poisoned store не принимает новых entries");
assert!(exemplar_snapshot().is_empty());
}
Some(other) => panic!("unexpected exemplar role {other}"),
None => unreachable!("role checked above"),
}
}
}