feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s

Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

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,
}
}