Files
crank/crates/crank-metrics/tests/schema_v2.rs
T
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08:22 +00:00

758 lines
30 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Story 3.6 · AT-3.6-08 · phase A (ATDD, test-only) — closed route/method identity.
//!
//! Этот таргет на фазе A содержит **только** A-селекторы: они используют
//! существующее API `crank-metrics` и не требуют правок `src/**`.
//!
//! * `TD-H7a` — замкнутый классификатор HTTP-метода: известные verb'ы сохраняют
//! собственное значение enum, а `OTHER` присваивается только действительно
//! неизвестному token'у. «Известный-но-неподдерживаемый» verb (`OPTIONS`,
//! `HEAD`, `CONNECT`, `TRACE`) — это **не** `OTHER`.
//! * `TD-R6` — замкнутый классификатор route: каждый объявленный template
//! round-trip'ится без изменений, а сырой URI/query/concrete id, не совпавший
//! ни с одним literal, остаётся `unmatched`. Этот direct-classifier-оракул
//! принадлежит **только** unit-проверке (middleware передаёт `MatchedPath`, а
//! не raw URI: `crates/crank-observability/src/instrumentation.rs`).
//!
//! B-селекторы v2 (typed ownership union, per-process budget, projections)
//! добавляются в этот же таргет отдельной build-карточкой: на фазе A их API
//! отсутствует, и они не могут быть скомпилированы.
use std::collections::BTreeSet;
use crank_metrics::{
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpMethod, HttpRoute,
MAX_EXEMPLAR_SLOTS_PER_PROCESS, MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_RENDERED_SERIES_PER_PROCESS, MCP_HTTP_ROUTE_DOMAIN, MetricDefinition, MetricKind,
MetricProcess, MetricService, MetricUnit, max_exemplar_slots, metric_schema,
metric_schema_for_service, normalize_http_route, render_metric_schema_json, schema_budget,
service_projection, validate_budget, validate_exemplar_budget, validate_http_routes,
validate_schema,
};
/// TD-H7a — closed method classification (чистая функция, без HTTP).
///
/// Оракул: `HttpMethod::classify` никогда не подменяет известный verb на `OTHER`
/// и не пропускает действительно неизвестный token в замкнутый домен.
#[test]
fn closed_methods_keep_their_value_and_only_unknown_is_other() {
// Замкнутый домен метода: ровно 10 значений, без дублей.
assert_eq!(
HttpMethod::ALL.len(),
HttpMethod::VALUES.len(),
"ALL и VALUES обязаны описывать один и тот же замкнутый домен"
);
assert_eq!(
HttpMethod::ALL.len(),
10,
"домен метода закрыт 10 значениями (GET/POST/PUT/PATCH/DELETE/OPTIONS/HEAD/CONNECT/TRACE/OTHER)"
);
for method in HttpMethod::ALL {
assert_eq!(
method.as_str(),
HttpMethod::VALUES[HttpMethod::ALL
.iter()
.position(|candidate| candidate == method)
.expect("ALL и VALUES обязаны быть согласованы по индексу")],
"ALL и VALUES обязаны быть согласованы"
);
}
let closed_values = HttpMethod::VALUES.iter().copied().collect::<BTreeSet<_>>();
assert_eq!(
closed_values.len(),
HttpMethod::VALUES.len(),
"значения замкнутого домена метода обязаны быть уникальны"
);
assert_eq!(
closed_values,
BTreeSet::from([
"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "CONNECT", "TRACE",
"OTHER",
]),
"замкнутый домен метода объявлен ровно этими десятью значениями"
);
// Round-trip: каждое значение домена классифицируется в само себя.
for method in HttpMethod::ALL {
assert_eq!(
HttpMethod::classify(method.as_str()),
*method,
"closed value `{}` обязан классифицироваться в себя",
method.as_str()
);
}
// Известный-но-неподдерживаемый verb сохраняет своё enum-значение и не является OTHER.
for (token, expected) in [
("OPTIONS", HttpMethod::Options),
("HEAD", HttpMethod::Head),
("CONNECT", HttpMethod::Connect),
("TRACE", HttpMethod::Trace),
("DELETE", HttpMethod::Delete),
("PATCH", HttpMethod::Patch),
] {
assert_eq!(
HttpMethod::classify(token),
expected,
"known verb `{token}` обязан сохранять своё значение, а не становиться OTHER"
);
assert_ne!(
HttpMethod::classify(token),
HttpMethod::Other,
"known-but-unsupported verb `{token}` не может быть OTHER"
);
}
// OTHER — только для действительно неизвестного token'а.
for unknown in [
"FOO",
"CUSTOM-x",
"PROPFIND",
"get",
"Get",
"",
"GET ",
"GET\t",
"X-User-Controlled",
] {
assert_eq!(
HttpMethod::classify(unknown),
HttpMethod::Other,
"неизвестный HTTP-token `{unknown}` обязан давать OTHER"
);
assert!(
!HttpMethod::VALUES.contains(&unknown),
"неизвестный token `{unknown}` не может попасть в замкнутый домен метода"
);
}
}
/// TD-R6 — closed route classifier + round-trip (чистая функция, без HTTP).
#[test]
fn http_route_classifier_is_closed_and_round_trips() {
// Домен замкнут и не содержит дублей.
let closed = HTTP_ROUTE_DOMAIN.iter().copied().collect::<BTreeSet<_>>();
assert_eq!(
closed.len(),
HTTP_ROUTE_DOMAIN.len(),
"HTTP_ROUTE_DOMAIN не может объявлять один template дважды"
);
assert!(
HTTP_ROUTE_DOMAIN.contains(&"unmatched"),
"домен обязан объявлять единственное не-route значение `unmatched`"
);
// Каждый объявленный template (кроме самого `unmatched`) round-trip'ится без изменений.
let mut templates = 0_usize;
for template in HTTP_ROUTE_DOMAIN {
if *template == "unmatched" {
continue;
}
templates += 1;
assert_eq!(
HttpRoute::from_matched_path(template).as_str(),
*template,
"объявленный template `{template}` обязан round-trip'иться"
);
assert_eq!(
HttpRoute::unmatched().as_str(),
"unmatched",
"константа unmatched обязана оставаться `unmatched`"
);
}
assert!(
templates > 0,
"домен обязан объявлять хотя бы один реальный template"
);
// Сырой URI/query/concrete id никогда не становится известным template:
// direct-classifier-оракул, который middleware не использует (там MatchedPath).
for raw in [
"unmatched",
"/unknown/raw/path",
"/api/admin/workspaces/ws_customer/operations/op_123",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/42",
"/api/admin/workspaces/ws_customer/resources?page=2",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/preview?inline=1",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/publish",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/revoke",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3",
"/api/admin/workspaces/ws_customer/resources/res_9f3a/versions/3/content",
"/health?probe=1",
"/api/admin/workspaces/ws_customer/does-not-exist",
] {
assert_eq!(
HttpRoute::from_matched_path(raw).as_str(),
"unmatched",
"сырое значение `{raw}` не является объявленным template и обязано давать unmatched"
);
}
}
// ---------------------------------------------------------------------------
// Фаза B — typed ownership union, per-process projections/bounds/budgets.
// ---------------------------------------------------------------------------
const RESOURCE_TEMPLATES: [&str; 13] = [
"/api/admin/workspaces/{workspace_id}/resources",
"/api/admin/workspaces/{workspace_id}/resources/import",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/archive",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/content",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/export",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/preview",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/publish",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/revoke",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/content",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/versions/{version}/export",
"/api/admin/workspaces/{workspace_id}/resources/{resource_id}/test-runs",
];
const PROMPT_TEMPLATES: [&str; 6] = [
"/api/admin/workspaces/{workspace_id}/prompts",
"/api/admin/workspaces/{workspace_id}/prompts/import",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/export",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/preview",
"/api/admin/workspaces/{workspace_id}/prompts/{prompt_id}/versions/{version}/export",
];
fn route_literals(source: &str) -> Vec<String> {
let mut routes = Vec::new();
let mut remaining = source;
while let Some(offset) = remaining.find(".route(") {
remaining = &remaining[offset + ".route(".len()..];
let Some(start) = remaining.find('"') else {
break;
};
let after_start = &remaining[start + 1..];
let Some(end) = after_start.find('"') else {
break;
};
routes.push(after_start[..end].to_owned());
remaining = &after_start[end + 1..];
}
routes
}
/// Canonical admin router inventory (F1 fixture): `unmatched` + every literal
/// canonicalised into its admin path family.
fn admin_router_inventory() -> BTreeSet<String> {
let source = include_str!("../../../apps/admin-api/src/app.rs");
let auth = [
"/bootstrap/status",
"/bootstrap/complete",
"/login",
"/logout",
"/session",
"/session/csrf",
"/profile",
"/password",
];
let admin_root = ["/capabilities", "/workspaces", "/workspaces/{workspace_id}"];
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
for route in route_literals(source) {
let canonical = if matches!(route.as_str(), "/health" | "/ready") {
route
} else if auth.contains(&route.as_str()) {
format!("/api/auth{route}")
} else if admin_root.contains(&route.as_str()) {
format!("/api/admin{route}")
} else {
format!("/api/admin/workspaces/{{workspace_id}}{route}")
};
actual.insert(canonical);
}
actual
}
fn mcp_router_inventory() -> BTreeSet<String> {
let source = include_str!("../../crank-community-mcp/src/app.rs");
let mut actual = BTreeSet::from(["unmatched".to_owned()]);
actual.extend(route_literals(source));
actual
}
fn domain_of(routes: &[&str]) -> BTreeSet<String> {
routes.iter().map(|route| (*route).to_owned()).collect()
}
/// TD-R1 — typed ownership union двусторонне равен реальному router inventory.
#[test]
fn ownership_union_is_exactly_the_router_inventory() {
validate_http_routes(HTTP_ROUTES)
.expect("the single ownership table must be structurally valid");
let expected = domain_of(HTTP_ROUTE_DOMAIN);
assert_eq!(
expected.len(),
91,
"union обязан объявлять 91 идентичностей"
);
let mut actual = admin_router_inventory();
actual.extend(mcp_router_inventory());
assert_eq!(
actual, expected,
"union и реальные routers обязаны совпасть"
);
assert_eq!(
HTTP_ROUTES.len(),
HTTP_ROUTE_DOMAIN.len(),
"домен обязан выводиться из той же таблицы без второй истины"
);
}
/// TD-R2 — per-service projections равны соответствующим router files.
#[test]
fn service_projections_match_router_files() {
assert_eq!(ADMIN_HTTP_ROUTE_DOMAIN.len(), 86, "admin-проекция = 86");
assert_eq!(MCP_HTTP_ROUTE_DOMAIN.len(), 8, "mcp-проекция = 8");
assert_eq!(
domain_of(ADMIN_HTTP_ROUTE_DOMAIN),
admin_router_inventory(),
"admin-проекция обязана совпасть с apps/admin-api/src/app.rs"
);
assert_eq!(
domain_of(MCP_HTTP_ROUTE_DOMAIN),
mcp_router_inventory(),
"mcp-проекция обязана совпасть с crates/crank-community-mcp/src/app.rs"
);
for service in [MetricService::AdminApi, MetricService::McpServer] {
let names = service_projection(service)
.iter()
.map(|definition| definition.name)
.collect::<BTreeSet<_>>();
assert!(
names.contains("crank_http_requests_total"),
"каждая проекция обязана объявлять HTTP counter"
);
}
}
/// TD-R3 — shared ровно три, prefix-ownership exact, никаких wildcard.
#[test]
fn shared_and_prefix_ownership_is_exact() {
let shared = HTTP_ROUTES
.iter()
.filter(|row| row.processes.len() == 2)
.map(|row| row.route)
.collect::<BTreeSet<_>>();
assert_eq!(
shared,
BTreeSet::from(["/health", "/ready", "unmatched"]),
"policy owners совпадают ровно на трёх общих строках"
);
for row in HTTP_ROUTES {
if row.route.starts_with("/api/auth/") || row.route.starts_with("/api/admin/") {
assert_eq!(
row.processes,
&[MetricProcess::AdminApi],
"{} обязана принадлежать только admin_api",
row.route
);
}
if row.route.starts_with("/v1/") {
assert_eq!(
row.processes,
&[MetricProcess::McpServer],
"{} обязана принадлежать только mcp_server",
row.route
);
}
assert!(
row.route == "unmatched" || row.route.starts_with('/'),
"{} — не route template",
row.route
);
assert!(
!row.route.contains('*'),
"{} не может использовать wildcard matching",
row.route
);
}
}
/// TD-R4 — тринадцать Resource-шаблонов: admin-owned добавления к v1-домену.
#[test]
fn resource_templates_are_admin_owned_additions() {
const FROZEN_V1: &str = include_str!("../../../docs/schemas/metrics-registry-v1.json");
for template in RESOURCE_TEMPLATES {
assert!(
HTTP_ROUTE_DOMAIN.contains(&template),
"{template} обязан войти в union"
);
assert_eq!(
crank_metrics::http_route_processes(template),
Some(&[MetricProcess::AdminApi][..]),
"{template} обязан принадлежать admin_api"
);
assert!(
!FROZEN_V1.contains(template),
"{template} не может быть частью замороженного v1-домена"
);
assert_eq!(
HttpRoute::from_matched_path(template).as_str(),
template,
"{template} обязан round-trip'иться после добавления"
);
assert_eq!(
normalize_http_route(
MetricService::AdminApi,
HttpRoute::from_matched_path(template)
)
.as_str(),
template,
"{template} обязан оставаться собой в admin-метриках, а не unmatched"
);
}
assert_eq!(
HTTP_ROUTE_DOMAIN.len() - RESOURCE_TEMPLATES.len(),
78,
"v1-домен + тринадцать Resource и шесть Prompt additions = union 91"
);
assert_eq!(HTTP_ROUTE_DOMAIN.len(), 91);
}
#[test]
fn prompt_templates_are_admin_owned_and_normalized() {
for template in PROMPT_TEMPLATES {
assert!(HTTP_ROUTE_DOMAIN.contains(&template));
assert_eq!(
crank_metrics::http_route_processes(template),
Some(&[MetricProcess::AdminApi][..])
);
assert_eq!(
normalize_http_route(
MetricService::AdminApi,
HttpRoute::from_matched_path(template)
)
.as_str(),
template
);
}
assert_eq!(PROMPT_TEMPLATES.len(), 6);
}
/// TD-R5 — таблица отвергает дубликаты, пустые и дублирующиеся owners.
#[test]
fn ownership_table_rejects_duplicates_and_empty_owners() {
validate_http_routes(HTTP_ROUTES).expect("production table must validate");
let duplicate = [
HTTP_ROUTES[0],
crank_metrics::HttpRouteDefinition {
route: HTTP_ROUTES[0].route,
processes: &[MetricProcess::McpServer],
},
];
assert_eq!(
validate_http_routes(&duplicate),
Err(crank_metrics::SchemaError::DuplicateMetric)
);
let empty = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[],
}];
assert_eq!(
validate_http_routes(&empty),
Err(crank_metrics::SchemaError::InvalidMetric)
);
let duplicated_owner = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[MetricProcess::AdminApi, MetricProcess::AdminApi],
}];
assert_eq!(
validate_http_routes(&duplicated_owner),
Err(crank_metrics::SchemaError::InvalidMetric)
);
let without_unmatched = [crank_metrics::HttpRouteDefinition {
route: "/health",
processes: &[MetricProcess::AdminApi],
}];
assert_eq!(
validate_http_routes(&without_unmatched),
Err(crank_metrics::SchemaError::InvalidDomain)
);
}
/// TD-M1 — bounds каждой проекции равны своим формулам `L`/`R`/`E`.
#[test]
fn per_process_bounds_equal_their_formulas() {
for service in [MetricService::AdminApi, MetricService::McpServer] {
for definition in service_projection(service) {
let logical = definition
.label_domains
.iter()
.map(|domain| domain.values.len())
.product::<usize>()
.max(1);
let rendered = if definition.kind == MetricKind::Histogram {
logical * (definition.buckets.len() + 3)
} else {
logical
};
let exemplars = if definition.kind == MetricKind::Histogram {
logical * (definition.buckets.len() + 1)
} else {
0
};
assert_eq!(
definition.max_logical_series,
logical,
"{}/{} logical",
definition.name,
service.process().as_str()
);
assert_eq!(
definition.max_rendered_series,
rendered,
"{}/{} rendered",
definition.name,
service.process().as_str()
);
assert_eq!(
definition.max_exemplar_slots(),
exemplars,
"{}/{} exemplar slots",
definition.name,
service.process().as_str()
);
assert!(
definition.label_domains.iter().all(|domain| {
domain.name != "route" || {
let allowed = match service {
MetricService::AdminApi => ADMIN_HTTP_ROUTE_DOMAIN,
MetricService::McpServer => MCP_HTTP_ROUTE_DOMAIN,
};
domain.values == allowed
}
}),
"{}/{} обязана нести только свою route-проекцию",
definition.name,
service.process().as_str()
);
}
}
}
/// TD-M2 — root.budgets содержит ровно два per-process бюджета, union-бюджета нет.
#[test]
fn root_budgets_are_per_process_only() {
let rendered = render_metric_schema_json().expect("v2 renders");
assert_eq!(
rendered.matches("\"budgets\":").count(),
1,
"root обязан объявлять ровно один ключ budgets"
);
assert!(rendered.ends_with(
",\"budgets\":[{\"process\":\"admin_api\",\"families\":15,\"logical_series\":6285,\
\"rendered_series\":19515,\"exemplar_slots\":12348},{\"process\":\"mcp_server\",\
\"families\":23,\"logical_series\":1083,\"rendered_series\":3558,\"exemplar_slots\":2310}]}\n"
));
assert_eq!(
schema_budget(MetricService::AdminApi),
Ok(crank_metrics::SchemaBudget {
logical_series: 6_285,
rendered_series: 19_515
})
);
assert_eq!(
schema_budget(MetricService::McpServer),
Ok(crank_metrics::SchemaBudget {
logical_series: 1_083,
rendered_series: 3_558
})
);
}
/// TD-M3 — frozen caps и границы `validate_exemplar_budget` точны.
#[test]
fn frozen_caps_and_edges_are_exact() {
assert_eq!(MAX_LOGICAL_SERIES_PER_PROCESS, 6_285);
assert_eq!(MAX_RENDERED_SERIES_PER_PROCESS, 19_515);
assert_eq!(MAX_EXEMPLAR_SLOTS_PER_PROCESS, 12_348);
assert!(validate_budget(6_285, 19_515).is_ok());
assert!(validate_budget(6_286, 19_515).is_err());
assert!(validate_exemplar_budget(12_347).is_ok());
assert!(validate_exemplar_budget(12_348).is_ok());
assert!(validate_exemplar_budget(12_349).is_err());
for service in [MetricService::AdminApi, MetricService::McpServer] {
let budget = schema_budget(service).expect("projection budget valid");
assert!(budget.logical_series <= MAX_LOGICAL_SERIES_PER_PROCESS);
assert!(budget.rendered_series <= MAX_RENDERED_SERIES_PER_PROCESS);
validate_exemplar_budget(max_exemplar_slots(service))
.expect("capacity inside the hard cap");
}
}
/// TD-M4 — любая испорченная проекция отвергается валидатором.
#[test]
fn any_invalid_projection_fails_validation() {
let base = *service_projection(MetricService::AdminApi)
.iter()
.find(|definition| definition.name == "crank_http_requests_total")
.expect("http counter present in admin projection");
let wrong_ceiling = MetricDefinition {
max_logical_series: base.max_logical_series + 1,
..base
};
assert_eq!(
validate_schema(&[wrong_ceiling]),
Err(crank_metrics::SchemaError::InvalidCeiling)
);
let wrong_domain = MetricDefinition {
label_domains: Box::leak(
base.label_domains
.iter()
.map(|domain| {
if domain.name == "route" {
crank_metrics::LabelDomain {
values: &["/definitely-not-a-route"],
..*domain
}
} else {
*domain
}
})
.collect::<Vec<_>>()
.into_boxed_slice(),
),
..base
};
assert_eq!(
validate_schema(&[wrong_domain]),
Err(crank_metrics::SchemaError::InvalidCeiling)
);
let mut mutated = service_projection(MetricService::AdminApi).to_vec();
mutated[0].max_rendered_series = 0;
assert!(
validate_schema(&mutated).is_err(),
"проекция с несогласованным ceiling обязана падать"
);
// Каждый invalid case проверяется для **обоих** сервисов: даже если
// запускается другой процесс, отказ обязан быть одинаковым.
for service in [MetricService::AdminApi, MetricService::McpServer] {
validate_schema(service_projection(service)).expect("production projection valid");
}
}
/// TD-M5 — checked-арифметика: реальное превышение per-process бюджета обязано
/// отвергаться типизированным `BudgetExceeded`, насыщенные metadata — типизированным
/// `InvalidCeiling`; ни один счётчик не принимается «почти верным».
#[test]
fn arithmetic_overflow_is_typed_and_not_saturated() {
let saturated = MetricDefinition {
name: "crank_test_total",
kind: MetricKind::Counter,
unit: MetricUnit::Count,
labels: &[],
label_domains: &[],
buckets: &[],
processes: &[MetricProcess::AdminApi],
max_logical_series: usize::MAX,
max_rendered_series: usize::MAX,
description: "saturated counter",
};
assert_eq!(
validate_schema(&[saturated]),
Err(crank_metrics::SchemaError::InvalidCeiling),
"насыщенный ceiling обязан быть отвергнут, а не принят"
);
// Настоящая арифметика: домен ровно на единицу больше frozen per-process
// лимита. Metadata точные (не насыщенные), поэтому отказ обязан быть
// типизированным BudgetExceeded, а не InvalidCeiling/срезом.
let oversize = MAX_LOGICAL_SERIES_PER_PROCESS + 1;
let values: &'static [&'static str] = Box::leak(
(0..oversize)
.map(|index| Box::leak(format!("value_{index}").into_boxed_str()) as &'static str)
.collect::<Vec<&'static str>>()
.into_boxed_slice(),
);
let oversize_domains: &'static [crank_metrics::LabelDomain] = Box::leak(
vec![crank_metrics::LabelDomain {
name: "state",
class: crank_metrics::LabelClass::ProductClosed,
values,
}]
.into_boxed_slice(),
);
let oversize_definition = MetricDefinition {
name: "crank_test_oversize_total",
kind: MetricKind::Counter,
unit: MetricUnit::Count,
labels: &["state"],
label_domains: oversize_domains,
buckets: &[],
processes: &[MetricProcess::AdminApi],
max_logical_series: oversize,
max_rendered_series: oversize,
description: "oversize counter",
};
assert_eq!(
validate_schema(&[oversize_definition]),
Err(crank_metrics::SchemaError::BudgetExceeded),
"точный бюджет больше лимита обязан отвергаться типизированно"
);
assert_eq!(
validate_budget(oversize, oversize),
Err(crank_metrics::SchemaError::BudgetExceeded),
"BudgetExceeded обязан быть типизированным на самой границе"
);
assert!(
validate_budget(
MAX_LOGICAL_SERIES_PER_PROCESS,
MAX_RENDERED_SERIES_PER_PROCESS
)
.is_ok()
);
for service in [MetricService::AdminApi, MetricService::McpServer] {
for definition in service_projection(service) {
assert_ne!(
definition.max_logical_series,
usize::MAX,
"{} не может нести насыщенное значение",
definition.name
);
assert_ne!(definition.max_rendered_series, usize::MAX);
}
}
}
/// TD-M6 — capacity вычисляется по сервису и укладывается в hard cap.
#[test]
fn exemplar_capacity_is_service_computed_and_capped() {
assert_eq!(max_exemplar_slots(MetricService::AdminApi), 12_348);
assert_eq!(max_exemplar_slots(MetricService::McpServer), 2_310);
assert!(max_exemplar_slots(MetricService::AdminApi) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
assert!(max_exemplar_slots(MetricService::McpServer) <= MAX_EXEMPLAR_SLOTS_PER_PROCESS);
assert_ne!(
max_exemplar_slots(MetricService::AdminApi),
14_658,
"derived union capacity не может использоваться как лимит процесса"
);
}
/// TD-M7 — per-service projection cache создаётся один раз.
#[test]
fn service_projection_cache_is_allocated_once() {
for service in [MetricService::AdminApi, MetricService::McpServer] {
let first = service_projection(service);
let second = service_projection(service);
assert!(
std::ptr::eq(first, second),
"проекция обязана быть стабильно закеширована"
);
let again = metric_schema_for_service(service).count();
assert_eq!(again, first.len());
}
assert_eq!(
metric_schema().len(),
23,
"union metadata сохраняет 23 family"
);
}