[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.
This commit is contained in:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

No files matched your search

@@ -1,6 +1,6 @@
use std::process::ExitCode;
const SNAPSHOT: &str = include_str!("../../../../docs/schemas/metrics-registry-v1.json");
const SNAPSHOT: &str = include_str!("../../../../docs/schemas/metrics-registry-v2.json");
fn main() -> ExitCode {
let rendered = match crank_metrics::render_metric_schema_json() {
@@ -21,7 +21,7 @@ fn main() -> ExitCode {
}
match SNAPSHOT {
snapshot if snapshot == rendered => {
println!("metrics_contract_ok schema_version=1");
println!("metrics_contract_ok schema_version=2");
ExitCode::SUCCESS
}
_ => {
+464 -2
View File
@@ -3,7 +3,7 @@ use std::{
sync::{Arc, Mutex, OnceLock},
};
use crate::{DURATION_BUCKETS_SECONDS, max_exemplar_slots};
use crate::{DURATION_BUCKETS_SECONDS, MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricService};
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ExemplarTraceId([u8; 32]);
@@ -50,13 +50,73 @@ fn store() -> &'static Mutex<BTreeMap<ExemplarKey, Arc<ExemplarObservation>>> {
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)
@@ -68,6 +128,7 @@ pub(crate) fn record_exemplar(
value,
trace_id,
};
let capacity = service_capacity(service);
let Ok(mut observations) = store().lock() else {
return;
};
@@ -76,7 +137,7 @@ pub(crate) fn record_exemplar(
labels,
bucket_index,
};
if observations.contains_key(&key) || observations.len() < max_exemplar_slots() {
if observations.contains_key(&key) || observations.len() < capacity {
observations.insert(key, Arc::new(observation));
}
}
@@ -87,3 +148,404 @@ pub fn exemplar_snapshot() -> Vec<Arc<ExemplarObservation>> {
.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"),
}
}
}
+17 -8
View File
@@ -3,6 +3,11 @@
//! Product crate передают только типизированные значения. Имена метрик,
//! ключи и значения labels сосредоточены здесь, поэтому пользовательские
//! идентификаторы и тексты нельзя случайно превратить во временные ряды.
//!
//! Story 3.6: допустимые HTTP-идентичности выводятся из **одного** typed
//! перечисления route+owners (`HTTP_ROUTES`); каждый процесс один раз
//! фиксирует сервис (`bind_metric_service`) до установки recorder, иначе все
//! recording-пути безопасно ничего не делают.
mod exemplar;
mod labels;
@@ -17,8 +22,9 @@ pub use labels::{
UpstreamOutcome,
};
pub use record::{
InFlightGuard, ToolInvocationMetrics, UpstreamRequestMetrics, initialize_gauges,
record_cache_outcome, record_confirmation_outcome, record_export_failure, record_http_request,
InFlightGuard, ToolInvocationMetrics, UpstreamRequestMetrics, bind_metric_service,
bound_metric_service, initialize_gauges, normalize_http_route, record_cache_outcome,
record_confirmation_outcome, record_export_failure, record_http_request,
record_http_request_with_exemplar, record_idempotency_outcome, record_invocation_history_lost,
record_limit_rejection, record_mcp_request, record_mcp_request_with_exemplar,
record_tool_invocation, record_tool_invocation_with_exemplar, record_upstream_request,
@@ -26,10 +32,13 @@ pub use record::{
set_mcp_active_sessions, set_mcp_session_metrics_fresh,
};
pub use schema::{
DURATION_BUCKETS_SECONDS, HTTP_ROUTE_DOMAIN, LabelClass, LabelDomain, MAX_EXPOSITION_BYTES,
MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY,
MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION, MetricDefinition, MetricKind,
MetricProcess, MetricService, MetricUnit, PROCESS_CONSTANT_LABELS, SchemaBudget, SchemaError,
max_exemplar_slots, metric_schema, metric_schema_for_service, render_metric_schema_json,
schema_budget, validate_budget, validate_schema,
ADMIN_HTTP_ROUTE_DOMAIN, DURATION_BUCKETS_SECONDS, HTTP_ROUTE_DOMAIN, HTTP_ROUTES,
HttpRouteDefinition, LabelClass, LabelDomain, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES,
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, MCP_HTTP_ROUTE_DOMAIN,
METRIC_SCHEMA_VERSION, MetricBindingError, MetricDefinition, MetricKind, MetricProcess,
MetricService, MetricUnit, PROCESS_CONSTANT_LABELS, SchemaBudget, SchemaError,
http_route_processes, max_exemplar_slots, metric_schema, metric_schema_for_service,
render_metric_schema_json, schema_budget, service_projection, validate_all_projections,
validate_budget, validate_exemplar_budget, validate_http_routes, validate_schema,
};
+148 -29
View File
@@ -1,14 +1,63 @@
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use metrics::Gauge;
use crate::schema::{MetricDefinition, metric_schema};
use crate::{
CacheOutcome, ConfirmationOutcome, DbPoolState, ExemplarTraceId, Exporter, HttpMethod,
HttpRoute, HttpStatusClass, IdempotencyOutcome, InvocationSource, LimitStage, McpMethod,
McpOutcome, McpResponseMode, SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind,
UpstreamOutcome,
McpOutcome, McpResponseMode, MetricBindingError, MetricService, SignalType, ToolErrorKind,
ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
};
static BINDING: OnceLock<MetricService> = OnceLock::new();
/// Publishes the closed process identity exactly once, before the recorder,
/// gauges, producers and any listener exist. Re-binding the same service is
/// idempotent; a different service is a typed conflict and never wins twice.
pub fn bind_metric_service(service: MetricService) -> Result<(), MetricBindingError> {
crate::schema::validate_all_projections().map_err(|_| MetricBindingError::InvalidSchema)?;
// `OnceLock::set` returns `Err(value)` (the value passed in, not the stored
// one), so the idempotency check must read the published binding back.
if BINDING.set(service).is_ok() {
return Ok(());
}
match BINDING.get() {
Some(existing) if *existing == service => Ok(()),
_ => Err(MetricBindingError::ConflictingService),
}
}
pub fn bound_metric_service() -> Option<MetricService> {
BINDING.get().copied()
}
/// Normalises one route against the bound service: own and shared routes are
/// preserved, a known route owned by another service degrades to `unmatched`.
pub fn normalize_http_route(service: MetricService, route: HttpRoute) -> HttpRoute {
match crate::http_route_processes(route.as_str()) {
Some(owners) if owners.contains(&service.process()) => route,
_ => HttpRoute::unmatched(),
}
}
pub(crate) fn family_applies(service: MetricService, name: &'static str) -> bool {
metric_schema()
.iter()
.find(|definition| definition.name == name)
.is_some_and(|definition: &MetricDefinition| {
definition.processes.contains(&service.process())
})
}
/// Unbound facades (plain unit tests or libraries without observability) are a
/// safe no-op; the process never registers a metric handle or exemplar entry.
fn bound_family(name: &'static str) -> Option<MetricService> {
let service = BINDING.get().copied()?;
family_applies(service, name).then_some(service)
}
pub fn record_http_request(
route: HttpRoute,
method: HttpMethod,
@@ -25,6 +74,10 @@ pub fn record_http_request_with_exemplar(
duration: Duration,
exemplar: Option<ExemplarTraceId>,
) {
let Some(service) = bound_family("crank_http_requests_total") else {
return;
};
let route = normalize_http_route(service, route);
metrics::counter!(
"crank_http_requests_total",
"route" => route.as_str(),
@@ -39,6 +92,7 @@ pub fn record_http_request_with_exemplar(
)
.record(duration.as_secs_f64());
crate::exemplar::record_exemplar(
service,
"crank_http_request_duration_seconds",
vec![("route", route.as_str()), ("method", method.as_str())],
duration.as_secs_f64(),
@@ -62,6 +116,9 @@ pub fn record_mcp_request_with_exemplar(
duration: Duration,
exemplar: Option<ExemplarTraceId>,
) {
let Some(service) = bound_family("crank_mcp_requests_total") else {
return;
};
metrics::counter!(
"crank_mcp_requests_total",
"method" => method.as_str(),
@@ -76,6 +133,7 @@ pub fn record_mcp_request_with_exemplar(
)
.record(duration.as_secs_f64());
crate::exemplar::record_exemplar(
service,
"crank_mcp_request_duration_seconds",
vec![("method", method.as_str()), ("outcome", outcome.as_str())],
duration.as_secs_f64(),
@@ -84,10 +142,16 @@ pub fn record_mcp_request_with_exemplar(
}
pub fn set_mcp_active_sessions(count: u64) {
if bound_family("crank_mcp_active_sessions").is_none() {
return;
}
metrics::gauge!("crank_mcp_active_sessions").set(count as f64);
}
pub fn set_mcp_session_metrics_fresh(fresh: bool) {
if bound_family("crank_mcp_session_metrics_fresh").is_none() {
return;
}
metrics::gauge!("crank_mcp_session_metrics_fresh").set(if fresh { 1.0 } else { 0.0 });
}
@@ -107,6 +171,9 @@ pub fn record_tool_invocation_with_exemplar(
duration: Duration,
exemplar: Option<ExemplarTraceId>,
) {
let Some(service) = bound_family("crank_tool_invocations_total") else {
return;
};
let error_kind = match outcome {
ToolOutcome::Success => ToolErrorKind::None,
ToolOutcome::Aborted => ToolErrorKind::Aborted,
@@ -131,6 +198,7 @@ pub fn record_tool_invocation_with_exemplar(
)
.record(duration.as_secs_f64());
crate::exemplar::record_exemplar(
service,
"crank_tool_invocation_duration_seconds",
vec![("source", source.as_str()), ("outcome", outcome.as_str())],
duration.as_secs_f64(),
@@ -152,6 +220,9 @@ pub fn record_upstream_request_with_exemplar(
duration: Duration,
exemplar: Option<ExemplarTraceId>,
) {
let Some(service) = bound_family("crank_upstream_requests_total") else {
return;
};
metrics::counter!(
"crank_upstream_requests_total",
"operation_kind" => operation_kind.as_str(),
@@ -165,6 +236,7 @@ pub fn record_upstream_request_with_exemplar(
)
.record(duration.as_secs_f64());
crate::exemplar::record_exemplar(
service,
"crank_upstream_request_duration_seconds",
vec![
("operation_kind", operation_kind.as_str()),
@@ -179,25 +251,24 @@ pub struct ToolInvocationMetrics {
source: InvocationSource,
started_at: Option<Instant>,
exemplar: Option<ExemplarTraceId>,
active: bool,
}
impl ToolInvocationMetrics {
pub fn start(source: InvocationSource) -> Self {
Self {
source,
started_at: Some(Instant::now()),
exemplar: None,
}
Self::start_with_exemplar(source, None)
}
pub fn start_with_exemplar(
source: InvocationSource,
exemplar: Option<ExemplarTraceId>,
) -> Self {
let active = bound_family("crank_tool_invocations_total").is_some();
Self {
source,
started_at: Some(Instant::now()),
started_at: active.then(Instant::now),
exemplar,
active,
}
}
@@ -220,7 +291,9 @@ impl ToolInvocationMetrics {
impl Drop for ToolInvocationMetrics {
fn drop(&mut self) {
self.finish(ToolOutcome::Aborted, ToolErrorKind::Aborted);
if self.active {
self.finish(ToolOutcome::Aborted, ToolErrorKind::Aborted);
}
}
}
@@ -228,25 +301,24 @@ pub struct UpstreamRequestMetrics {
operation_kind: UpstreamOperationKind,
started_at: Option<Instant>,
exemplar: Option<ExemplarTraceId>,
active: bool,
}
impl UpstreamRequestMetrics {
pub fn start(operation_kind: UpstreamOperationKind) -> Self {
Self {
operation_kind,
started_at: Some(Instant::now()),
exemplar: None,
}
Self::start_with_exemplar(operation_kind, None)
}
pub fn start_with_exemplar(
operation_kind: UpstreamOperationKind,
exemplar: Option<ExemplarTraceId>,
) -> Self {
let active = bound_family("crank_upstream_requests_total").is_some();
Self {
operation_kind,
started_at: Some(Instant::now()),
started_at: active.then(Instant::now),
exemplar,
active,
}
}
@@ -268,11 +340,16 @@ impl UpstreamRequestMetrics {
impl Drop for UpstreamRequestMetrics {
fn drop(&mut self) {
self.finish(UpstreamOutcome::Aborted);
if self.active {
self.finish(UpstreamOutcome::Aborted);
}
}
}
pub fn record_limit_rejection(stage: LimitStage) {
if bound_family("crank_runtime_limit_rejections_total").is_none() {
return;
}
metrics::counter!(
"crank_runtime_limit_rejections_total",
"stage" => stage.as_str()
@@ -281,6 +358,9 @@ pub fn record_limit_rejection(stage: LimitStage) {
}
pub fn record_cache_outcome(outcome: CacheOutcome) {
if bound_family("crank_runtime_cache_total").is_none() {
return;
}
metrics::counter!(
"crank_runtime_cache_total",
"outcome" => outcome.as_str()
@@ -289,6 +369,9 @@ pub fn record_cache_outcome(outcome: CacheOutcome) {
}
pub fn record_idempotency_outcome(outcome: IdempotencyOutcome) {
if bound_family("crank_idempotency_total").is_none() {
return;
}
metrics::counter!(
"crank_idempotency_total",
"outcome" => outcome.as_str()
@@ -297,6 +380,9 @@ pub fn record_idempotency_outcome(outcome: IdempotencyOutcome) {
}
pub fn record_confirmation_outcome(outcome: ConfirmationOutcome) {
if bound_family("crank_confirmation_total").is_none() {
return;
}
metrics::counter!(
"crank_confirmation_total",
"outcome" => outcome.as_str()
@@ -305,6 +391,9 @@ pub fn record_confirmation_outcome(outcome: ConfirmationOutcome) {
}
pub fn set_db_pool_connections(state: DbPoolState, count: u32) {
if bound_family("crank_db_pool_connections").is_none() {
return;
}
metrics::gauge!(
"crank_db_pool_connections",
"state" => state.as_str()
@@ -313,16 +402,25 @@ pub fn set_db_pool_connections(state: DbPoolState, count: u32) {
}
pub fn set_catalog(tool_count: usize, estimated_context_tokens: usize, warnings: usize) {
if bound_family("crank_catalog_tools").is_none() {
return;
}
metrics::gauge!("crank_catalog_tools").set(tool_count as f64);
metrics::gauge!("crank_catalog_estimated_context_tokens").set(estimated_context_tokens as f64);
metrics::gauge!("crank_catalog_warnings").set(warnings as f64);
}
pub fn record_invocation_history_lost() {
if bound_family("crank_invocation_history_lost_total").is_none() {
return;
}
metrics::counter!("crank_invocation_history_lost_total").increment(1);
}
pub fn record_export_failure(signal: SignalType, exporter: Exporter) {
if bound_family("crank_telemetry_export_failures_total").is_none() {
return;
}
metrics::counter!(
"crank_telemetry_export_failures_total",
"signal_type" => signal.as_str(),
@@ -331,44 +429,65 @@ pub fn record_export_failure(signal: SignalType, exporter: Exporter) {
.increment(1);
}
pub fn initialize_gauges(service: crate::MetricService) {
metrics::gauge!("crank_http_inflight").set(0.0);
metrics::gauge!("crank_runtime_inflight").set(0.0);
/// Gauges are initialised only for the bound service; any other service (or an
/// unbound process) is a no-op and never registers a handle.
pub fn initialize_gauges(service: MetricService) {
if bound_metric_service() != Some(service) {
return;
}
if family_applies(service, "crank_http_inflight") {
metrics::gauge!("crank_http_inflight").set(0.0);
}
if family_applies(service, "crank_runtime_inflight") {
metrics::gauge!("crank_runtime_inflight").set(0.0);
}
set_db_pool_connections(DbPoolState::Idle, 0);
set_db_pool_connections(DbPoolState::Used, 0);
if service == crate::MetricService::McpServer {
metrics::gauge!("crank_mcp_active_sessions").set(0.0);
if service == MetricService::McpServer {
set_mcp_active_sessions(0);
set_mcp_session_metrics_fresh(false);
metrics::gauge!("crank_mcp_active_streams").set(0.0);
if family_applies(service, "crank_mcp_active_streams") {
metrics::gauge!("crank_mcp_active_streams").set(0.0);
}
set_catalog(0, 0, 0);
}
}
pub struct InFlightGuard {
gauge: Gauge,
gauge: Option<Gauge>,
}
impl InFlightGuard {
pub fn http() -> Self {
Self::increment(metrics::gauge!("crank_http_inflight"))
Self::increment("crank_http_inflight")
}
pub fn runtime() -> Self {
Self::increment(metrics::gauge!("crank_runtime_inflight"))
Self::increment("crank_runtime_inflight")
}
pub fn mcp_stream() -> Self {
Self::increment(metrics::gauge!("crank_mcp_active_streams"))
Self::increment("crank_mcp_active_streams")
}
fn increment(gauge: Gauge) -> Self {
fn increment(name: &'static str) -> Self {
if bound_family(name).is_none() {
return Self { gauge: None };
}
let gauge = match name {
"crank_http_inflight" => metrics::gauge!("crank_http_inflight"),
"crank_runtime_inflight" => metrics::gauge!("crank_runtime_inflight"),
_ => metrics::gauge!("crank_mcp_active_streams"),
};
gauge.increment(1.0);
Self { gauge }
Self { gauge: Some(gauge) }
}
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
self.gauge.decrement(1.0);
if let Some(gauge) = &self.gauge {
gauge.decrement(1.0);
}
}
}
+32 -770
View File
@@ -1,772 +1,34 @@
use std::collections::BTreeSet;
//! Реестр метрик: корень модуля (wiring + ре-экспорты подмодулей).
//!
//! Разбиение чисто механическое: имена и сигнатуры всех items не изменились,
//! поэтому и пути `crate::schema::<Item>` внутри крейта, и список
//! `pub use schema::{...}` в `lib.rs` остаются валидными без правок.
use crate::labels::{
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpStatusClass,
IdempotencyOutcome, InvocationSource, LimitStage, McpMethod, McpOutcome, McpResponseMode,
SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
mod budget;
#[cfg(test)]
mod checked_arithmetic_tests;
mod descriptor;
mod projection;
mod rendering;
mod routes;
pub(crate) use budget::checked_exemplar_capacity;
pub use budget::{
MetricBindingError, SchemaBudget, SchemaError, validate_all_projections, validate_budget,
validate_exemplar_budget, validate_schema,
};
pub use descriptor::{
DURATION_BUCKETS_SECONDS, LabelClass, LabelDomain, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES,
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION,
MetricDefinition, MetricKind, MetricProcess, MetricService, MetricUnit,
PROCESS_CONSTANT_LABELS, metric_schema,
};
pub use projection::{
max_exemplar_slots, metric_schema_for_service, schema_budget, service_projection,
};
pub use rendering::render_metric_schema_json;
pub use routes::{
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpRouteDefinition,
MCP_HTTP_ROUTE_DOMAIN, http_route_processes, validate_http_routes,
};
pub const METRIC_SCHEMA_VERSION: u32 = 1;
pub const MAX_METRIC_FAMILIES: usize = 128;
pub const MAX_PRODUCT_LABELS_PER_FAMILY: usize = 4;
pub const MAX_LOGICAL_SERIES_PER_PROCESS: usize = 5_563;
pub const MAX_RENDERED_SERIES_PER_PROCESS: usize = 17_638;
pub const MAX_EXPOSITION_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
}
impl MetricKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Counter => "counter",
Self::Gauge => "gauge",
Self::Histogram => "histogram",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricUnit {
Count,
Seconds,
}
impl MetricUnit {
pub const fn as_str(self) -> &'static str {
match self {
Self::Count => "count",
Self::Seconds => "seconds",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricProcess {
AdminApi,
McpServer,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricService {
AdminApi,
McpServer,
}
impl MetricService {
pub fn parse(value: &str) -> Option<Self> {
match value {
"admin-api" => Some(Self::AdminApi),
"mcp-server" => Some(Self::McpServer),
_ => None,
}
}
pub const fn process(self) -> MetricProcess {
match self {
Self::AdminApi => MetricProcess::AdminApi,
Self::McpServer => MetricProcess::McpServer,
}
}
}
impl MetricProcess {
pub const fn as_str(self) -> &'static str {
match self {
Self::AdminApi => "admin_api",
Self::McpServer => "mcp_server",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LabelClass {
ProductClosed,
ProcessConstant,
}
impl LabelClass {
pub const fn as_str(self) -> &'static str {
match self {
Self::ProductClosed => "product_closed",
Self::ProcessConstant => "process_constant",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LabelDomain {
pub name: &'static str,
pub class: LabelClass,
pub values: &'static [&'static str],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MetricDefinition {
pub name: &'static str,
pub kind: MetricKind,
pub unit: MetricUnit,
pub labels: &'static [&'static str],
pub label_domains: &'static [LabelDomain],
pub buckets: &'static [f64],
pub processes: &'static [MetricProcess],
pub max_logical_series: usize,
pub max_rendered_series: usize,
pub description: &'static str,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchemaBudget {
pub logical_series: usize,
pub rendered_series: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SchemaError {
TooManyFamilies,
DuplicateMetric,
InvalidMetric,
DuplicateLabel,
InvalidDomain,
InvalidBuckets,
InvalidCeiling,
BudgetExceeded,
}
pub const DURATION_BUCKETS_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
];
pub const PROCESS_CONSTANT_LABELS: &[LabelDomain] = &[
LabelDomain {
name: "service",
class: LabelClass::ProcessConstant,
values: &["admin-api", "mcp-server"],
},
LabelDomain {
name: "version",
class: LabelClass::ProcessConstant,
values: &["validated_release_identity"],
},
LabelDomain {
name: "environment",
class: LabelClass::ProcessConstant,
values: &["validated_startup_value"],
},
];
const BOTH: &[MetricProcess] = &[MetricProcess::AdminApi, MetricProcess::McpServer];
const MCP: &[MetricProcess] = &[MetricProcess::McpServer];
pub const HTTP_ROUTE_DOMAIN: &[&str] = &[
"unmatched",
"/health",
"/ready",
"/api/auth/login",
"/api/auth/bootstrap/status",
"/api/auth/bootstrap/complete",
"/api/auth/logout",
"/api/auth/session",
"/api/auth/session/csrf",
"/api/auth/profile",
"/api/auth/password",
"/api/admin/capabilities",
"/api/admin/workspaces",
"/api/admin/workspaces/{workspace_id}",
"/api/admin/workspaces/{workspace_id}/onboarding",
"/api/admin/workspaces/{workspace_id}/onboarding/events",
"/api/admin/workspaces/{workspace_id}/onboarding/reset-selection",
"/api/admin/workspaces/{workspace_id}/onboarding/import-context",
"/api/admin/workspaces/{workspace_id}/onboarding/select-draft",
"/api/admin/workspaces/{workspace_id}/operations",
"/api/admin/workspaces/{workspace_id}/imports/openapi/preview",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans",
"/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply",
"/api/admin/workspaces/{workspace_id}/operations/analyze-quality",
"/api/admin/workspaces/{workspace_id}/operations/import",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export",
"/api/admin/workspaces/{workspace_id}/agents",
"/api/admin/workspaces/{workspace_id}/agents/tool-search/preview",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}",
"/api/admin/workspaces/{workspace_id}/auth-profiles",
"/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}",
"/api/admin/workspaces/{workspace_id}/upstreams",
"/api/admin/workspaces/{workspace_id}/upstreams/{upstream_id}",
"/api/admin/workspaces/{workspace_id}/secrets",
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}",
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}/rotate",
"/api/admin/workspaces/{workspace_id}/export",
"/api/admin/workspaces/{workspace_id}/logs",
"/api/admin/workspaces/{workspace_id}/logs/export.csv",
"/api/admin/workspaces/{workspace_id}/logs/{log_id}",
"/api/admin/workspaces/{workspace_id}/approvals",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny",
"/api/admin/workspaces/{workspace_id}/usage",
"/api/admin/workspaces/{workspace_id}/usage/export.csv",
"/api/admin/workspaces/{workspace_id}/usage/operations/{operation_id}",
"/api/admin/workspaces/{workspace_id}/usage/agents/{agent_id}",
"/v1/{workspace_slug}/{agent_slug}",
"/v1/{workspace_slug}/{agent_slug}/approvals",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
];
const METHODS: &[&str] = HttpMethod::VALUES;
const STATUS: &[&str] = HttpStatusClass::VALUES;
const MCP_METHODS: &[&str] = McpMethod::VALUES;
const RESPONSE_MODES: &[&str] = McpResponseMode::VALUES;
const MCP_OUTCOMES: &[&str] = McpOutcome::VALUES;
const SOURCES: &[&str] = InvocationSource::VALUES;
const TOOL_OUTCOMES: &[&str] = ToolOutcome::VALUES;
const TOOL_ERRORS: &[&str] = ToolErrorKind::VALUES;
const OPERATION_KINDS: &[&str] = UpstreamOperationKind::VALUES;
const UPSTREAM_OUTCOMES: &[&str] = UpstreamOutcome::VALUES;
const LIMIT_STAGES: &[&str] = LimitStage::VALUES;
const CACHE_OUTCOMES: &[&str] = CacheOutcome::VALUES;
const IDEMPOTENCY_OUTCOMES: &[&str] = IdempotencyOutcome::VALUES;
const CONFIRMATION_OUTCOMES: &[&str] = ConfirmationOutcome::VALUES;
const DB_STATES: &[&str] = DbPoolState::VALUES;
const SIGNAL_TYPES: &[&str] = SignalType::VALUES;
const EXPORTERS: &[&str] = Exporter::VALUES;
const fn domain(name: &'static str, values: &'static [&'static str]) -> LabelDomain {
LabelDomain {
name,
class: LabelClass::ProductClosed,
values,
}
}
#[allow(
clippy::too_many_arguments,
reason = "the canonical descriptor keeps every metric contract dimension explicit"
)]
const fn metric(
name: &'static str,
kind: MetricKind,
unit: MetricUnit,
labels: &'static [&'static str],
label_domains: &'static [LabelDomain],
buckets: &'static [f64],
processes: &'static [MetricProcess],
logical: usize,
description: &'static str,
) -> MetricDefinition {
let rendered = if matches!(kind, MetricKind::Histogram) {
logical * (buckets.len() + 3)
} else {
logical
};
MetricDefinition {
name,
kind,
unit,
labels,
label_domains,
buckets,
processes,
max_logical_series: logical,
max_rendered_series: rendered,
description,
}
}
const METRIC_SCHEMA: &[MetricDefinition] = &[
metric(
"crank_http_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["route", "method", "status_class"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
domain("status_class", STATUS),
],
&[],
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10 * 6,
"Total HTTP requests.",
),
metric(
"crank_http_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["route", "method"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
],
DURATION_BUCKETS_SECONDS,
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10,
"HTTP request duration in seconds.",
),
metric(
"crank_http_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"HTTP requests currently being processed.",
),
metric(
"crank_mcp_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["method", "response_mode", "outcome"],
&[
domain("method", MCP_METHODS),
domain("response_mode", RESPONSE_MODES),
domain("outcome", MCP_OUTCOMES),
],
&[],
MCP,
9 * 3 * 7,
"Total MCP JSON-RPC requests.",
),
metric(
"crank_mcp_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["method", "outcome"],
&[
domain("method", MCP_METHODS),
domain("outcome", MCP_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
MCP,
9 * 7,
"MCP JSON-RPC request duration in seconds.",
),
metric(
"crank_mcp_active_sessions",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Active persisted MCP transport sessions.",
),
metric(
"crank_mcp_session_metrics_fresh",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Whether the active-session gauge was refreshed successfully.",
),
metric(
"crank_mcp_active_streams",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"MCP event streams currently being served.",
),
metric(
"crank_tool_invocations_total",
MetricKind::Counter,
MetricUnit::Count,
&["source", "outcome", "error_kind"],
&[
domain("source", SOURCES),
domain("outcome", TOOL_OUTCOMES),
domain("error_kind", TOOL_ERRORS),
],
&[],
BOTH,
3 * 3 * 22,
"Total tool invocations.",
),
metric(
"crank_tool_invocation_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["source", "outcome"],
&[domain("source", SOURCES), domain("outcome", TOOL_OUTCOMES)],
DURATION_BUCKETS_SECONDS,
BOTH,
3 * 3,
"Tool invocation duration in seconds.",
),
metric(
"crank_upstream_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
&[],
BOTH,
13,
"Total upstream requests.",
),
metric(
"crank_upstream_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
BOTH,
13,
"Upstream request duration in seconds.",
),
metric(
"crank_runtime_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Runtime executions currently in progress.",
),
metric(
"crank_runtime_limit_rejections_total",
MetricKind::Counter,
MetricUnit::Count,
&["stage"],
&[domain("stage", LIMIT_STAGES)],
&[],
BOTH,
3,
"Runtime executions rejected by a bounded limit.",
),
metric(
"crank_runtime_cache_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CACHE_OUTCOMES)],
&[],
BOTH,
7,
"Runtime response cache outcomes.",
),
metric(
"crank_idempotency_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", IDEMPOTENCY_OUTCOMES)],
&[],
BOTH,
8,
"Runtime idempotency outcomes.",
),
metric(
"crank_confirmation_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CONFIRMATION_OUTCOMES)],
&[],
BOTH,
5,
"Runtime confirmation outcomes.",
),
metric(
"crank_db_pool_connections",
MetricKind::Gauge,
MetricUnit::Count,
&["state"],
&[domain("state", DB_STATES)],
&[],
BOTH,
2,
"PostgreSQL pool connections by state.",
),
metric(
"crank_catalog_tools",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Tools in the current published catalog.",
),
metric(
"crank_catalog_estimated_context_tokens",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Estimated context tokens in the current published catalog.",
),
metric(
"crank_catalog_warnings",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Warnings in the current published catalog.",
),
metric(
"crank_invocation_history_lost_total",
MetricKind::Counter,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Invocation history records lost after an action completed.",
),
metric(
"crank_telemetry_export_failures_total",
MetricKind::Counter,
MetricUnit::Count,
&["signal_type", "exporter"],
&[
domain("signal_type", SIGNAL_TYPES),
domain("exporter", EXPORTERS),
],
&[],
BOTH,
4,
"Telemetry export failures.",
),
];
pub const fn metric_schema() -> &'static [MetricDefinition] {
METRIC_SCHEMA
}
pub fn metric_schema_for_service(
service: MetricService,
) -> impl Iterator<Item = &'static MetricDefinition> {
METRIC_SCHEMA
.iter()
.filter(move |definition| definition.processes.contains(&service.process()))
}
pub fn schema_budget() -> Result<SchemaBudget, SchemaError> {
validate_schema(METRIC_SCHEMA)
}
pub fn validate_budget(logical: usize, rendered: usize) -> Result<(), SchemaError> {
if logical > MAX_LOGICAL_SERIES_PER_PROCESS || rendered > MAX_RENDERED_SERIES_PER_PROCESS {
Err(SchemaError::BudgetExceeded)
} else {
Ok(())
}
}
pub fn max_exemplar_slots() -> usize {
METRIC_SCHEMA
.iter()
.filter(|definition| definition.kind == MetricKind::Histogram)
.map(|definition| definition.max_logical_series * (definition.buckets.len() + 1))
.sum()
}
pub fn validate_schema(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
if schema.len() > MAX_METRIC_FAMILIES {
return Err(SchemaError::TooManyFamilies);
}
let mut names = BTreeSet::new();
let mut logical = 0usize;
let mut rendered = 0usize;
for item in schema {
if !names.insert(item.name) {
return Err(SchemaError::DuplicateMetric);
}
if !valid_metric_name(item.name)
|| !valid_static_text(item.description)
|| item.processes.is_empty()
|| item.labels.len() > MAX_PRODUCT_LABELS_PER_FAMILY
|| item.labels.len() != item.label_domains.len()
{
return Err(SchemaError::InvalidMetric);
}
let mut labels = BTreeSet::new();
let mut computed = 1usize;
for (label, domain) in item.labels.iter().zip(item.label_domains) {
if *label != domain.name || !valid_label_name(label) || !labels.insert(*label) {
return Err(SchemaError::DuplicateLabel);
}
if domain.class != LabelClass::ProductClosed
|| domain.values.is_empty()
|| domain.values.iter().any(|value| !valid_domain_value(value))
|| domain.values.iter().copied().collect::<BTreeSet<_>>().len()
!= domain.values.len()
{
return Err(SchemaError::InvalidDomain);
}
computed = computed
.checked_mul(domain.values.len())
.ok_or(SchemaError::BudgetExceeded)?;
}
if item.kind == MetricKind::Histogram {
if item.buckets.is_empty()
|| item.buckets.iter().any(|v| !v.is_finite() || *v <= 0.0)
|| item.buckets.windows(2).any(|pair| pair[0] >= pair[1])
{
return Err(SchemaError::InvalidBuckets);
}
} else if !item.buckets.is_empty() {
return Err(SchemaError::InvalidBuckets);
}
let expected_rendered = if item.kind == MetricKind::Histogram {
computed
.checked_mul(item.buckets.len() + 3)
.ok_or(SchemaError::BudgetExceeded)?
} else {
computed
};
if computed != item.max_logical_series || expected_rendered != item.max_rendered_series {
return Err(SchemaError::InvalidCeiling);
}
logical = logical
.checked_add(computed)
.ok_or(SchemaError::BudgetExceeded)?;
rendered = rendered
.checked_add(expected_rendered)
.ok_or(SchemaError::BudgetExceeded)?;
}
validate_budget(logical, rendered)?;
Ok(SchemaBudget {
logical_series: logical,
rendered_series: rendered,
})
}
fn valid_static_text(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= 512
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
fn valid_metric_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
&& name.starts_with("crank_")
}
fn valid_label_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with("__")
&& name
.bytes()
.next()
.is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
&& name
.bytes()
.skip(1)
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
fn valid_domain_value(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 256
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
pub fn render_metric_schema_json() -> Result<String, SchemaError> {
let budget = schema_budget()?;
let mut out = format!(
"{{\n \"schema_version\": {METRIC_SCHEMA_VERSION},\n \"budget\": {{\"logical_series\": {}, \"rendered_series\": {}, \"max_logical_series\": {MAX_LOGICAL_SERIES_PER_PROCESS}, \"max_rendered_series\": {MAX_RENDERED_SERIES_PER_PROCESS}}},\n \"global_labels\": [\n",
budget.logical_series, budget.rendered_series
);
for (index, label) in PROCESS_CONSTANT_LABELS.iter().enumerate() {
out.push_str(&format!(
" {{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}\n",
label.name,
label.class.as_str(),
json_strings(label.values),
comma(index, PROCESS_CONSTANT_LABELS.len())
));
}
out.push_str(" ],\n \"metrics\": [\n");
for (index, item) in METRIC_SCHEMA.iter().enumerate() {
out.push_str(&format!(" {{\"name\": \"{}\", \"kind\": \"{}\", \"unit\": \"{}\", \"help\": \"{}\", \"processes\": [{}], \"labels\": [", item.name, item.kind.as_str(), item.unit.as_str(), item.description, json_processes(item.processes)));
for (label_index, domain) in item.label_domains.iter().enumerate() {
out.push_str(&format!(
"{{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}",
domain.name,
domain.class.as_str(),
json_strings(domain.values),
comma(label_index, item.label_domains.len())
));
}
out.push_str(&format!("], \"buckets_seconds\": [{}], \"max_logical_series\": {}, \"max_rendered_series\": {}}}{}\n", item.buckets.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "), item.max_logical_series, item.max_rendered_series, comma(index, METRIC_SCHEMA.len())));
}
out.push_str(" ]\n}\n");
Ok(out)
}
fn json_strings(values: &[&str]) -> String {
values
.iter()
.map(|value| format!("\"{value}\""))
.collect::<Vec<_>>()
.join(", ")
}
fn json_processes(values: &[MetricProcess]) -> String {
values
.iter()
.map(|value| format!("\"{}\"", value.as_str()))
.collect::<Vec<_>>()
.join(", ")
}
const fn comma(index: usize, len: usize) -> &'static str {
if index + 1 == len { "" } else { "," }
}
+262
View File
@@ -0,0 +1,262 @@
//! Checked-арифметика бюджетов серий/exemplar, структурная валидация и
//! per-process ceilings.
use std::collections::BTreeSet;
use super::descriptor::{
LabelClass, MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS,
METRIC_SCHEMA, MetricDefinition, MetricKind, MetricService,
};
use super::projection::service_projection;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchemaBudget {
pub logical_series: usize,
pub rendered_series: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SchemaError {
TooManyFamilies,
DuplicateMetric,
InvalidMetric,
DuplicateLabel,
InvalidDomain,
InvalidBuckets,
InvalidCeiling,
BudgetExceeded,
}
#[derive(Debug, Eq, PartialEq)]
pub enum MetricBindingError {
InvalidSchema,
ConflictingService,
}
/// Checked series budget of one candidate family: the product of its
/// label-domain sizes and, for histograms, the `buckets + 3` rendered sample
/// lines per logical series. Overflow is a typed budget failure; the closed
/// schema never saturates and never reports a truncated count.
pub(crate) fn checked_series_budget<I>(
domain_sizes: I,
kind: MetricKind,
bucket_count: usize,
) -> Result<SchemaBudget, SchemaError>
where
I: IntoIterator<Item = usize>,
{
let logical_series = domain_sizes
.into_iter()
.try_fold(1_usize, |product, size| {
product.checked_mul(size).ok_or(SchemaError::BudgetExceeded)
})?;
if kind != MetricKind::Histogram {
return Ok(SchemaBudget {
logical_series,
rendered_series: logical_series,
});
}
let rendered_per_series = bucket_count
.checked_add(3)
.ok_or(SchemaError::BudgetExceeded)?;
let rendered_series = logical_series
.checked_mul(rendered_per_series)
.ok_or(SchemaError::BudgetExceeded)?;
Ok(SchemaBudget {
logical_series,
rendered_series,
})
}
/// Checked exemplar slots of one family (`L x (buckets + 1)`): an overflow is a
/// typed budget failure, never a wrapped slot count.
pub(crate) fn checked_exemplar_slots(
kind: MetricKind,
logical_series: usize,
bucket_count: usize,
) -> Result<usize, SchemaError> {
if kind != MetricKind::Histogram {
return Ok(0);
}
let buckets = bucket_count
.checked_add(1)
.ok_or(SchemaError::BudgetExceeded)?;
logical_series
.checked_mul(buckets)
.ok_or(SchemaError::BudgetExceeded)
}
/// Checked exemplar capacity of one service projection. `None` means the
/// projection's arithmetic overflowed, so every caller can fail closed (no
/// exemplar growth) instead of recording under a saturated capacity.
pub(crate) fn checked_exemplar_capacity(service: MetricService) -> Option<usize> {
service_projection(service)
.iter()
.try_fold(0_usize, |total, definition| {
checked_exemplar_slots(
definition.kind,
definition.max_logical_series,
definition.buckets.len(),
)
.ok()
.and_then(|slots| total.checked_add(slots))
})
}
pub fn validate_budget(logical: usize, rendered: usize) -> Result<(), SchemaError> {
if logical > MAX_LOGICAL_SERIES_PER_PROCESS || rendered > MAX_RENDERED_SERIES_PER_PROCESS {
Err(SchemaError::BudgetExceeded)
} else {
Ok(())
}
}
pub fn validate_exemplar_budget(slots: usize) -> Result<(), SchemaError> {
if slots > MAX_EXEMPLAR_SLOTS_PER_PROCESS {
Err(SchemaError::BudgetExceeded)
} else {
Ok(())
}
}
/// Structural validation of exactly one projected schema, including the
/// per-process ceilings. It must never be applied to the union descriptors.
pub fn validate_schema(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
let budget = validate_structure(schema)?;
validate_budget(budget.logical_series, budget.rendered_series)?;
let exemplars = schema.iter().try_fold(0_usize, |total, definition| {
let slots = checked_exemplar_slots(
definition.kind,
definition.max_logical_series,
definition.buckets.len(),
)?;
total.checked_add(slots).ok_or(SchemaError::BudgetExceeded)
})?;
validate_exemplar_budget(exemplars)?;
Ok(budget)
}
/// Structural validation without any sum ceiling (used for the union metadata
/// and reused by the renderer before it validates every service projection).
fn validate_structure(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
if schema.len() > MAX_METRIC_FAMILIES {
return Err(SchemaError::TooManyFamilies);
}
let mut names = BTreeSet::new();
let mut logical = 0usize;
let mut rendered = 0usize;
for item in schema {
if !names.insert(item.name) {
return Err(SchemaError::DuplicateMetric);
}
if !valid_metric_name(item.name)
|| !valid_static_text(item.description)
|| item.processes.is_empty()
|| item.labels.len() > MAX_PRODUCT_LABELS_PER_FAMILY
|| item.labels.len() != item.label_domains.len()
{
return Err(SchemaError::InvalidMetric);
}
let mut owners = BTreeSet::new();
for owner in item.processes {
if !owners.insert(*owner) {
return Err(SchemaError::InvalidMetric);
}
}
let mut labels = BTreeSet::new();
for (label, domain) in item.labels.iter().zip(item.label_domains) {
if *label != domain.name || !valid_label_name(label) || !labels.insert(*label) {
return Err(SchemaError::DuplicateLabel);
}
if domain.class != LabelClass::ProductClosed
|| domain.values.is_empty()
|| domain.values.iter().any(|value| !valid_domain_value(value))
|| domain.values.iter().copied().collect::<BTreeSet<_>>().len()
!= domain.values.len()
{
return Err(SchemaError::InvalidDomain);
}
}
if item.kind == MetricKind::Histogram {
if item.buckets.is_empty()
|| item.buckets.iter().any(|v| !v.is_finite() || *v <= 0.0)
|| item.buckets.windows(2).any(|pair| pair[0] >= pair[1])
{
return Err(SchemaError::InvalidBuckets);
}
} else if !item.buckets.is_empty() {
return Err(SchemaError::InvalidBuckets);
}
// Единственная checked-арифметика серий: переполнение домена или
// rendered-серий обязано быть типизированным BudgetExceeded, а не
// насыщенным «почти верным» значением.
let budget = checked_series_budget(
item.label_domains.iter().map(|domain| domain.values.len()),
item.kind,
item.buckets.len(),
)?;
if budget.logical_series != item.max_logical_series
|| budget.rendered_series != item.max_rendered_series
{
return Err(SchemaError::InvalidCeiling);
}
logical = logical
.checked_add(budget.logical_series)
.ok_or(SchemaError::BudgetExceeded)?;
rendered = rendered
.checked_add(budget.rendered_series)
.ok_or(SchemaError::BudgetExceeded)?;
}
Ok(SchemaBudget {
logical_series: logical,
rendered_series: rendered,
})
}
/// Validates the union structure plus **every** service projection. Union
/// totals are deliberately not compared against the per-process ceilings.
pub fn validate_all_projections() -> Result<(), SchemaError> {
validate_structure(METRIC_SCHEMA)?;
validate_schema(service_projection(MetricService::AdminApi))?;
validate_schema(service_projection(MetricService::McpServer))?;
Ok(())
}
fn valid_static_text(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= 512
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
fn valid_metric_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
&& name.starts_with("crank_")
}
fn valid_label_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with("__")
&& name
.bytes()
.next()
.is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
&& name
.bytes()
.skip(1)
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
fn valid_domain_value(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 256
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
@@ -0,0 +1,105 @@
//! Checked-арифметика серий и exemplar-слотов: типизированное переполнение
//! вместо насыщения (TD-M5).
use super::budget::{
SchemaBudget, SchemaError, checked_exemplar_capacity, checked_exemplar_slots,
checked_series_budget,
};
use super::descriptor::{MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricKind, MetricService};
use super::projection::{max_exemplar_slots, service_projection};
/// TD-M5 — реальное целочисленное переполнение checked-seam'а обязано быть
/// типизированным `BudgetExceeded`, а не насыщенным/усечённым счётчиком.
/// Фикстура — только размеры доменов, поэтому enormous-аллокаций нет.
#[test]
fn checked_seam_reports_overflow_typed_and_never_saturates() {
// Логический product переполняется.
assert_eq!(
checked_series_budget([usize::MAX, 2], MetricKind::Counter, 0),
Err(SchemaError::BudgetExceeded)
);
// Граница: ровно представимый product остаётся принятым (без saturation).
assert_eq!(
checked_series_budget([usize::MAX, 1], MetricKind::Counter, 0),
Ok(SchemaBudget {
logical_series: usize::MAX,
rendered_series: usize::MAX,
})
);
// Rendered product переполняется при корректном logical.
assert_eq!(
checked_series_budget([usize::MAX / 4, 2], MetricKind::Histogram, 13),
Err(SchemaError::BudgetExceeded)
);
// `buckets + 3` само переполняется.
assert_eq!(
checked_series_budget([1], MetricKind::Histogram, usize::MAX),
Err(SchemaError::BudgetExceeded)
);
// Нормальный histogram считается точно (13 buckets → 16 rendered).
assert_eq!(
checked_series_budget([7, 2], MetricKind::Histogram, 13),
Ok(SchemaBudget {
logical_series: 14,
rendered_series: 224,
})
);
// Пустой домен: один logical series, как у gauge без labels.
assert_eq!(
checked_series_budget(std::iter::empty::<usize>(), MetricKind::Gauge, 0),
Ok(SchemaBudget {
logical_series: 1,
rendered_series: 1,
})
);
}
/// TD-M5 — exemplar-слоты считаются checked, capacity fail-closed.
#[test]
fn checked_exemplar_slots_and_capacity_are_typed_and_bounded() {
assert_eq!(
checked_exemplar_slots(MetricKind::Histogram, usize::MAX, 13),
Err(SchemaError::BudgetExceeded)
);
assert_eq!(
checked_exemplar_slots(MetricKind::Histogram, usize::MAX / 2, 2),
Err(SchemaError::BudgetExceeded)
);
assert_eq!(
checked_exemplar_slots(MetricKind::Histogram, 1, usize::MAX),
Err(SchemaError::BudgetExceeded)
);
assert_eq!(
checked_exemplar_slots(MetricKind::Counter, usize::MAX, 13),
Ok(0)
);
// 4 series x (13 finite buckets + 1 Inf) = 56 слотов, без saturation.
assert_eq!(checked_exemplar_slots(MetricKind::Histogram, 4, 13), Ok(56));
// Реальная проекция остаётся в frozen-границах.
assert_eq!(
checked_exemplar_capacity(MetricService::AdminApi),
Some(12_348)
);
assert_eq!(
checked_exemplar_capacity(MetricService::McpServer),
Some(2_310)
);
assert_eq!(
max_exemplar_slots(MetricService::AdminApi),
MAX_EXEMPLAR_SLOTS_PER_PROCESS
);
for service in [MetricService::AdminApi, MetricService::McpServer] {
for definition in service_projection(service) {
assert_ne!(definition.max_logical_series, usize::MAX);
assert_eq!(
definition.max_exemplar_slots(),
checked_exemplar_slots(
definition.kind,
definition.max_logical_series,
definition.buckets.len()
)
.expect("projected exemplar slots are in range")
);
}
}
}
@@ -0,0 +1,520 @@
//! Закрытые дескрипторы метрик: kind/unit/process/service, домены labels и
//! `METRIC_SCHEMA` (union-таблица метадат, не бюджет процесса).
use super::routes::{BOTH, HTTP_ROUTE_DOMAIN, MCP};
use crate::labels::{
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpStatusClass,
IdempotencyOutcome, InvocationSource, LimitStage, McpMethod, McpOutcome, McpResponseMode,
SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
};
pub const METRIC_SCHEMA_VERSION: u32 = 2;
pub const MAX_METRIC_FAMILIES: usize = 128;
pub const MAX_PRODUCT_LABELS_PER_FAMILY: usize = 4;
pub const MAX_LOGICAL_SERIES_PER_PROCESS: usize = 6_285;
pub const MAX_RENDERED_SERIES_PER_PROCESS: usize = 19_515;
pub const MAX_EXEMPLAR_SLOTS_PER_PROCESS: usize = 12_348;
pub const MAX_EXPOSITION_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
}
impl MetricKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Counter => "counter",
Self::Gauge => "gauge",
Self::Histogram => "histogram",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricUnit {
Count,
Seconds,
}
impl MetricUnit {
pub const fn as_str(self) -> &'static str {
match self {
Self::Count => "count",
Self::Seconds => "seconds",
}
}
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MetricProcess {
AdminApi,
McpServer,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricService {
AdminApi,
McpServer,
}
impl MetricService {
pub fn parse(value: &str) -> Option<Self> {
match value {
"admin-api" => Some(Self::AdminApi),
"mcp-server" => Some(Self::McpServer),
_ => None,
}
}
pub const fn process(self) -> MetricProcess {
match self {
Self::AdminApi => MetricProcess::AdminApi,
Self::McpServer => MetricProcess::McpServer,
}
}
}
impl MetricProcess {
pub const fn as_str(self) -> &'static str {
match self {
Self::AdminApi => "admin_api",
Self::McpServer => "mcp_server",
}
}
pub const fn service(self) -> MetricService {
match self {
Self::AdminApi => MetricService::AdminApi,
Self::McpServer => MetricService::McpServer,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LabelClass {
ProductClosed,
ProcessConstant,
}
impl LabelClass {
pub const fn as_str(self) -> &'static str {
match self {
Self::ProductClosed => "product_closed",
Self::ProcessConstant => "process_constant",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LabelDomain {
pub name: &'static str,
pub class: LabelClass,
pub values: &'static [&'static str],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MetricDefinition {
pub name: &'static str,
pub kind: MetricKind,
pub unit: MetricUnit,
pub labels: &'static [&'static str],
pub label_domains: &'static [LabelDomain],
pub buckets: &'static [f64],
pub processes: &'static [MetricProcess],
pub max_logical_series: usize,
pub max_rendered_series: usize,
pub description: &'static str,
}
impl MetricDefinition {
/// `E(m, p)` — exemplar slots contributed by this family inside one process
/// projection. Histograms hold `L x (finite_buckets + 1)` latest-per-bucket
/// observations; counters/gauges hold none. The multiply is checked: an
/// overflowing definition (one that already failed the checked seam) fails
/// loudly instead of returning a saturated or truncated count.
pub const fn max_exemplar_slots(&self) -> usize {
if !matches!(self.kind, MetricKind::Histogram) {
return 0;
}
match self.max_logical_series.checked_mul(self.buckets.len() + 1) {
Some(slots) => slots,
None => panic!("exemplar slot arithmetic overflowed a validated definition"),
}
}
}
pub const DURATION_BUCKETS_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
];
pub const PROCESS_CONSTANT_LABELS: &[LabelDomain] = &[
LabelDomain {
name: "service",
class: LabelClass::ProcessConstant,
values: &["admin-api", "mcp-server"],
},
LabelDomain {
name: "version",
class: LabelClass::ProcessConstant,
values: &["validated_release_identity"],
},
LabelDomain {
name: "environment",
class: LabelClass::ProcessConstant,
values: &["validated_startup_value"],
},
];
const METHODS: &[&str] = HttpMethod::VALUES;
const STATUS: &[&str] = HttpStatusClass::VALUES;
const MCP_METHODS: &[&str] = McpMethod::VALUES;
const RESPONSE_MODES: &[&str] = McpResponseMode::VALUES;
const MCP_OUTCOMES: &[&str] = McpOutcome::VALUES;
const SOURCES: &[&str] = InvocationSource::VALUES;
const TOOL_OUTCOMES: &[&str] = ToolOutcome::VALUES;
const TOOL_ERRORS: &[&str] = ToolErrorKind::VALUES;
const OPERATION_KINDS: &[&str] = UpstreamOperationKind::VALUES;
const UPSTREAM_OUTCOMES: &[&str] = UpstreamOutcome::VALUES;
const LIMIT_STAGES: &[&str] = LimitStage::VALUES;
const CACHE_OUTCOMES: &[&str] = CacheOutcome::VALUES;
const IDEMPOTENCY_OUTCOMES: &[&str] = IdempotencyOutcome::VALUES;
const CONFIRMATION_OUTCOMES: &[&str] = ConfirmationOutcome::VALUES;
const DB_STATES: &[&str] = DbPoolState::VALUES;
const SIGNAL_TYPES: &[&str] = SignalType::VALUES;
const EXPORTERS: &[&str] = Exporter::VALUES;
const fn domain(name: &'static str, values: &'static [&'static str]) -> LabelDomain {
LabelDomain {
name,
class: LabelClass::ProductClosed,
values,
}
}
#[allow(
clippy::too_many_arguments,
reason = "the canonical descriptor keeps every metric contract dimension explicit"
)]
const fn metric(
name: &'static str,
kind: MetricKind,
unit: MetricUnit,
labels: &'static [&'static str],
label_domains: &'static [LabelDomain],
buckets: &'static [f64],
processes: &'static [MetricProcess],
logical: usize,
description: &'static str,
) -> MetricDefinition {
let rendered = if matches!(kind, MetricKind::Histogram) {
logical * (buckets.len() + 3)
} else {
logical
};
MetricDefinition {
name,
kind,
unit,
labels,
label_domains,
buckets,
processes,
max_logical_series: logical,
max_rendered_series: rendered,
description,
}
}
/// Union descriptors: the route domain is the whole union and `max_*` are the
/// union Cartesian metadata used for structural diagnostics, **not** a process
/// budget. Real per-process data lives in the service projections.
pub(crate) const METRIC_SCHEMA: &[MetricDefinition] = &[
metric(
"crank_http_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["route", "method", "status_class"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
domain("status_class", STATUS),
],
&[],
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10 * 6,
"Total HTTP requests.",
),
metric(
"crank_http_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["route", "method"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
],
DURATION_BUCKETS_SECONDS,
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10,
"HTTP request duration in seconds.",
),
metric(
"crank_http_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"HTTP requests currently being processed.",
),
metric(
"crank_mcp_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["method", "response_mode", "outcome"],
&[
domain("method", MCP_METHODS),
domain("response_mode", RESPONSE_MODES),
domain("outcome", MCP_OUTCOMES),
],
&[],
MCP,
9 * 3 * 7,
"Total MCP JSON-RPC requests.",
),
metric(
"crank_mcp_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["method", "outcome"],
&[
domain("method", MCP_METHODS),
domain("outcome", MCP_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
MCP,
9 * 7,
"MCP JSON-RPC request duration in seconds.",
),
metric(
"crank_mcp_active_sessions",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Active persisted MCP transport sessions.",
),
metric(
"crank_mcp_session_metrics_fresh",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Whether the active-session gauge was refreshed successfully.",
),
metric(
"crank_mcp_active_streams",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"MCP event streams currently being served.",
),
metric(
"crank_tool_invocations_total",
MetricKind::Counter,
MetricUnit::Count,
&["source", "outcome", "error_kind"],
&[
domain("source", SOURCES),
domain("outcome", TOOL_OUTCOMES),
domain("error_kind", TOOL_ERRORS),
],
&[],
BOTH,
3 * 3 * 22,
"Total tool invocations.",
),
metric(
"crank_tool_invocation_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["source", "outcome"],
&[domain("source", SOURCES), domain("outcome", TOOL_OUTCOMES)],
DURATION_BUCKETS_SECONDS,
BOTH,
3 * 3,
"Tool invocation duration in seconds.",
),
metric(
"crank_upstream_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
&[],
BOTH,
13,
"Total upstream requests.",
),
metric(
"crank_upstream_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
BOTH,
13,
"Upstream request duration in seconds.",
),
metric(
"crank_runtime_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Runtime executions currently in progress.",
),
metric(
"crank_runtime_limit_rejections_total",
MetricKind::Counter,
MetricUnit::Count,
&["stage"],
&[domain("stage", LIMIT_STAGES)],
&[],
BOTH,
3,
"Runtime executions rejected by a bounded limit.",
),
metric(
"crank_runtime_cache_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CACHE_OUTCOMES)],
&[],
BOTH,
7,
"Runtime response cache outcomes.",
),
metric(
"crank_idempotency_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", IDEMPOTENCY_OUTCOMES)],
&[],
BOTH,
8,
"Runtime idempotency outcomes.",
),
metric(
"crank_confirmation_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CONFIRMATION_OUTCOMES)],
&[],
BOTH,
5,
"Runtime confirmation outcomes.",
),
metric(
"crank_db_pool_connections",
MetricKind::Gauge,
MetricUnit::Count,
&["state"],
&[domain("state", DB_STATES)],
&[],
BOTH,
2,
"PostgreSQL pool connections by state.",
),
metric(
"crank_catalog_tools",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Tools in the current published catalog.",
),
metric(
"crank_catalog_estimated_context_tokens",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Estimated context tokens in the current published catalog.",
),
metric(
"crank_catalog_warnings",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Warnings in the current published catalog.",
),
metric(
"crank_invocation_history_lost_total",
MetricKind::Counter,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Invocation history records lost after an action completed.",
),
metric(
"crank_telemetry_export_failures_total",
MetricKind::Counter,
MetricUnit::Count,
&["signal_type", "exporter"],
&[
domain("signal_type", SIGNAL_TYPES),
domain("exporter", EXPORTERS),
],
&[],
BOTH,
4,
"Telemetry export failures.",
),
];
/// Union descriptors (`metadata`, not a budget).
pub const fn metric_schema() -> &'static [MetricDefinition] {
METRIC_SCHEMA
}
@@ -0,0 +1,86 @@
//! Ленивые per-service проекции union-таблицы: один раз посчитанный
//! checked-бюджет на процесс, без per-request аллокаций.
use std::sync::OnceLock;
use super::budget::{
SchemaBudget, SchemaError, checked_exemplar_capacity, checked_series_budget, validate_schema,
};
use super::descriptor::{LabelDomain, METRIC_SCHEMA, MetricDefinition, MetricService};
use super::routes::service_route_domain;
fn build_projection(service: MetricService) -> Result<&'static [MetricDefinition], SchemaError> {
let route_values = service_route_domain(service);
let mut definitions = Vec::new();
for definition in METRIC_SCHEMA {
if !definition.processes.contains(&service.process()) {
continue;
}
let label_domains: &'static [LabelDomain] = Box::leak(
definition
.label_domains
.iter()
.map(|label_domain| {
if label_domain.name == "route" {
LabelDomain {
values: route_values,
..*label_domain
}
} else {
*label_domain
}
})
.collect::<Vec<_>>()
.into_boxed_slice(),
);
let budget = checked_series_budget(
label_domains
.iter()
.map(|label_domain| label_domain.values.len()),
definition.kind,
definition.buckets.len(),
)?;
definitions.push(MetricDefinition {
label_domains,
max_logical_series: budget.logical_series,
max_rendered_series: budget.rendered_series,
..*definition
});
}
Ok(Box::leak(definitions.into_boxed_slice()))
}
static ADMIN_PROJECTION: OnceLock<&'static [MetricDefinition]> = OnceLock::new();
static MCP_PROJECTION: OnceLock<&'static [MetricDefinition]> = OnceLock::new();
/// Derived projection cache initialized once per service (no per-request allocation).
/// The static schema is a compile-time constant, so a checked-seam overflow here
/// is a programming error: it fails loudly instead of publishing a saturated or
/// truncated series budget.
pub fn service_projection(service: MetricService) -> &'static [MetricDefinition] {
let cache = match service {
MetricService::AdminApi => &ADMIN_PROJECTION,
MetricService::McpServer => &MCP_PROJECTION,
};
cache.get_or_init(|| match build_projection(service) {
Ok(projection) => projection,
Err(error) => {
panic!("static metric projection must satisfy the checked schema seam: {error:?}")
}
})
}
pub fn metric_schema_for_service(
service: MetricService,
) -> impl Iterator<Item = &'static MetricDefinition> {
service_projection(service).iter()
}
pub fn schema_budget(service: MetricService) -> Result<SchemaBudget, SchemaError> {
validate_schema(service_projection(service))
}
pub fn max_exemplar_slots(service: MetricService) -> usize {
checked_exemplar_capacity(service)
.expect("validated service projection must carry a bounded exemplar budget")
}
@@ -0,0 +1,171 @@
//! Детерминированный компактный v2-снимок реестра
//! (`docs/schemas/metrics-registry-v2.json`).
use super::budget::{
SchemaError, checked_exemplar_slots, validate_all_projections, validate_schema,
};
use super::descriptor::{
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_METRIC_FAMILIES, MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS,
METRIC_SCHEMA, METRIC_SCHEMA_VERSION, MetricProcess, PROCESS_CONSTANT_LABELS,
};
use super::projection::service_projection;
use super::routes::HTTP_ROUTES;
/// Deterministic compact v2 registry snapshot (Rust descriptor table is the
/// only generator). Every service projection is validated before rendering.
pub fn render_metric_schema_json() -> Result<String, SchemaError> {
validate_all_projections()?;
let mut out = String::with_capacity(20 * 1024);
out.push_str("{\"schema_version\":");
out.push_str(&METRIC_SCHEMA_VERSION.to_string());
out.push_str(",\"limits\":{\"max_families\":");
out.push_str(&MAX_METRIC_FAMILIES.to_string());
out.push_str(",\"max_product_labels_per_family\":");
out.push_str(&MAX_PRODUCT_LABELS_PER_FAMILY.to_string());
out.push_str(",\"max_logical_series\":");
out.push_str(&MAX_LOGICAL_SERIES_PER_PROCESS.to_string());
out.push_str(",\"max_rendered_series\":");
out.push_str(&MAX_RENDERED_SERIES_PER_PROCESS.to_string());
out.push_str(",\"max_exemplar_slots\":");
out.push_str(&MAX_EXEMPLAR_SLOTS_PER_PROCESS.to_string());
out.push_str(",\"max_exposition_bytes\":");
out.push_str(&MAX_EXPOSITION_BYTES.to_string());
out.push_str("},\"global_labels\":[");
for (index, label) in PROCESS_CONSTANT_LABELS.iter().enumerate() {
comma(&mut out, index);
out.push_str("{\"name\":\"");
out.push_str(label.name);
out.push_str("\",\"class\":\"");
out.push_str(label.class.as_str());
out.push_str("\",\"domain\":[");
out.push_str(&json_strings(label.values));
out.push_str("]}");
}
out.push_str("],\"http_routes\":[");
for (index, route) in HTTP_ROUTES.iter().enumerate() {
comma(&mut out, index);
out.push_str("{\"route\":\"");
out.push_str(route.route);
out.push_str("\",\"processes\":[");
out.push_str(&json_processes(route.processes));
out.push_str("]}");
}
out.push_str("],\"metrics\":[");
for (index, definition) in METRIC_SCHEMA.iter().enumerate() {
comma(&mut out, index);
out.push_str("{\"name\":\"");
out.push_str(definition.name);
out.push_str("\",\"kind\":\"");
out.push_str(definition.kind.as_str());
out.push_str("\",\"unit\":\"");
out.push_str(definition.unit.as_str());
out.push_str("\",\"help\":\"");
out.push_str(definition.description);
out.push_str("\",\"processes\":[");
out.push_str(&json_processes(definition.processes));
out.push_str("],\"labels\":[");
for (label_index, label_domain) in definition.label_domains.iter().enumerate() {
comma(&mut out, label_index);
out.push_str("{\"name\":\"");
out.push_str(label_domain.name);
out.push_str("\",\"class\":\"");
out.push_str(label_domain.class.as_str());
if label_domain.name == "route" {
out.push_str("\",\"domain_ref\":\"http_routes\"}");
} else {
out.push_str("\",\"domain\":[");
out.push_str(&json_strings(label_domain.values));
out.push_str("]}");
}
}
out.push_str("],\"buckets_seconds\":[");
out.push_str(&json_numbers(definition.buckets));
out.push_str("],\"bounds\":[");
for (bound_index, process) in definition.processes.iter().enumerate() {
comma(&mut out, bound_index);
out.push_str(&bound_json(*process, definition.name)?);
}
out.push_str("]}");
}
out.push_str("],\"budgets\":[");
for (index, process) in [MetricProcess::AdminApi, MetricProcess::McpServer]
.iter()
.enumerate()
{
comma(&mut out, index);
let projection = service_projection(process.service());
let budget = validate_schema(projection)?;
let exemplars = projection.iter().try_fold(0_usize, |total, definition| {
let slots = checked_exemplar_slots(
definition.kind,
definition.max_logical_series,
definition.buckets.len(),
)?;
total.checked_add(slots).ok_or(SchemaError::BudgetExceeded)
})?;
out.push_str("{\"process\":\"");
out.push_str(process.as_str());
out.push_str("\",\"families\":");
out.push_str(&projection.len().to_string());
out.push_str(",\"logical_series\":");
out.push_str(&budget.logical_series.to_string());
out.push_str(",\"rendered_series\":");
out.push_str(&budget.rendered_series.to_string());
out.push_str(",\"exemplar_slots\":");
out.push_str(&exemplars.to_string());
out.push('}');
}
out.push_str("]}\n");
Ok(out)
}
fn bound_json(process: MetricProcess, name: &str) -> Result<String, SchemaError> {
let projection = service_projection(process.service());
let definition = projection
.iter()
.find(|definition| definition.name == name)
.expect("validated projection declares every family it owns");
let exemplars = checked_exemplar_slots(
definition.kind,
definition.max_logical_series,
definition.buckets.len(),
)?;
Ok(format!(
"{{\"process\":\"{}\",\"logical_series\":{},\"rendered_series\":{},\"exemplar_slots\":{}}}",
process.as_str(),
definition.max_logical_series,
definition.max_rendered_series,
exemplars
))
}
fn json_strings(values: &[&str]) -> String {
values
.iter()
.map(|value| format!("\"{value}\""))
.collect::<Vec<_>>()
.join(",")
}
fn json_numbers(values: &[f64]) -> String {
values
.iter()
.map(|value| value.to_string())
.collect::<Vec<_>>()
.join(",")
}
fn json_processes(values: &[MetricProcess]) -> String {
values
.iter()
.map(|value| format!("\"{}\"", value.as_str()))
.collect::<Vec<_>>()
.join(",")
}
fn comma(out: &mut String, index: usize) {
if index > 0 {
out.push(',');
}
}
+497
View File
@@ -0,0 +1,497 @@
//! Единственная вручную поддерживаемая таблица route+owners (`HTTP_ROUTES`) и
//! производные от неё домены (union и две сервисные проекции).
use std::collections::BTreeSet;
use super::budget::SchemaError;
use super::descriptor::{MetricProcess, MetricService};
pub(crate) const BOTH: &[MetricProcess] = &[MetricProcess::AdminApi, MetricProcess::McpServer];
pub(crate) const MCP: &[MetricProcess] = &[MetricProcess::McpServer];
/// One row of the single manually maintained route/ownership truth.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HttpRouteDefinition {
pub route: &'static str,
pub processes: &'static [MetricProcess],
}
const fn process_matches(value: MetricProcess, expected: MetricProcess) -> bool {
matches!(
(value, expected),
(MetricProcess::AdminApi, MetricProcess::AdminApi)
| (MetricProcess::McpServer, MetricProcess::McpServer)
)
}
const fn owners_contain(row: &HttpRouteDefinition, process: MetricProcess) -> bool {
let mut index = 0;
while index < row.processes.len() {
if process_matches(row.processes[index], process) {
return true;
}
index += 1;
}
false
}
const fn project_route_count(process: MetricProcess) -> usize {
let mut count = 0;
let mut index = 0;
while index < HTTP_ROUTES.len() {
if owners_contain(&HTTP_ROUTES[index], process) {
count += 1;
}
index += 1;
}
count
}
const fn project_route_domain<const N: usize>(process: MetricProcess) -> [&'static str; N] {
let mut routes = [""; N];
let mut index = 0;
let mut next = 0;
while index < HTTP_ROUTES.len() {
if owners_contain(&HTTP_ROUTES[index], process) {
routes[next] = HTTP_ROUTES[index].route;
next += 1;
}
index += 1;
}
routes
}
/// Union route domain (`91`) derived from the single ownership table.
pub const HTTP_ROUTE_DOMAIN: &[&str] = &union_route_domain_array();
const fn union_route_domain_array() -> [&'static str; HTTP_ROUTES.len()] {
let mut routes = [""; HTTP_ROUTES.len()];
let mut index = 0;
while index < HTTP_ROUTES.len() {
routes[index] = HTTP_ROUTES[index].route;
index += 1;
}
routes
}
const ADMIN_ROUTE_COUNT: usize = project_route_count(MetricProcess::AdminApi);
const MCP_ROUTE_COUNT: usize = project_route_count(MetricProcess::McpServer);
pub const ADMIN_HTTP_ROUTE_DOMAIN: &[&str] =
&project_route_domain::<ADMIN_ROUTE_COUNT>(MetricProcess::AdminApi);
pub const MCP_HTTP_ROUTE_DOMAIN: &[&str] =
&project_route_domain::<MCP_ROUTE_COUNT>(MetricProcess::McpServer);
/// The single manually maintained route+owners enumeration. Sorted by ASCII
/// route; `unmatched` is the last row. Every other domain (union and the two
/// service projections) is derived from this table.
pub const HTTP_ROUTES: &[HttpRouteDefinition] = &[
HttpRouteDefinition {
route: "/api/admin/capabilities",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/tool-search/preview",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/approvals",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/auth-profiles",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/preview",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/logs",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/logs/export.csv",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/logs/{log_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/onboarding",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/onboarding/events",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/onboarding/import-context",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/onboarding/reset-selection",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/onboarding/select-draft",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/analyze-quality",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/import",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/{version}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts/import",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/preview",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/versions/{version}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/import",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/archive",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/content",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/preview",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/publish",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/revoke",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/test-runs",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/content",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/export",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/secrets",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/secrets/{secret_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/secrets/{secret_id}/rotate",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/upstreams",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/upstreams/{upstream_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/usage",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/usage/agents/{agent_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/usage/export.csv",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/admin/workspaces/{workspace_id}/usage/operations/{operation_id}",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/bootstrap/complete",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/bootstrap/status",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/login",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/logout",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/password",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/profile",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/session",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/api/auth/session/csrf",
processes: &[MetricProcess::AdminApi],
},
HttpRouteDefinition {
route: "/health",
processes: BOTH,
},
HttpRouteDefinition {
route: "/ready",
processes: BOTH,
},
HttpRouteDefinition {
route: "/v1/{workspace_slug}/{agent_slug}",
processes: &[MetricProcess::McpServer],
},
HttpRouteDefinition {
route: "/v1/{workspace_slug}/{agent_slug}/approvals",
processes: &[MetricProcess::McpServer],
},
HttpRouteDefinition {
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
processes: &[MetricProcess::McpServer],
},
HttpRouteDefinition {
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
processes: &[MetricProcess::McpServer],
},
HttpRouteDefinition {
route: "/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
processes: &[MetricProcess::McpServer],
},
HttpRouteDefinition {
route: "unmatched",
processes: BOTH,
},
];
/// Structural validation of one candidate ownership table (used to reject
/// duplicated routes, empty owner sets and duplicate owners in reviews/mutation
/// tests). The production table itself is a `const`, so this is the typed gate
/// that proves the same invariants on any candidate.
pub fn validate_http_routes(routes: &[HttpRouteDefinition]) -> Result<(), SchemaError> {
if routes.is_empty() {
return Err(SchemaError::InvalidDomain);
}
let mut seen = BTreeSet::new();
for row in routes {
if !seen.insert(row.route) {
return Err(SchemaError::DuplicateMetric);
}
if row.processes.is_empty() || row.processes.len() > 2 {
return Err(SchemaError::InvalidMetric);
}
let mut owners = BTreeSet::new();
for owner in row.processes {
if !owners.insert(*owner) {
return Err(SchemaError::InvalidMetric);
}
}
}
if !seen.contains("unmatched") {
return Err(SchemaError::InvalidDomain);
}
Ok(())
}
/// Owners of one declared route template (`None` = not a declared template).
pub fn http_route_processes(route: &str) -> Option<&'static [MetricProcess]> {
HTTP_ROUTES
.iter()
.find(|definition| definition.route == route)
.map(|definition| definition.processes)
}
pub(crate) fn service_route_domain(service: MetricService) -> &'static [&'static str] {
match service {
MetricService::AdminApi => ADMIN_HTTP_ROUTE_DOMAIN,
MetricService::McpServer => MCP_HTTP_ROUTE_DOMAIN,
}
}
+295
View File
@@ -0,0 +1,295 @@
//! Story 3.6 · AT-3.6-08 · фаза B — service binding и exact wrong-tuple policy.
//!
//! Binding процесса — это `OnceLock`, а не per-request состояние, поэтому
//! каждый сценарий, требующий другого сервиса (или вообще отсутствия binding),
//! исполняется в **fresh child** того же тест-бинаря: глобальный reset/rebind
//! отсутствует by design (CONTRACT §4/§5, фикстура F2).
//!
//! `TD-B1` unbound facade — безопасный no-op.
//! `TD-B2` повтор того же сервиса идемпотентен.
//! `TD-B3` конфликт разных сервисов: ровно один winner, loser — `ConflictingService`.
//! `TD-B4` known route чужого сервиса пишется как `unmatched` (counter+duration).
//! `TD-B5` прямой exemplar не может создать ключ чужого route.
use std::collections::BTreeSet;
use std::time::Duration;
use crank_metrics::{
ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
MetricBindingError, MetricService, bound_metric_service, exemplar_snapshot,
record_cache_outcome, record_http_request, record_http_request_with_exemplar,
record_invocation_history_lost, record_mcp_request, record_tool_invocation,
record_upstream_request, set_catalog, set_db_pool_connections, set_mcp_active_sessions,
};
use metrics_util::debugging::DebuggingRecorder;
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
const MCP_ONLY_ROUTE: &str = "/v1/{workspace_slug}/{agent_slug}";
const ADMIN_ROUTE: &str = "/api/admin/workspaces/{workspace_id}/operations";
fn route_to_child(role: &str, test: &str) -> bool {
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
None => {
let output =
std::process::Command::new(std::env::current_exe().expect("current test binary"))
.args([test, "--exact", "--nocapture"])
.env(BINDING_ROLE_ENV, role)
.output()
.expect("re-executed binding child");
assert!(
output.status.success(),
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
}
}
type Samples = Vec<(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)>;
fn rendered_keys(samples: &Samples) -> BTreeSet<String> {
samples
.iter()
.map(|(key, _, _, _)| {
let mut labels = key
.key()
.labels()
.map(|label| format!("{}={}", label.key(), label.value()))
.collect::<Vec<_>>();
labels.sort();
format!("{}{{{}}}", key.key().name(), labels.join(","))
})
.collect()
}
fn trace() -> ExemplarTraceId {
ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("valid trace id")
}
/// TD-B1 — до binding все facade-пути (включая guards и exemplar) — безопасный
/// no-op: ни одного handle, ни одной series, ни одного exemplar entry.
#[test]
fn unbound_facade_is_a_no_op() {
if route_to_child("unbound", "unbound_facade_is_a_no_op") {
return;
}
assert_eq!(bound_metric_service(), None);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
record_http_request(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(1),
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(1),
Some(trace()),
);
record_mcp_request(
crank_metrics::McpMethod::ToolsCall,
crank_metrics::McpResponseMode::Json,
crank_metrics::McpOutcome::Success,
Duration::from_millis(1),
);
record_tool_invocation(
crank_metrics::InvocationSource::AgentToolCall,
crank_metrics::ToolOutcome::Success,
crank_metrics::ToolErrorKind::None,
Duration::from_millis(1),
);
record_upstream_request(
crank_metrics::UpstreamOperationKind::Rest,
crank_metrics::UpstreamOutcome::Success,
Duration::from_millis(1),
);
record_cache_outcome(crank_metrics::CacheOutcome::Hit);
record_invocation_history_lost();
set_db_pool_connections(crank_metrics::DbPoolState::Idle, 1);
set_mcp_active_sessions(1);
set_catalog(1, 1, 1);
let _http = crank_metrics::InFlightGuard::http();
let _runtime = crank_metrics::InFlightGuard::runtime();
let _stream = crank_metrics::InFlightGuard::mcp_stream();
let _tool = crank_metrics::ToolInvocationMetrics::start(
crank_metrics::InvocationSource::AgentToolCall,
);
let _upstream = crank_metrics::UpstreamRequestMetrics::start(
crank_metrics::UpstreamOperationKind::Rest,
);
});
let samples = snapshotter.snapshot().into_vec();
assert!(
samples.is_empty(),
"unbound facade не может регистрировать series: {:?}",
rendered_keys(&samples)
);
assert!(
exemplar_snapshot().is_empty(),
"unbound facade не может создавать exemplar entries"
);
}
/// TD-B2 — повтор того же сервиса идемпотентен.
#[test]
fn same_service_bind_is_idempotent() {
if route_to_child("admin_api", "same_service_bind_is_idempotent") {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("first bind");
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("same-service rebind");
assert_eq!(bound_metric_service(), Some(MetricService::AdminApi));
assert_eq!(
crank_metrics::bind_metric_service(MetricService::McpServer),
Err(MetricBindingError::ConflictingService)
);
assert_eq!(
bound_metric_service(),
Some(MetricService::AdminApi),
"конфликт не меняет уже опубликованный сервис"
);
}
/// TD-B3 — concurrent конфликт разных сервисов: ровно один winner.
#[test]
fn conflicting_concurrent_bind_has_one_winner() {
if route_to_child("conflict", "conflicting_concurrent_bind_has_one_winner") {
return;
}
let results = std::thread::scope(|scope| {
let admin = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::AdminApi));
let mcp = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::McpServer));
vec![
("admin_api", admin.join().expect("admin bind thread")),
("mcp_server", mcp.join().expect("mcp bind thread")),
]
});
let winners = results
.iter()
.filter(|(_, result)| result.is_ok())
.collect::<Vec<_>>();
assert_eq!(
winners.len(),
1,
"ровно один сервис может победить: {results:?}"
);
for (role, result) in &results {
if let Err(error) = result {
assert_eq!(
*error,
MetricBindingError::ConflictingService,
"loser {role} обязан получить типизированный конфликт"
);
}
}
let winner = winners[0].0;
let expected = match winner {
"admin_api" => Some(MetricService::AdminApi),
_ => Some(MetricService::McpServer),
};
assert_eq!(bound_metric_service(), expected);
}
/// TD-B4 — known route чужого сервиса degraded в `unmatched`, запрос сохраняется.
#[test]
fn wrong_service_route_records_unmatched() {
if route_to_child("admin_api", "wrong_service_route_records_unmatched") {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
record_http_request(
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_secs_f64(0.004),
);
});
let samples = snapshotter.snapshot().into_vec();
let keys = rendered_keys(&samples);
assert!(
keys.contains("crank_http_requests_total{method=GET,route=unmatched,status_class=2xx}"),
"чужой known route обязан стать unmatched с сохранением method/status: {keys:?}"
);
assert!(
keys.contains("crank_http_request_duration_seconds{method=GET,route=unmatched}"),
"duration обязан идти в тот же unmatched series: {keys:?}"
);
assert!(
keys.iter().all(|key| !key.contains("workspace_slug")),
"ни одна series не может нести ключ чужого route: {keys:?}"
);
assert_eq!(
keys.len(),
2,
"wrong tuple не создаёт новых families: {keys:?}"
);
}
/// TD-B5 — прямой exemplar не создаёт ключ чужого route.
#[test]
fn direct_exemplar_cannot_create_foreign_route_key() {
if route_to_child(
"admin_api",
"direct_exemplar_cannot_create_foreign_route_key",
) {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
assert!(
exemplar_snapshot().is_empty(),
"fixture требует чистый exemplar store"
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(4),
Some(trace()),
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(4),
Some(trace()),
);
let observations = exemplar_snapshot();
assert_eq!(
observations.len(),
2,
"exemplar обязан попасть в unmatched и в собственную admin-серию: {observations:#?}"
);
assert!(
observations.iter().all(
|observation| observation.labels.contains(&("route", "unmatched"))
|| observation.labels.contains(&("route", ADMIN_ROUTE))
),
"ни один exemplar не может нести чужой route: {observations:#?}"
);
assert!(
observations
.iter()
.all(|observation| !observation.labels.contains(&("route", MCP_ONLY_ROUTE))),
"foreign route key не может быть создан"
);
assert!(
MAX_EXEMPLAR_SLOTS_PER_PROCESS
>= crank_metrics::max_exemplar_slots(MetricService::AdminApi)
);
}
@@ -9,6 +9,8 @@ use metrics_util::debugging::DebuggingRecorder;
#[test]
fn one_million_hostile_values_collapse_to_the_same_closed_series() {
crank_metrics::bind_metric_service(MetricService::McpServer)
.expect("isolated metrics binding for the cardinality fixture");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
+67 -6
View File
@@ -3,15 +3,47 @@ use std::{collections::BTreeSet, time::Duration};
use crank_metrics::{
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpRoute,
HttpStatusClass, IdempotencyOutcome, InFlightGuard, InvocationSource, LimitStage, McpMethod,
McpOutcome, McpResponseMode, SignalType, ToolErrorKind, ToolInvocationMetrics, ToolOutcome,
UpstreamOperationKind, UpstreamOutcome, UpstreamRequestMetrics, initialize_gauges,
metric_schema, record_cache_outcome, record_confirmation_outcome, record_export_failure,
record_http_request, record_idempotency_outcome, record_invocation_history_lost,
record_limit_rejection, record_mcp_request, record_tool_invocation, record_upstream_request,
set_catalog, set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
McpOutcome, McpResponseMode, MetricService, SignalType, ToolErrorKind, ToolInvocationMetrics,
ToolOutcome, UpstreamOperationKind, UpstreamOutcome, UpstreamRequestMetrics,
bind_metric_service, initialize_gauges, metric_schema, record_cache_outcome,
record_confirmation_outcome, record_export_failure, record_http_request,
record_idempotency_outcome, record_invocation_history_lost, record_limit_rejection,
record_mcp_request, record_tool_invocation, record_upstream_request, set_catalog,
set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
};
use metrics_util::debugging::DebuggingRecorder;
/// Service binding is process-global (`OnceLock`), so every case that needs a
/// different service runs in a fresh child re-executed from this same test
/// binary instead of resetting a global.
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
fn route_to_child(role: &str, test: &str) -> bool {
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
None => {
let output =
std::process::Command::new(std::env::current_exe().expect("current test binary"))
.args([test, "--exact", "--nocapture"])
.env(BINDING_ROLE_ENV, role)
.output()
.expect("re-executed binding child");
assert!(
output.status.success(),
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
}
}
fn bind(service: MetricService) {
bind_metric_service(service).expect("isolated metrics binding for this fixture");
}
#[test]
fn schema_names_are_unique_and_labels_are_closed() {
let schema = metric_schema();
@@ -82,6 +114,10 @@ fn application_outcomes_are_distinct_from_transport_success() {
#[test]
fn impossible_tool_outcome_pairs_are_normalized() {
if route_to_child("mcp_server", "impossible_tool_outcome_pairs_are_normalized") {
return;
}
bind(MetricService::McpServer);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
@@ -102,6 +138,13 @@ fn impossible_tool_outcome_pairs_are_normalized() {
#[test]
fn dropped_product_guards_record_aborted_outcomes() {
if route_to_child(
"mcp_server",
"dropped_product_guards_record_aborted_outcomes",
) {
return;
}
bind(MetricService::McpServer);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
@@ -131,6 +174,10 @@ fn has_label(key: &metrics::Key, name: &str, value: &str) -> bool {
#[test]
fn diverse_calls_cannot_create_unbounded_series() {
if route_to_child("mcp_server", "diverse_calls_cannot_create_unbounded_series") {
return;
}
bind(MetricService::McpServer);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
@@ -178,6 +225,13 @@ fn diverse_calls_cannot_create_unbounded_series() {
#[test]
fn every_recording_api_matches_the_declared_schema() {
if route_to_child(
"mcp_server",
"every_recording_api_matches_the_declared_schema",
) {
return;
}
bind(MetricService::McpServer);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
@@ -259,6 +313,13 @@ fn every_recording_api_matches_the_declared_schema() {
#[test]
fn admin_gauge_initialization_never_emits_mcp_only_series() {
if route_to_child(
"admin_api",
"admin_gauge_initialization_never_emits_mcp_only_series",
) {
return;
}
bind(MetricService::AdminApi);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
@@ -0,0 +1,141 @@
//! Story 3.6 · AT-3.6-08 · фаза B — v2 snapshot и CLI.
//!
//! `TD-C1` default output CLI равен закоммиченному v2-снимку byte-for-byte.
//! `TD-C2` `--check` не зависит от cwd и печатает точную строку версии.
//! `TD-C3` ошибки CLI точны, без JSON в выводе.
//! `TD-C4` сериализация компактна и не несёт динамического текста.
use std::path::PathBuf;
use std::process::Command;
const FROZEN_V2: &str = include_str!("../../../docs/schemas/metrics-registry-v2.json");
fn binary() -> Command {
Command::new(env!("CARGO_BIN_EXE_crank-metrics-contract"))
}
/// TD-C1 — default output CLI = versioned snapshot (byte-for-byte, детерминированно).
#[test]
fn default_output_is_the_versioned_snapshot() {
let first = binary().output().expect("contract CLI runs");
assert!(
first.status.success(),
"{}",
String::from_utf8_lossy(&first.stderr)
);
let stdout = String::from_utf8(first.stdout).expect("utf-8 snapshot");
assert_eq!(
stdout, FROZEN_V2,
"default CLI обязан печатать ровно закоммиченный v2-снимок"
);
let second = binary().output().expect("contract CLI reruns");
assert_eq!(
String::from_utf8(second.stdout).expect("utf-8 snapshot"),
stdout,
"рендер обязан быть детерминированным"
);
let rendered = crank_metrics::render_metric_schema_json().expect("renderer");
assert_eq!(
rendered, FROZEN_V2,
"Rust renderer обязан совпасть с закоммиченным снимком"
);
}
/// TD-C2 — `--check` независим от cwd и печатает точную строку версии.
#[test]
fn check_is_cwd_independent_and_exact() {
let directory = std::env::temp_dir().join(format!(
"crank-metrics-contract-v2-{}-{}",
std::process::id(),
std::thread::current().name().unwrap_or("main").len()
));
std::fs::create_dir_all(&directory).expect("temp cwd");
let output = binary()
.arg("--check")
.current_dir(&directory)
.output()
.expect("contract CLI runs");
std::fs::remove_dir_all(&directory).ok();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
String::from_utf8(output.stdout).expect("utf-8"),
"metrics_contract_ok schema_version=2\n",
"--check обязан печатать ровно эту строку"
);
assert!(output.stderr.is_empty(), "--check не пишет stderr");
}
/// TD-C3 — ошибочные команды: точный stderr, ненулевой exit, никакого JSON.
#[test]
fn error_paths_are_exact_and_json_free() {
for args in [vec!["--unknown"], vec!["--check", "extra"], vec!["render"]] {
let output = binary().args(&args).output().expect("contract CLI runs");
assert!(
!output.status.success(),
"команда {args:?} обязана падать, output: {:?}",
output
);
assert_eq!(
String::from_utf8(output.stderr).expect("utf-8"),
"metrics_contract_invalid_command\n",
"точный static error text для {args:?}"
);
let stdout = String::from_utf8(output.stdout).expect("utf-8");
assert!(
!stdout.contains('{') && !stdout.contains('"'),
"ошибочный вывод не может содержать JSON: {stdout:?}"
);
}
}
/// TD-C4 — компактная сериализация без динамического текста и < 65536 bytes.
#[test]
fn serialization_is_compact_and_free_of_dynamic_text() {
assert!(
FROZEN_V2.len() < 65_536,
"v2-снимок обязан остаться < 65536 bytes, observed {}",
FROZEN_V2.len()
);
assert!(FROZEN_V2.ends_with("}\n"), "ровно одна завершающая LF");
assert_eq!(
FROZEN_V2.matches('\n').count(),
1,
"компактный JSON без переводов строк внутри документа"
);
assert!(
!FROZEN_V2.contains(" "),
"вне строк не может быть пробелов"
);
assert!(FROZEN_V2.starts_with("{\"schema_version\":2,"));
assert!(FROZEN_V2.contains("\"unmatched\""));
for forbidden in [
"trace_id",
"request_id",
"correlation_id",
"workspace-",
"/home/",
"/tmp/",
"http://",
"https://",
] {
assert!(
!FROZEN_V2.contains(forbidden),
"v2-снимок не может нести динамический текст `{forbidden}`"
);
}
assert!(
FROZEN_V2
.contains("\"buckets_seconds\":[0.005,0.01,0.025,0.05,0.1,0.25,0.5,1,2.5,5,10,30,60]"),
"bucket'ы обязаны быть точными числами (1, а не 1.0)"
);
let snapshot_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../docs/schemas/metrics-registry-v2.json");
assert!(snapshot_path.is_file(), "v2-снимок обязан быть закоммичен");
let v1_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../docs/schemas/metrics-registry-v1.json");
assert!(v1_path.is_file(), "frozen v1 обязан остаться на месте");
}
+206
View File
@@ -0,0 +1,206 @@
//! Story 3.6 · AT-3.6-08 · фаза B — family gating и gauges по binding.
//!
//! `TD-B8` MCP-only facade вызовы в admin-процессе — no-op без handle/exemplar.
//! `TD-B9` `initialize_gauges` требует совпадающий binding, иначе no-op.
//! `TD-B10` guard чужого family при drop не создаёт series.
//!
//! Каждый кейс исполняется в fresh child (binding — process-global `OnceLock`).
use std::collections::BTreeSet;
use std::time::Duration;
use crank_metrics::{
DbPoolState, InFlightGuard, InvocationSource, McpMethod, McpOutcome, McpResponseMode,
MetricService, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
exemplar_snapshot, initialize_gauges, record_cache_outcome, record_idempotency_outcome,
record_invocation_history_lost, record_mcp_request, record_mcp_request_with_exemplar,
record_tool_invocation, record_upstream_request, set_catalog, set_mcp_active_sessions,
};
use metrics_util::debugging::DebuggingRecorder;
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
fn route_to_child(role: &str, test: &str) -> bool {
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
None => {
let output =
std::process::Command::new(std::env::current_exe().expect("current test binary"))
.args([test, "--exact", "--nocapture"])
.env(BINDING_ROLE_ENV, role)
.output()
.expect("re-executed binding child");
assert!(
output.status.success(),
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
}
}
fn bind_admin() {
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
}
fn series_names(
samples: &[(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)],
) -> BTreeSet<String> {
samples
.iter()
.map(|(key, _, _, _)| key.key().name().to_owned())
.collect()
}
/// TD-B8 — MCP-only families в admin-процессе не создают ни handles, ни exemplars.
#[test]
fn mcp_only_calls_are_noop_in_admin_process() {
if route_to_child("admin_api", "mcp_only_calls_are_noop_in_admin_process") {
return;
}
bind_admin();
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
record_mcp_request(
McpMethod::ToolsCall,
McpResponseMode::Json,
McpOutcome::Success,
Duration::from_millis(1),
);
record_mcp_request_with_exemplar(
McpMethod::ToolsCall,
McpResponseMode::Json,
McpOutcome::Success,
Duration::from_millis(1),
crank_metrics::ExemplarTraceId::parse("0123456789abcdef0123456789abcdef"),
);
set_mcp_active_sessions(3);
crank_metrics::set_mcp_session_metrics_fresh(true);
set_catalog(7, 70, 1);
});
let samples = snapshotter.snapshot().into_vec();
assert!(
samples.is_empty(),
"MCP-only families обязаны быть no-op в admin: {:?}",
series_names(&samples)
);
assert!(
exemplar_snapshot().is_empty(),
"MCP-only exemplar не может создавать entry в admin-процессе"
);
// Общие families при этом продолжают работать.
let shared = DebuggingRecorder::new();
let shared_snapshotter = shared.snapshotter();
metrics::with_local_recorder(&shared, || {
record_tool_invocation(
InvocationSource::AgentToolCall,
ToolOutcome::Success,
ToolErrorKind::None,
Duration::from_millis(1),
);
record_upstream_request(
UpstreamOperationKind::Rest,
UpstreamOutcome::Success,
Duration::from_millis(1),
);
record_cache_outcome(crank_metrics::CacheOutcome::Hit);
record_idempotency_outcome(crank_metrics::IdempotencyOutcome::Replay);
record_invocation_history_lost();
});
let names = series_names(&shared_snapshotter.snapshot().into_vec());
assert!(
names.contains("crank_tool_invocations_total")
&& names.contains("crank_upstream_requests_total")
&& names.contains("crank_runtime_cache_total"),
"shared families обязаны работать в admin: {names:?}"
);
}
/// TD-B9 — `initialize_gauges` требует совпадающий binding.
#[test]
fn initialize_gauges_requires_matching_binding() {
if route_to_child("admin_api", "initialize_gauges_requires_matching_binding") {
return;
}
bind_admin();
let foreign = DebuggingRecorder::new();
let foreign_snapshotter = foreign.snapshotter();
metrics::with_local_recorder(&foreign, || {
initialize_gauges(MetricService::McpServer);
});
assert!(
foreign_snapshotter.snapshot().into_vec().is_empty(),
"initialize_gauges чужого сервиса обязан быть no-op"
);
let own = DebuggingRecorder::new();
let own_snapshotter = own.snapshotter();
metrics::with_local_recorder(&own, || {
initialize_gauges(MetricService::AdminApi);
});
let names = series_names(&own_snapshotter.snapshot().into_vec());
assert!(names.contains("crank_http_inflight"));
assert!(names.contains("crank_runtime_inflight"));
assert!(names.contains("crank_db_pool_connections"));
assert!(
names.iter().all(|name| !name.starts_with("crank_mcp_")),
"admin gauges не могут включать MCP-only series: {names:?}"
);
assert!(
names.iter().all(|name| !name.starts_with("crank_catalog_")),
"admin gauges не могут включать catalog series: {names:?}"
);
}
/// TD-B10 — guard чужого family при drop не создаёт series.
#[test]
fn foreign_family_guard_drop_creates_no_series() {
if route_to_child("admin_api", "foreign_family_guard_drop_creates_no_series") {
return;
}
bind_admin();
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
let stream = InFlightGuard::mcp_stream();
drop(stream);
let tool = crank_metrics::ToolInvocationMetrics::start(InvocationSource::AgentToolCall);
drop(tool);
let upstream = crank_metrics::UpstreamRequestMetrics::start(UpstreamOperationKind::Rest);
drop(upstream);
});
let names = series_names(&snapshotter.snapshot().into_vec());
assert!(
names.iter().all(|name| !name.starts_with("crank_mcp_")),
"guard чужого family не может создавать series: {names:?}"
);
assert!(
!names.contains("crank_mcp_active_streams"),
"foreign stream guard обязан быть no-op: {names:?}"
);
// Собственный family работает: guard admin http и shared families.
let own = DebuggingRecorder::new();
let own_snapshotter = own.snapshotter();
metrics::with_local_recorder(&own, || {
let http = InFlightGuard::http();
drop(http);
});
let own_names = series_names(&own_snapshotter.snapshot().into_vec());
assert!(
own_names.contains("crank_http_inflight"),
"admin http guard обязан регистрировать series: {own_names:?}"
);
let _ = DbPoolState::Idle;
}
@@ -0,0 +1,453 @@
//! Story 3.6 · AT-3.6-08 · phase A (ATDD, test-only) — exemplar capacity invariants.
//!
//! Этот таргет на фазе A содержит **только** A-селекторы: они используют
//! существующее API `crank-metrics` (`record_http_request_with_exemplar`,
//! `exemplar_snapshot`, `DebuggingRecorder`) и не требуют правок `src/**`.
//!
//! * `TD-X1` — exemplar никогда не создаёт новый series (агрегат остаётся тем же
//! keyset'ом и получает оба наблюдения).
//! * `TD-X2` — latest-per-(family,labelset,bucket) стабилен: повторная запись того
//! же ключа обновляет значение/trace_id, но не увеличивает число наблюдений.
//!
//! Публичный exact-maximal sweep/capacity этих сервисов и private poison-путь
//! принадлежат фазе build (отсутствующее API/`src/**` правки) и в этот таргет не
//! добавляются, чтобы фаза A оставалась компилируемой и честной.
use std::collections::BTreeSet;
use std::time::Duration;
use crank_metrics::{
ExemplarObservation, ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass,
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MetricService, exemplar_snapshot, max_exemplar_slots,
record_http_request, record_http_request_with_exemplar,
};
use metrics_util::debugging::DebuggingRecorder;
const HTTP_COUNTER: &str = "crank_http_requests_total";
const HTTP_DURATION: &str = "crank_http_request_duration_seconds";
fn trace(value: &str) -> ExemplarTraceId {
ExemplarTraceId::parse(value).expect("sanitised 32-lowercase-hex trace id")
}
/// Rendered `name{label=value,…}` keys of the whole local snapshot (labels sorted).
fn series_keys(
snapshot: &[(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)],
) -> BTreeSet<String> {
snapshot
.iter()
.map(|(key, _, _, _)| {
let mut labels = key
.key()
.labels()
.map(|label| format!("{}={}", label.key(), label.value()))
.collect::<Vec<_>>();
labels.sort();
format!("{}{{{}}}", key.key().name(), labels.join(","))
})
.collect()
}
/// Aggregate debug values of one observed series inside a snapshot (`None` = series absent).
fn series_value(
snapshot: &[(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)],
rendered_key: &str,
) -> Option<String> {
snapshot
.iter()
.find(|(key, _, _, _)| {
let mut labels = key
.key()
.labels()
.map(|label| format!("{}={}", label.key(), label.value()))
.collect::<Vec<_>>();
labels.sort();
format!("{}{{{}}}", key.key().name(), labels.join(",")) == rendered_key
})
.map(|(_, _, _, value)| format!("{value:?}"))
}
/// Histogram deltas of one series inside a (draining) snapshot.
fn histogram_values(
snapshot: &[(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)],
rendered_key: &str,
) -> Vec<f64> {
snapshot
.iter()
.find(|(key, _, _, _)| {
let mut labels = key
.key()
.labels()
.map(|label| format!("{}={}", label.key(), label.value()))
.collect::<Vec<_>>();
labels.sort();
format!("{}{{{}}}", key.key().name(), labels.join(",")) == rendered_key
})
.map(|(_, _, _, value)| match value {
metrics_util::debugging::DebugValue::Histogram(values) => {
values.iter().map(|value| value.0).collect()
}
other => panic!("series {rendered_key} is not a histogram: {other:?}"),
})
.unwrap_or_default()
}
/// Observations of the process-global exemplar store for one exact keyset.
fn observations(
metric: &str,
route: &str,
method: &str,
) -> Vec<std::sync::Arc<ExemplarObservation>> {
exemplar_snapshot()
.into_iter()
.filter(|observation| {
observation.metric == metric
&& observation.labels.contains(&("route", route))
&& observation.labels.contains(&("method", method))
})
.collect()
}
/// TD-X1 — exemplar не создаёт новый series и не подменяет агрегат.
///
/// `DebuggingRecorder::snapshot()` является **дренирующим** дельта-снимком
/// (`metrics-util::debugging`, swap/clear): каждый снимок несёт ровно то, что
/// записано с момента предыдущего. Поэтому оракул сравнивает keyset дельт двух
/// последовательных запросов: exemplar-запись обязана попасть в тот же keyset.
#[test]
fn exemplar_observation_never_creates_a_new_series() {
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
.expect("isolated metrics binding for the exemplar capacity fixture");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let template = HttpRoute::from_matched_path("/api/admin/capabilities").as_str();
assert_ne!(template, "unmatched", "оракул требует известный template");
let route = HttpRoute::from_matched_path(template);
let (without_exemplar, with_exemplar) = metrics::with_local_recorder(&recorder, || {
record_http_request_with_exemplar(
route,
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(4),
None,
);
let without_exemplar = snapshotter.snapshot().into_vec();
record_http_request_with_exemplar(
route,
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(5),
Some(trace("0123456789abcdef0123456789abcdef")),
);
let with_exemplar = snapshotter.snapshot().into_vec();
(without_exemplar, with_exemplar)
});
let plain_keys = series_keys(&without_exemplar);
let exemplar_keys = series_keys(&with_exemplar);
assert_eq!(
plain_keys.len(),
2,
"агрегат HTTP-запроса объявлен ровно двумя series (counter + histogram): {plain_keys:#?}"
);
assert_eq!(
exemplar_keys, plain_keys,
"exemplar не может создавать новый series (keyset дельт обязан совпасть)"
);
assert!(
!exemplar_keys.iter().any(|key| key.contains("exemplar")),
"exemplar не является отдельным series агрегата: {exemplar_keys:#?}"
);
let counter_key = plain_keys
.iter()
.find(|key| key.starts_with(&format!("{HTTP_COUNTER}{{")))
.expect("counter series must exist")
.clone();
let duration_key = plain_keys
.iter()
.find(|key| key.starts_with(&format!("{HTTP_DURATION}{{")))
.expect("duration series must exist")
.clone();
// Обе записи попадают в **тот же** агрегат: каждая наблюдается ровно один раз.
for (label, snapshot) in [("without", &without_exemplar), ("with", &with_exemplar)] {
assert_eq!(
series_value(snapshot, &counter_key).as_deref(),
Some("Counter(1)"),
"[{label}] counter обязан получить ровно этот запрос, observed {:?}",
series_value(snapshot, &counter_key)
);
assert_eq!(
histogram_values(snapshot, &duration_key).len(),
1,
"[{label}] duration обязан получить ровно это наблюдение"
);
}
assert_eq!(
histogram_values(&without_exemplar, &duration_key),
vec![0.004]
);
assert_eq!(histogram_values(&with_exemplar, &duration_key), vec![0.005]);
// Приватный exemplar-store: ровно одно наблюдение для этого keyset, с тем же trace_id.
let stored = observations(HTTP_DURATION, template, "GET");
assert_eq!(
stored.len(),
1,
"exemplar store обязан хранить latest-per-key, observed {stored:#?}"
);
assert_eq!(
stored[0].trace_id,
trace("0123456789abcdef0123456789abcdef")
);
assert_eq!(
stored[0].bucket_upper_bound,
Some(0.005),
"4-5 ms обязаны попасть в первый объявленный bucket"
);
// trace_id никогда не становится обычной меткой агрегата.
for key in exemplar_keys {
assert!(
!key.contains("trace_id"),
"trace_id не может быть обычной меткой: {key}"
);
}
}
/// TD-X2 — latest-per-(family,labelset,bucket) стабилен (overwrite, не накопление).
#[test]
fn latest_overwrite_is_stable() {
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
.expect("isolated metrics binding for the exemplar capacity fixture");
let route = HttpRoute::from_matched_path("/ready");
assert_eq!(
route.as_str(),
"/ready",
"оракул требует известный template `/ready`"
);
// Изолированный keyset внутри процесс-глобального store.
assert!(
observations(HTTP_DURATION, "/ready", "GET").is_empty(),
"keyset `/ready`+GET обязан быть чистым до записи"
);
let first = trace("00000000000000000000000000000001");
let second = trace("00000000000000000000000000000002");
record_http_request_with_exemplar(
route,
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_micros(1_000),
Some(first),
);
let after_first = observations(HTTP_DURATION, "/ready", "GET");
assert_eq!(
after_first.len(),
1,
"первая запись создаёт одно наблюдение"
);
assert_eq!(after_first[0].trace_id, first);
assert!((after_first[0].value - 0.001).abs() < 1e-9);
assert_eq!(after_first[0].bucket_upper_bound, Some(0.005));
// Тот же (family, labelset, bucket): 2 ms также попадают в bucket le=0.005.
record_http_request_with_exemplar(
route,
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_micros(2_000),
Some(second),
);
let after_second = observations(HTTP_DURATION, "/ready", "GET");
assert_eq!(
after_second.len(),
1,
"повторная запись того же ключа обязана обновлять latest, а не накапливать: {after_second:#?}"
);
assert_eq!(
after_second[0].trace_id, second,
"latest обязан нести trace_id последней записи"
);
assert!(
(after_second[0].value - 0.002).abs() < 1e-9,
"latest обязан нести значение последней записи, observed {}",
after_second[0].value
);
assert_eq!(
after_second[0].bucket_upper_bound,
Some(0.005),
"оба значения обязаны делить bucket le=0.005"
);
// Новый bucket того же keyset — отдельное наблюдение (ключ включает bucket).
record_http_request_with_exemplar(
route,
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(20),
Some(second),
);
let after_third_bucket = observations(HTTP_DURATION, "/ready", "GET");
assert_eq!(
after_third_bucket.len(),
2,
"другой bucket — отдельный latest-ключ: {after_third_bucket:#?}"
);
assert!(after_third_bucket.iter().any(|observation| {
observation.bucket_upper_bound == Some(0.025) && (observation.value - 0.020).abs() < 1e-9
}));
}
// ---------------------------------------------------------------------------
// Фаза B — public facade enforcement и per-service capacity.
// ---------------------------------------------------------------------------
/// TD-X3b — public facade: достижимое множество нормализованных ключей равно
/// объявленной проекции сервиса и никогда не превышает её (для counter/histogram
/// это в точности `71x10x6` и `71x10`), а чужой route не появляется вовсе.
#[test]
fn public_facade_projection_enforcement() {
crank_metrics::bind_metric_service(MetricService::AdminApi)
.expect("admin metrics binding for the facade sweep");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let admin_routes = crank_metrics::ADMIN_HTTP_ROUTE_DOMAIN;
let methods = HttpMethod::VALUES;
let statuses = HttpStatusClass::VALUES;
metrics::with_local_recorder(&recorder, || {
// Чужой (MCP-only) route: обязан схлопнуться в unmatched, а не создать ключ.
for method in methods {
record_http_request(
HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
HttpMethod::classify(method),
HttpStatusClass::Success,
Duration::from_millis(1),
);
}
for route in admin_routes {
for method in methods {
for status in statuses {
record_http_request(
HttpRoute::from_matched_path(route),
HttpMethod::classify(method),
HttpStatusClass::from_status(match *status {
"1xx" => 101,
"2xx" => 200,
"3xx" => 302,
"4xx" => 404,
"5xx" => 500,
_ => 0,
}),
Duration::from_millis(1),
);
}
}
}
});
let samples = snapshotter.snapshot().into_vec();
let counters = samples
.iter()
.filter(|(key, _, _, _)| key.key().name() == HTTP_COUNTER)
.count();
let durations = samples
.iter()
.filter(|(key, _, _, _)| key.key().name() == HTTP_DURATION)
.count();
assert_eq!(
counters,
admin_routes.len() * methods.len() * statuses.len(),
"facade обязан покрыть ровно объявленную counter-проекцию admin"
);
assert_eq!(
durations,
admin_routes.len() * methods.len(),
"facade обязан покрыть ровно объявленную histogram-проекцию admin"
);
for (key, _, _, _) in &samples {
for label in key.key().labels() {
assert!(
!label.value().contains("workspace_slug"),
"чужой route не может стать label-значением: {label:?}"
);
}
}
assert!(
samples.iter().any(|(key, _, _, _)| {
key.key().name() == HTTP_COUNTER
&& key
.key()
.labels()
.any(|label| label.key() == "route" && label.value() == "unmatched")
}),
"чужой route обязан остаться наблюдаемым как unmatched"
);
}
/// TD-X4 — per-service capacity edges никогда не превышают hard cap.
#[test]
fn capacity_edges_do_not_exceed_hard_cap() {
for service in [MetricService::AdminApi, MetricService::McpServer] {
let capacity = max_exemplar_slots(service);
assert!(
capacity <= MAX_EXEMPLAR_SLOTS_PER_PROCESS,
"{:?} capacity {capacity} превышает hard cap",
service
);
assert!(crank_metrics::validate_exemplar_budget(capacity).is_ok());
assert!(
capacity == MAX_EXEMPLAR_SLOTS_PER_PROCESS
|| crank_metrics::validate_exemplar_budget(capacity + 1).is_ok(),
"{:?} capacity {capacity} ниже hard cap, но capacity+1 отвергнут",
service
);
assert!(
crank_metrics::validate_exemplar_budget(MAX_EXEMPLAR_SLOTS_PER_PROCESS).is_ok(),
"hard cap обязан быть разрешён"
);
assert!(
crank_metrics::validate_exemplar_budget(MAX_EXEMPLAR_SLOTS_PER_PROCESS + 1).is_err(),
"cap+1 обязан быть отвергнут"
);
}
}
/// TD-X6 — union capacity (14658) никогда не используется как лимит процесса.
#[test]
fn union_capacity_is_never_used_as_process_limit() {
let admin = max_exemplar_slots(MetricService::AdminApi);
let mcp = max_exemplar_slots(MetricService::McpServer);
assert_eq!(admin, 12_348);
assert_eq!(mcp, 2_310);
assert_ne!(admin, 14_658, "union-capacity не может быть лимитом admin");
assert_ne!(mcp, 14_658, "union-capacity не может быть лимитом mcp");
assert_eq!(
admin, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
"владелец утвердил hard cap ровно по фактическому admin budget (12348): admin обязан сохранить все свои slots"
);
assert_eq!(
admin + mcp,
14_658,
"два процесса вместе имеют отдельные capacities; union не является лимитом процесса"
);
}
+2
View File
@@ -14,6 +14,8 @@ fn trace_id_is_validated_and_never_becomes_an_ordinary_label() {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
.expect("isolated metrics binding for the exemplar fixture");
metrics::with_local_recorder(&recorder, || {
record_http_request_with_exemplar(
HttpRoute::from_matched_path("/health"),
+2
View File
@@ -80,6 +80,8 @@ struct ProfileSample {
#[test]
fn reproducible_foundation_profile_stays_inside_latency_and_cpu_proxy_budgets() {
crank_metrics::bind_metric_service(crank_metrics::MetricService::McpServer)
.expect("isolated metrics binding for the overhead profile");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let mut baseline = Vec::with_capacity(SAMPLES);
+447 -13
View File
@@ -10,12 +10,14 @@ use crank_metrics::{
#[test]
fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
assert_eq!(METRIC_SCHEMA_VERSION, 1);
assert_eq!(METRIC_SCHEMA_VERSION, 2);
assert_eq!(metric_schema().len(), 23);
let budget = schema_budget().expect("canonical schema must be valid");
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
for service in [MetricService::AdminApi, MetricService::McpServer] {
let budget = schema_budget(service).expect("canonical schema must be valid");
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
}
for definition in metric_schema() {
assert!(!definition.description.trim().is_empty());
@@ -46,16 +48,25 @@ fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
#[test]
fn frozen_budget_edges_are_exact() {
assert!(validate_budget(5_562, 17_637).is_ok());
assert!(validate_budget(5_563, 17_638).is_ok());
assert!(validate_budget(5_564, 16_000).is_err());
assert!(validate_budget(5_200, 17_639).is_err());
assert_eq!(crank_metrics::max_exemplar_slots(), 11_270);
assert!(validate_budget(6_284, 19_514).is_ok());
assert!(validate_budget(6_285, 19_515).is_ok());
assert!(validate_budget(6_286, 16_000).is_err());
assert!(validate_budget(6_000, 19_516).is_err());
assert_eq!(
crank_metrics::max_exemplar_slots(MetricService::AdminApi),
12_348
);
assert_eq!(
crank_metrics::max_exemplar_slots(MetricService::McpServer),
2_310
);
assert!(crank_metrics::validate_exemplar_budget(12_348).is_ok());
assert!(crank_metrics::validate_exemplar_budget(12_349).is_err());
}
#[test]
fn every_registered_route_round_trips_without_dynamic_segments() {
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 72);
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
for route in HTTP_ROUTE_DOMAIN {
assert_eq!(HttpRoute::from_matched_path(route).as_str(), *route);
assert!(!route.contains("trace_id"));
@@ -66,10 +77,17 @@ fn every_registered_route_round_trips_without_dynamic_segments() {
#[test]
fn canonical_schema_validation_reports_its_category() {
assert_eq!(
schema_budget(),
schema_budget(MetricService::AdminApi),
Ok(crank_metrics::SchemaBudget {
logical_series: 5_563,
rendered_series: 17_638
logical_series: 6_285,
rendered_series: 19_515
})
);
assert_eq!(
schema_budget(MetricService::McpServer),
Ok(crank_metrics::SchemaBudget {
logical_series: 1_083,
rendered_series: 3_558
})
);
}
@@ -195,3 +213,419 @@ fn route_literals(source: &str) -> Vec<String> {
}
routes
}
/// TD-C5: замороженный v1-снимок `docs/schemas/metrics-registry-v1.json` остаётся
/// byte-for-byte compatibility input'ом, а не пере-генерируется под новый контракт.
///
/// Оракул — sha256 + точная длина самих байтов файла. sha256 реализован здесь
/// локально (без новой dependency), поэтому первым шагом проверяются контрольные
/// векторы FIPS 180-4: без них byte-oracle был бы вакуумным.
#[test]
fn v1_snapshot_is_retained_byte_for_byte() {
// Self-control локального хэшера (FIPS 180-4).
assert_eq!(
sha256_hex(b""),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
assert_eq!(
sha256_hex(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(
sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"
);
const FROZEN_V1_SNAPSHOT: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
assert_eq!(
sha256_hex(FROZEN_V1_SNAPSHOT.as_bytes()),
"b2ff5f31187559d1095df76fa685e4a9b68db8252523d3a844f5db5da3f48560",
"замороженный v1-снимок обязан оставаться byte-for-byte неизменным"
);
assert_eq!(
FROZEN_V1_SNAPSHOT.len(),
18_512,
"длина замороженного v1-снимка обязана оставаться неизменной"
);
assert!(
FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 1"),
"v1-снимок обязан объявлять свою версию контракта"
);
assert!(
!FROZEN_V1_SNAPSHOT.contains("\"schema_version\": 2"),
"v1-снимок не пере-генерируется под v2-контракт"
);
}
fn sha256_hex(input: &[u8]) -> String {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
0xc67178f2,
];
let mut state: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
let bit_length = (input.len() as u64).wrapping_mul(8);
let mut message = input.to_vec();
message.push(0x80);
while message.len() % 64 != 56 {
message.push(0);
}
message.extend_from_slice(&bit_length.to_be_bytes());
for block in message.chunks_exact(64) {
let mut schedule = [0_u32; 64];
for (index, chunk) in block.chunks_exact(4).enumerate() {
schedule[index] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
}
for index in 16..64 {
let s0 = schedule[index - 15].rotate_right(7)
^ schedule[index - 15].rotate_right(18)
^ (schedule[index - 15] >> 3);
let s1 = schedule[index - 2].rotate_right(17)
^ schedule[index - 2].rotate_right(19)
^ (schedule[index - 2] >> 10);
schedule[index] = schedule[index - 16]
.wrapping_add(s0)
.wrapping_add(schedule[index - 7])
.wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = state;
for index in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let choice = (e & f) ^ ((!e) & g);
let temp1 = h
.wrapping_add(s1)
.wrapping_add(choice)
.wrapping_add(K[index])
.wrapping_add(schedule[index]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let majority = (a & b) ^ (a & c) ^ (b & c);
let temp2 = s0.wrapping_add(majority);
h = g;
g = f;
f = e;
e = d.wrapping_add(temp1);
d = c;
c = b;
b = a;
a = temp1.wrapping_add(temp2);
}
for (slot, value) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) {
*slot = slot.wrapping_add(value);
}
}
state.iter().map(|word| format!("{word:08x}")).collect()
}
/// F7 (CONTRACT §6) — v1↔v2 metric-by-metric compatibility на реальных байтах
/// обоих замороженных документов: kind/unit/help/processes/порядок labels/class/
/// non-route домены/buckets обязаны совпадать, а v1 route-домен — быть
/// подмножеством v2 union (`domain_ref: http_routes`). Парсер минимальный:
/// никакой новой dependency, оба документа machine-generated.
#[test]
fn v1_and_v2_registries_are_metric_by_metric_compatible() {
const V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
const V2: &str = include_str!("../../../docs/schemas/metrics-registry-v2.json");
let v1 = metric_objects(V1);
let v2 = metric_objects(V2);
assert_eq!(v1.len(), 23);
assert_eq!(
v1.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
v2.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
"v2 обязан сохранить тот же набор и порядок family"
);
for ((name, v1_object), (_, v2_object)) in v1.iter().zip(v2.iter()) {
for field in ["kind", "unit", "help", "processes", "buckets_seconds"] {
assert_eq!(
json_field(v1_object, field),
json_field(v2_object, field),
"{name}: поле {field} обязано быть совместимым между v1 и v2"
);
}
let v1_labels = label_entries(v1_object);
let v2_labels = label_entries(v2_object);
assert_eq!(
v1_labels
.iter()
.map(|label| label.name.clone())
.collect::<Vec<_>>(),
v2_labels
.iter()
.map(|label| label.name.clone())
.collect::<Vec<_>>(),
"{name}: порядок labels обязан совпадать"
);
for (v1_label, v2_label) in v1_labels.iter().zip(v2_labels.iter()) {
assert_eq!(v1_label.class, v2_label.class, "{name}/{}", v1_label.name);
if v1_label.name == "route" {
assert_eq!(v1_label.domain_ref, None);
assert_eq!(
v2_label.domain_ref.as_deref(),
Some("http_routes"),
"{name}: v2 обязан ссылаться на единый union маршрутов"
);
continue;
}
assert_eq!(
v1_label.domain, v2_label.domain,
"{name}/{}: домен обязан совпадать между v1 и v2",
v1_label.name
);
assert_eq!(v2_label.domain_ref, None);
}
}
let v1_routes = route_domain_v1(V1);
let v2_routes = union_routes_v2(V2);
assert_eq!(v1_routes.len(), 72, "замороженный v1 route-домен");
assert_eq!(v2_routes.len(), 91);
for route in &v1_routes {
assert!(
v2_routes.contains(route),
"v1 route `{route}` отсутствует в v2 union"
);
}
let added = v2_routes
.iter()
.filter(|route| !v1_routes.contains(*route))
.collect::<Vec<_>>();
assert_eq!(
added.len(),
19,
"v2 обязан добавить тринадцать Resource и шесть Prompt шаблонов"
);
assert_eq!(
added
.iter()
.filter(|route| route.contains("/resources"))
.count(),
13
);
assert_eq!(
added
.iter()
.filter(|route| route.contains("/prompts"))
.count(),
6
);
}
/// F7/R2 — контроль самого compatibility helper'а: пробелы вне строк
/// незначимы, изменение HELP внутри строки обязано обнаруживаться, а значимый
/// пробел внутри строки — сохраняться.
#[test]
fn help_compatibility_helper_preserves_string_content() {
let compact = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
let pretty = "{\n \"help\": \"Total HTTP requests.\",\n \"unit\": \"1\"\n}";
assert_eq!(
compact_json(pretty),
compact,
"format-only пробелы вне строк обязаны игнорироваться"
);
assert_eq!(
json_field(&compact_json(pretty), "help"),
json_field(&compact_json(compact), "help")
);
assert!(
compact_json(compact).contains("\"Total HTTP requests.\""),
"значимый пробел HELP обязан сохраняться в компакте: {}",
compact_json(compact)
);
let changed_help = "{\"help\":\"TotalHTTP requests.\",\"unit\":\"1\"}";
assert_ne!(
json_field(&compact_json(compact), "help"),
json_field(&compact_json(changed_help), "help"),
"изменение HELP внутри строки обязано быть обнаружено"
);
let reflowed_help = "{\"help\":\"Total HTTP requests.\",\"unit\":\"1\"}";
assert_ne!(
json_field(&compact_json(compact), "help"),
json_field(&compact_json(reflowed_help), "help"),
"внутренние пробелы HELP значимы и обязаны различаться"
);
}
struct RegistryLabel {
name: String,
class: String,
domain: Vec<String>,
domain_ref: Option<String>,
}
/// Компактизация JSON: пробелы удаляются только ВНЕ строк. Содержимое
/// quoted/escaped string сохраняется байт-в-байт, иначе значимые пробелы HELP
/// (`"Total HTTP requests."` против `"TotalHTTP requests."`) стали бы
/// неразличимыми и per-metric oracle пропустил бы drift (F7 / R2).
fn compact_json(text: &str) -> String {
let mut compact = String::with_capacity(text.len());
let mut in_string = false;
let mut escaped = false;
for ch in text.chars() {
if in_string {
compact.push(ch);
if escaped {
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == '"' {
in_string = false;
}
continue;
}
if ch == '"' {
in_string = true;
compact.push(ch);
} else if !ch.is_whitespace() {
compact.push(ch);
}
}
compact
}
/// `(name, compact object)` для каждой family из секции `"metrics":[`.
/// Секция ограничивается парным `]`, поэтому `budgets`/`http_routes` в неё не
/// попадают, а top-level объекты выделяются балансировкой скобок.
fn metric_objects(document: &str) -> Vec<(String, String)> {
let compact = compact_json(document);
let marker = "\"metrics\":[";
let metrics_at = compact.find(marker).expect("metrics section");
let array_start = metrics_at + marker.len() - 1;
let array_end = array_start + balanced_end(&compact[array_start..], b'[', b']');
let section = &compact[array_start + 1..array_end - 1];
let mut objects = Vec::new();
let mut cursor = 0_usize;
while let Some(offset) = section[cursor..].find('{') {
let at = cursor + offset;
let end = at + balanced_end(&section[at..], b'{', b'}');
let object = &section[at..end];
let name = unquote(&json_field(object, "name"));
objects.push((name, object.to_owned()));
cursor = end;
}
objects
}
/// Значение поля как compact JSON text: строка, массив, объект или scalar.
fn json_field(object: &str, key: &str) -> String {
let needle = format!("\"{key}\":");
let at = object
.find(&needle)
.unwrap_or_else(|| panic!("поле {key} отсутствует"));
let value = &object[at + needle.len()..];
match value.as_bytes().first() {
Some(b'"') => {
let end = value[1..].find('"').expect("string terminator");
value[..end + 2].to_owned()
}
Some(b'[') => value[..balanced_end(value, b'[', b']')].to_owned(),
Some(b'{') => value[..balanced_end(value, b'{', b'}')].to_owned(),
_ => value
.find([',', '}'])
.map_or_else(|| value.to_owned(), |end| value[..end].to_owned()),
}
}
fn balanced_end(value: &str, open: u8, close: u8) -> usize {
let mut depth = 0_usize;
for (index, byte) in value.bytes().enumerate() {
if byte == open {
depth += 1;
} else if byte == close {
depth = depth.saturating_sub(1);
if depth == 0 {
return index + 1;
}
}
}
panic!("unbalanced JSON value");
}
fn unquote(value: &str) -> String {
value.trim_matches('"').to_owned()
}
fn string_array(value: &str) -> Vec<String> {
let inner = &value[1..value.len() - 1];
let mut values = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = inner[cursor..].find('"') {
let at = cursor + at;
let after = &inner[at + 1..];
let end = after.find('"').expect("string terminator");
values.push(after[..end].to_owned());
cursor = at + 1 + end + 1;
}
values
}
fn label_entries(object: &str) -> Vec<RegistryLabel> {
let array = json_field(object, "labels");
let inner = array[1..array.len() - 1].to_owned();
let mut labels = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = inner[cursor..].find("{\"name\":") {
let at = cursor + at;
let end = at + balanced_end(&inner[at..], b'{', b'}');
let entry = &inner[at..end];
labels.push(RegistryLabel {
name: unquote(&json_field(entry, "name")),
class: unquote(&json_field(entry, "class")),
domain: if entry.contains("\"domain\":[") {
string_array(&json_field(entry, "domain"))
} else {
Vec::new()
},
domain_ref: entry
.contains("\"domain_ref\":")
.then(|| unquote(&json_field(entry, "domain_ref"))),
});
cursor = end;
}
labels
}
fn route_domain_v1(document: &str) -> Vec<String> {
let objects = metric_objects(document);
let (_, object) = objects
.iter()
.find(|(name, _)| name == "crank_http_requests_total")
.expect("v1 HTTP counter");
label_entries(object)
.into_iter()
.find(|label| label.name == "route")
.expect("v1 route label")
.domain
}
fn union_routes_v2(document: &str) -> Vec<String> {
let compact = compact_json(document);
let section = &compact[compact
.find("\"http_routes\":[")
.expect("http_routes section")..];
let needle = "\"route\":\"";
let mut routes = Vec::new();
let mut cursor = 0_usize;
while let Some(at) = section[cursor..].find(needle) {
let at = cursor + at + needle.len();
let end = section[at..].find('"').expect("route terminator");
routes.push(section[at..at + end].to_owned());
cursor = at + end + 1;
}
routes
}
+757
View File
@@ -0,0 +1,757 @@
//! Story 3.6 · AT-3.6-08 · phase A (ATDD, test-only) — closed route/method identity.
//!
//! Этот таргет на фазе A содержит **только** A-селекторы: они используют
//! существующее API `crank-metrics` и не требуют правок `src/**`.
//!
//! * `TD-H7a` — замкнутый классификатор HTTP-метода: известные verb'ы сохраняют
//! собственное значение enum, а `OTHER` присваивается только действительно
//! неизвестному token'у. «Известный-но-неподдерживаемый» verb (`OPTIONS`,
//! `HEAD`, `CONNECT`, `TRACE`) — это **не** `OTHER`.
//! * `TD-R6` — замкнутый классификатор route: каждый объявленный template
//! round-trip'ится без изменений, а сырой URI/query/concrete id, не совпавший
//! ни с одним literal, остаётся `unmatched`. Этот direct-classifier-оракул
//! принадлежит **только** unit-проверке (middleware передаёт `MatchedPath`, а
//! не raw URI: `crates/crank-observability/src/instrumentation.rs`).
//!
//! B-селекторы v2 (typed ownership union, per-process budget, projections)
//! добавляются в этот же таргет отдельной build-карточкой: на фазе A их API
//! отсутствует, и они не могут быть скомпилированы.
use std::collections::BTreeSet;
use crank_metrics::{
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpMethod, HttpRoute,
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_RENDERED_SERIES_PER_PROCESS, MCP_HTTP_ROUTE_DOMAIN, MetricDefinition, MetricKind,
MetricProcess, MetricService, MetricUnit, max_exemplar_slots, metric_schema,
metric_schema_for_service, normalize_http_route, render_metric_schema_json, schema_budget,
service_projection, validate_budget, validate_exemplar_budget, validate_http_routes,
validate_schema,
};
/// TD-H7a — closed method classification (чистая функция, без HTTP).
///
/// Оракул: `HttpMethod::classify` никогда не подменяет известный verb на `OTHER`
/// и не пропускает действительно неизвестный token в замкнутый домен.
#[test]
fn closed_methods_keep_their_value_and_only_unknown_is_other() {
// Замкнутый домен метода: ровно 10 значений, без дублей.
assert_eq!(
HttpMethod::ALL.len(),
HttpMethod::VALUES.len(),
"ALL и VALUES обязаны описывать один и тот же замкнутый домен"
);
assert_eq!(
HttpMethod::ALL.len(),
10,
"домен метода закрыт 10 значениями (GET/POST/PUT/PATCH/DELETE/OPTIONS/HEAD/CONNECT/TRACE/OTHER)"
);
for method in HttpMethod::ALL {
assert_eq!(
method.as_str(),
HttpMethod::VALUES[HttpMethod::ALL
.iter()
.position(|candidate| candidate == method)
.expect("ALL и VALUES обязаны быть согласованы по индексу")],
"ALL и VALUES обязаны быть согласованы"
);
}
let closed_values = HttpMethod::VALUES.iter().copied().collect::<BTreeSet<_>>();
assert_eq!(
closed_values.len(),
HttpMethod::VALUES.len(),
"значения замкнутого домена метода обязаны быть уникальны"
);
assert_eq!(
closed_values,
BTreeSet::from([
"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "CONNECT", "TRACE",
"OTHER",
]),
"замкнутый домен метода объявлен ровно этими десятью значениями"
);
// Round-trip: каждое значение домена классифицируется в само себя.
for method in HttpMethod::ALL {
assert_eq!(
HttpMethod::classify(method.as_str()),
*method,
"closed value `{}` обязан классифицироваться в себя",
method.as_str()
);
}
// Известный-но-неподдерживаемый verb сохраняет своё enum-значение и не является OTHER.
for (token, expected) in [
("OPTIONS", HttpMethod::Options),
("HEAD", HttpMethod::Head),
("CONNECT", HttpMethod::Connect),
("TRACE", HttpMethod::Trace),
("DELETE", HttpMethod::Delete),
("PATCH", HttpMethod::Patch),
] {
assert_eq!(
HttpMethod::classify(token),
expected,
"known verb `{token}` обязан сохранять своё значение, а не становиться OTHER"
);
assert_ne!(
HttpMethod::classify(token),
HttpMethod::Other,
"known-but-unsupported verb `{token}` не может быть OTHER"
);
}
// OTHER — только для действительно неизвестного token'а.
for unknown in [
"FOO",
"CUSTOM-x",
"PROPFIND",
"get",
"Get",
"",
"GET ",
"GET\t",
"X-User-Controlled",
] {
assert_eq!(
HttpMethod::classify(unknown),
HttpMethod::Other,
"неизвестный HTTP-token `{unknown}` обязан давать OTHER"
);
assert!(
!HttpMethod::VALUES.contains(&unknown),
"неизвестный token `{unknown}` не может попасть в замкнутый домен метода"
);
}
}
/// TD-R6 — closed route classifier + round-trip (чистая функция, без HTTP).
#[test]
fn http_route_classifier_is_closed_and_round_trips() {
// Домен замкнут и не содержит дублей.
let closed = HTTP_ROUTE_DOMAIN.iter().copied().collect::<BTreeSet<_>>();
assert_eq!(
closed.len(),
HTTP_ROUTE_DOMAIN.len(),
"HTTP_ROUTE_DOMAIN не может объявлять один template дважды"
);
assert!(
HTTP_ROUTE_DOMAIN.contains(&"unmatched"),
"домен обязан объявлять единственное не-route значение `unmatched`"
);
// Каждый объявленный template (кроме самого `unmatched`) round-trip'ится без изменений.
let mut templates = 0_usize;
for template in HTTP_ROUTE_DOMAIN {
if *template == "unmatched" {
continue;
}
templates += 1;
assert_eq!(
HttpRoute::from_matched_path(template).as_str(),
*template,
"объявленный template `{template}` обязан round-trip'иться"
);
assert_eq!(
HttpRoute::unmatched().as_str(),
"unmatched",
"константа unmatched обязана оставаться `unmatched`"
);
}
assert!(
templates > 0,
"домен обязан объявлять хотя бы один реальный template"
);
// Сырой URI/query/concrete id никогда не становится известным template:
// direct-classifier-оракул, который middleware не использует (там MatchedPath).
for raw in [
"unmatched",
"/unknown/raw/path",
"/api/admin/workspaces/ws_customer/operations/op_123",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/42",
"/api/admin/workspaces/ws_customer/resources?page=2",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/preview?inline=1",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/publish",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/revoke",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3/content",
"/health?probe=1",
"/api/admin/workspaces/ws_customer/does-not-exist",
] {
assert_eq!(
HttpRoute::from_matched_path(raw).as_str(),
"unmatched",
"сырое значение `{raw}` не является объявленным template и обязано давать unmatched"
);
}
}
// ---------------------------------------------------------------------------
// Фаза B — typed ownership union, per-process projections/bounds/budgets.
// ---------------------------------------------------------------------------
const RESOURCE_TEMPLATES: [&str; 13] = [
"/api/admin/workspaces/{workspace_id}/resources",
"/api/admin/workspaces/{workspace_id}/resources/import",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/archive",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/content",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/export",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/preview",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/publish",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/revoke",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/content",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/export",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/test-runs",
];
const PROMPT_TEMPLATES: [&str; 6] = [
"/api/admin/workspaces/{workspace_id}/prompts",
"/api/admin/workspaces/{workspace_id}/prompts/import",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/export",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/preview",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/versions/{version}/export",
];
fn route_literals(source: &str) -> Vec<String> {
let mut routes = Vec::new();
let mut remaining = source;
while let Some(offset) = remaining.find(".route(") {
remaining = &remaining[offset + ".route(".len()..];
let Some(start) = remaining.find('"') else {
break;
};
let after_start = &remaining[start + 1..];
let Some(end) = after_start.find('"') else {
break;
};
routes.push(after_start[..end].to_owned());
remaining = &after_start[end + 1..];
}
routes
}
/// Canonical admin router inventory (F1 fixture): `unmatched` + every literal
/// canonicalised into its admin path family.
fn admin_router_inventory() -> BTreeSet<String> {
let source = include_str!("../../../apps/admin-api/src/app.rs");
let auth = [
"/bootstrap/status",
"/bootstrap/complete",
"/login",
"/logout",
"/session",
"/session/csrf",
"/profile",
"/password",
];
let admin_root = ["/capabilities", "/workspaces", "/workspaces/{workspace_id}"];
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
for route in route_literals(source) {
let canonical = if matches!(route.as_str(), "/health" | "/ready") {
route
} else if auth.contains(&route.as_str()) {
format!("/api/auth{route}")
} else if admin_root.contains(&route.as_str()) {
format!("/api/admin{route}")
} else {
format!("/api/admin/workspaces/{{workspace_id}}{route}")
};
actual.insert(canonical);
}
actual
}
fn mcp_router_inventory() -> BTreeSet<String> {
let source = include_str!("../../crank-community-mcp/src/app.rs");
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
actual.extend(route_literals(source));
actual
}
fn domain_of(routes: &[&str]) -> BTreeSet<String> {
routes.iter().map(|route| (*route).to_owned()).collect()
}
/// TD-R1 — typed ownership union двусторонне равен реальному router inventory.
#[test]
fn ownership_union_is_exactly_the_router_inventory() {
validate_http_routes(HTTP_ROUTES)
.expect("the single ownership table must be structurally valid");
let expected = domain_of(HTTP_ROUTE_DOMAIN);
assert_eq!(
expected.len(),
91,
"union обязан объявлять 91 идентичностей"
);
let mut actual = admin_router_inventory();
actual.extend(mcp_router_inventory());
assert_eq!(
actual, expected,
"union и реальные routers обязаны совпасть"
);
assert_eq!(
HTTP_ROUTES.len(),
HTTP_ROUTE_DOMAIN.len(),
"домен обязан выводиться из той же таблицы без второй истины"
);
}
/// TD-R2 — per-service projections равны соответствующим router files.
#[test]
fn service_projections_match_router_files() {
assert_eq!(ADMIN_HTTP_ROUTE_DOMAIN.len(), 86, "admin-проекция = 86");
assert_eq!(MCP_HTTP_ROUTE_DOMAIN.len(), 8, "mcp-проекция = 8");
assert_eq!(
domain_of(ADMIN_HTTP_ROUTE_DOMAIN),
admin_router_inventory(),
"admin-проекция обязана совпасть с apps/admin-api/src/app.rs"
);
assert_eq!(
domain_of(MCP_HTTP_ROUTE_DOMAIN),
mcp_router_inventory(),
"mcp-проекция обязана совпасть с crates/crank-community-mcp/src/app.rs"
);
for service in [MetricService::AdminApi, MetricService::McpServer] {
let names = service_projection(service)
.iter()
.map(|definition| definition.name)
.collect::<BTreeSet<_>>();
assert!(
names.contains("crank_http_requests_total"),
"каждая проекция обязана объявлять HTTP counter"
);
}
}
/// TD-R3 — shared ровно три, prefix-ownership exact, никаких wildcard.
#[test]
fn shared_and_prefix_ownership_is_exact() {
let shared = HTTP_ROUTES
.iter()
.filter(|row| row.processes.len() == 2)
.map(|row| row.route)
.collect::<BTreeSet<_>>();
assert_eq!(
shared,
BTreeSet::from(["/health", "/ready", "unmatched"]),
"policy owners совпадают ровно на трёх общих строках"
);
for row in HTTP_ROUTES {
if row.route.starts_with("/api/auth/") || row.route.starts_with("/api/admin/") {
assert_eq!(
row.processes,
&[MetricProcess::AdminApi],
"{} обязана принадлежать только admin_api",
row.route
);
}
if row.route.starts_with("/v1/") {
assert_eq!(
row.processes,
&[MetricProcess::McpServer],
"{} обязана принадлежать только mcp_server",
row.route
);
}
assert!(
row.route == "unmatched" || row.route.starts_with('/'),
"{} — не route template",
row.route
);
assert!(
!row.route.contains('*'),
"{} не может использовать wildcard matching",
row.route
);
}
}
/// TD-R4 — тринадцать Resource-шаблонов: admin-owned добавления к v1-домену.
#[test]
fn resource_templates_are_admin_owned_additions() {
const FROZEN_V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
for template in RESOURCE_TEMPLATES {
assert!(
HTTP_ROUTE_DOMAIN.contains(&template),
"{template} обязан войти в union"
);
assert_eq!(
crank_metrics::http_route_processes(template),
Some(&[MetricProcess::AdminApi][..]),
"{template} обязан принадлежать admin_api"
);
assert!(
!FROZEN_V1.contains(template),
"{template} не может быть частью замороженного v1-домена"
);
assert_eq!(
HttpRoute::from_matched_path(template).as_str(),
template,
"{template} обязан round-trip'иться после добавления"
);
assert_eq!(
normalize_http_route(
MetricService::AdminApi,
HttpRoute::from_matched_path(template)
)
.as_str(),
template,
"{template} обязан оставаться собой в admin-метриках, а не unmatched"
);
}
assert_eq!(
HTTP_ROUTE_DOMAIN.len() - RESOURCE_TEMPLATES.len(),
78,
"v1-домен + тринадцать Resource и шесть Prompt additions = union 91"
);
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
}
#[test]
fn prompt_templates_are_admin_owned_and_normalized() {
for template in PROMPT_TEMPLATES {
assert!(HTTP_ROUTE_DOMAIN.contains(&template));
assert_eq!(
crank_metrics::http_route_processes(template),
Some(&[MetricProcess::AdminApi][..])
);
assert_eq!(
normalize_http_route(
MetricService::AdminApi,
HttpRoute::from_matched_path(template)
)
.as_str(),
template
);
}
assert_eq!(PROMPT_TEMPLATES.len(), 6);
}
/// TD-R5 — таблица отвергает дубликаты, пустые и дублирующиеся owners.
#[test]
fn ownership_table_rejects_duplicates_and_empty_owners() {
validate_http_routes(HTTP_ROUTES).expect("production table must validate");
let duplicate = [
HTTP_ROUTES[0],
crank_metrics::HttpRouteDefinition {
route: HTTP_ROUTES[0].route,
processes: &[MetricProcess::McpServer],
},
];
assert_eq!(
validate_http_routes(&duplicate),
Err(crank_metrics::SchemaError::DuplicateMetric)
);
let empty = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[],
}];
assert_eq!(
validate_http_routes(&empty),
Err(crank_metrics::SchemaError::InvalidMetric)
);
let duplicated_owner = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[MetricProcess::AdminApi, MetricProcess::AdminApi],
}];
assert_eq!(
validate_http_routes(&duplicated_owner),
Err(crank_metrics::SchemaError::InvalidMetric)
);
let without_unmatched = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[MetricProcess::AdminApi],
}];
assert_eq!(
validate_http_routes(&without_unmatched),
Err(crank_metrics::SchemaError::InvalidDomain)
);
}
/// TD-M1 — bounds каждой проекции равны своим формулам `L`/`R`/`E`.
#[test]
fn per_process_bounds_equal_their_formulas() {
for service in [MetricService::AdminApi, MetricService::McpServer] {
for definition in service_projection(service) {
let logical = definition
.label_domains
.iter()
.map(|domain| domain.values.len())
.product::<usize>()
.max(1);
let rendered = if definition.kind == MetricKind::Histogram {
logical * (definition.buckets.len() + 3)
} else {
logical
};
let exemplars = if definition.kind == MetricKind::Histogram {
logical * (definition.buckets.len() + 1)
} else {
0
};
assert_eq!(
definition.max_logical_series,
logical,
"{}/{} logical",
definition.name,
service.process().as_str()
);
assert_eq!(
definition.max_rendered_series,
rendered,
"{}/{} rendered",
definition.name,
service.process().as_str()
);
assert_eq!(
definition.max_exemplar_slots(),
exemplars,
"{}/{} exemplar slots",
definition.name,
service.process().as_str()
);
assert!(
definition.label_domains.iter().all(|domain| {
domain.name != "route" || {
let allowed = match service {
MetricService::AdminApi => ADMIN_HTTP_ROUTE_DOMAIN,
MetricService::McpServer => MCP_HTTP_ROUTE_DOMAIN,
};
domain.values == allowed
}
}),
"{}/{} обязана нести только свою route-проекцию",
definition.name,
service.process().as_str()
);
}
}
}
/// TD-M2 — root.budgets содержит ровно два per-process бюджета, union-бюджета нет.
#[test]
fn root_budgets_are_per_process_only() {
let rendered = render_metric_schema_json().expect("v2 renders");
assert_eq!(
rendered.matches("\"budgets\":").count(),
1,
"root обязан объявлять ровно один ключ budgets"
);
assert!(rendered.ends_with(
",\"budgets\":[{\"process\":\"admin_api\",\"families\":15,\"logical_series\":6285,\
\"rendered_series\":19515,\"exemplar_slots\":12348},{\"process\":\"mcp_server\",\
\"families\":23,\"logical_series\":1083,\"rendered_series\":3558,\"exemplar_slots\":2310}]}\n"
));
assert_eq!(
schema_budget(MetricService::AdminApi),
Ok(crank_metrics::SchemaBudget {
logical_series: 6_285,
rendered_series: 19_515
})
);
assert_eq!(
schema_budget(MetricService::McpServer),
Ok(crank_metrics::SchemaBudget {
logical_series: 1_083,
rendered_series: 3_558
})
);
}
/// TD-M3 — frozen caps и границы `validate_exemplar_budget` точны.
#[test]
fn frozen_caps_and_edges_are_exact() {
assert_eq!(MAX_LOGICAL_SERIES_PER_PROCESS, 6_285);
assert_eq!(MAX_RENDERED_SERIES_PER_PROCESS, 19_515);
assert_eq!(MAX_EXEMPLAR_SLOTS_PER_PROCESS, 12_348);
assert!(validate_budget(6_285, 19_515).is_ok());
assert!(validate_budget(6_286, 19_515).is_err());
assert!(validate_exemplar_budget(12_347).is_ok());
assert!(validate_exemplar_budget(12_348).is_ok());
assert!(validate_exemplar_budget(12_349).is_err());
for service in [MetricService::AdminApi, MetricService::McpServer] {
let budget = schema_budget(service).expect("projection budget valid");
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
validate_exemplar_budget(max_exemplar_slots(service))
.expect("capacity inside the hard cap");
}
}
/// TD-M4 — любая испорченная проекция отвергается валидатором.
#[test]
fn any_invalid_projection_fails_validation() {
let base = *service_projection(MetricService::AdminApi)
.iter()
.find(|definition| definition.name == "crank_http_requests_total")
.expect("http counter present in admin projection");
let wrong_ceiling = MetricDefinition {
max_logical_series: base.max_logical_series + 1,
..base
};
assert_eq!(
validate_schema(&[wrong_ceiling]),
Err(crank_metrics::SchemaError::InvalidCeiling)
);
let wrong_domain = MetricDefinition {
label_domains: Box::leak(
base.label_domains
.iter()
.map(|domain| {
if domain.name == "route" {
crank_metrics::LabelDomain {
values: &["/definitely-not-a-route"],
..*domain
}
} else {
*domain
}
})
.collect::<Vec<_>>()
.into_boxed_slice(),
),
..base
};
assert_eq!(
validate_schema(&[wrong_domain]),
Err(crank_metrics::SchemaError::InvalidCeiling)
);
let mut mutated = service_projection(MetricService::AdminApi).to_vec();
mutated[0].max_rendered_series = 0;
assert!(
validate_schema(&mutated).is_err(),
"проекция с несогласованным ceiling обязана падать"
);
// Каждый invalid case проверяется для **обоих** сервисов: даже если
// запускается другой процесс, отказ обязан быть одинаковым.
for service in [MetricService::AdminApi, MetricService::McpServer] {
validate_schema(service_projection(service)).expect("production projection valid");
}
}
/// TD-M5 — checked-арифметика: реальное превышение per-process бюджета обязано
/// отвергаться типизированным `BudgetExceeded`, насыщенные metadata — типизированным
/// `InvalidCeiling`; ни один счётчик не принимается «почти верным».
#[test]
fn arithmetic_overflow_is_typed_and_not_saturated() {
let saturated = MetricDefinition {
name: "crank_test_total",
kind: MetricKind::Counter,
unit: MetricUnit::Count,
labels: &[],
label_domains: &[],
buckets: &[],
processes: &[MetricProcess::AdminApi],
max_logical_series: usize::MAX,
max_rendered_series: usize::MAX,
description: "saturated counter",
};
assert_eq!(
validate_schema(&[saturated]),
Err(crank_metrics::SchemaError::InvalidCeiling),
"насыщенный ceiling обязан быть отвергнут, а не принят"
);
// Настоящая арифметика: домен ровно на единицу больше frozen per-process
// лимита. Metadata точные (не насыщенные), поэтому отказ обязан быть
// типизированным BudgetExceeded, а не InvalidCeiling/срезом.
let oversize = MAX_LOGICAL_SERIES_PER_PROCESS + 1;
let values: &'static [&'static str] = Box::leak(
(0..oversize)
.map(|index| Box::leak(format!("value_{index}").into_boxed_str()) as &'static str)
.collect::<Vec<&'static str>>()
.into_boxed_slice(),
);
let oversize_domains: &'static [crank_metrics::LabelDomain] = Box::leak(
vec![crank_metrics::LabelDomain {
name: "state",
class: crank_metrics::LabelClass::ProductClosed,
values,
}]
.into_boxed_slice(),
);
let oversize_definition = MetricDefinition {
name: "crank_test_oversize_total",
kind: MetricKind::Counter,
unit: MetricUnit::Count,
labels: &["state"],
label_domains: oversize_domains,
buckets: &[],
processes: &[MetricProcess::AdminApi],
max_logical_series: oversize,
max_rendered_series: oversize,
description: "oversize counter",
};
assert_eq!(
validate_schema(&[oversize_definition]),
Err(crank_metrics::SchemaError::BudgetExceeded),
"точный бюджет больше лимита обязан отвергаться типизированно"
);
assert_eq!(
validate_budget(oversize, oversize),
Err(crank_metrics::SchemaError::BudgetExceeded),
"BudgetExceeded обязан быть типизированным на самой границе"
);
assert!(
validate_budget(
MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_RENDERED_SERIES_PER_PROCESS
)
.is_ok()
);
for service in [MetricService::AdminApi, MetricService::McpServer] {
for definition in service_projection(service) {
assert_ne!(
definition.max_logical_series,
usize::MAX,
"{} не может нести насыщенное значение",
definition.name
);
assert_ne!(definition.max_rendered_series, usize::MAX);
}
}
}
/// TD-M6 — capacity вычисляется по сервису и укладывается в hard cap.
#[test]
fn exemplar_capacity_is_service_computed_and_capped() {
assert_eq!(max_exemplar_slots(MetricService::AdminApi), 12_348);
assert_eq!(max_exemplar_slots(MetricService::McpServer), 2_310);
assert!(max_exemplar_slots(MetricService::AdminApi) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
assert!(max_exemplar_slots(MetricService::McpServer) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
assert_ne!(
max_exemplar_slots(MetricService::AdminApi),
14_658,
"derived union capacity не может использоваться как лимит процесса"
);
}
/// TD-M7 — per-service projection cache создаётся один раз.
#[test]
fn service_projection_cache_is_allocated_once() {
for service in [MetricService::AdminApi, MetricService::McpServer] {
let first = service_projection(service);
let second = service_projection(service);
assert!(
std::ptr::eq(first, second),
"проекция обязана быть стабильно закеширована"
);
let again = metric_schema_for_service(service).count();
assert_eq!(again, first.len());
}
assert_eq!(
metric_schema().len(),
23,
"union metadata сохраняет 23 family"
);
}