Files
crank/crates/crank-observability/tests/prometheus_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

274 lines
11 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 · фаза B — реальный Prometheus/OpenMetrics exporter.
//!
//! `TD-E1` exact sample counts реального legacy-scrape против формул проекции.
//! `TD-E3i` OpenMetrics negotiation + `# EOF`.
//! `TD-E4i` реальный listener: cap=2, третий scrape отвергается, permit освобождается.
//!
//! Каждый кейс — fresh child того же тест-бинаря: глобальный recorder/tracing
//! dispatcher и service binding устанавливаются один раз на процесс.
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
use std::process::Command;
use std::sync::{Arc, Barrier};
use std::time::Duration;
use crank_metrics::{ADMIN_HTTP_ROUTE_DOMAIN, HttpMethod, HttpRoute, HttpStatusClass};
use crank_observability::{MetricsConfig, ObservabilityConfig, RedactionLimits, ServiceIdentity};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const ROLE_ENV: &str = "CRANK_OBS_V2_ROLE";
fn route_to_child(role: &str, test: &str) -> bool {
match std::env::var(ROLE_ENV).ok().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
None => {
let output = Command::new(std::env::current_exe().expect("current test binary"))
.args([test, "--exact", "--nocapture"])
.env(ROLE_ENV, role)
.output()
.expect("re-executed exporter 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
}
}
}
async fn spawn_listener(
service: &str,
) -> (
SocketAddr,
tokio::task::JoinHandle<Result<(), crank_observability::MetricsServeError>>,
) {
let identity = ServiceIdentity::try_new(service, "0.3.1", "test").expect("identity");
let lifecycle = crank_observability::init(ObservabilityConfig::new(
identity,
"off",
RedactionLimits::default(),
))
.expect("observability lifecycle");
let config = MetricsConfig::new(
true,
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
None,
)
.expect("loopback metrics config");
let server = lifecycle
.metrics_surface(config)
.bind()
.await
.expect("metrics listener");
let address = server.local_addr().expect("listener address");
let task = tokio::spawn(server.serve());
(address, task)
}
fn record_admin_cartesian() {
for route in ADMIN_HTTP_ROUTE_DOMAIN {
for method in HttpMethod::VALUES {
for status in HttpStatusClass::VALUES {
crank_metrics::record_http_request(
HttpRoute::from_matched_path(route),
HttpMethod::classify(method),
HttpStatusClass::from_status(match *status {
"1xx" => 101,
"2xx" => 200,
"3xx" => 302,
"4xx" => 404,
"5xx" => 500,
_ => 0,
}),
Duration::from_millis(1),
);
}
}
}
}
async fn raw_get(address: SocketAddr, accept: Option<&str>) -> String {
let mut stream = tokio::net::TcpStream::connect(address)
.await
.expect("listener connection");
let accept = accept
.map(|value| format!("Accept: {value}\r\n"))
.unwrap_or_default();
stream
.write_all(
format!(
"GET /metrics HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n{accept}\r\n"
)
.as_bytes(),
)
.await
.expect("metrics request");
let mut response = Vec::new();
stream
.read_to_end(&mut response)
.await
.expect("metrics response");
String::from_utf8(response).expect("utf-8 response")
}
/// TD-E1 — реальный legacy-scrape: фактические sample counts равны формулам проекции.
#[tokio::test(flavor = "multi_thread")]
async fn real_legacy_sample_count_matches_formulas() {
if route_to_child("admin-api", "real_legacy_sample_count_matches_formulas") {
return;
}
let (address, task) = spawn_listener("admin-api").await;
record_admin_cartesian();
let response = raw_get(address, None).await;
task.abort();
let _ = task.await;
assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
assert!(response.contains("content-type: text/plain; version=0.0.4"));
let routes = ADMIN_HTTP_ROUTE_DOMAIN.len();
let counter_series = routes * HttpMethod::VALUES.len() * HttpStatusClass::VALUES.len();
let histogram_series = routes * HttpMethod::VALUES.len();
assert_eq!(
response
.lines()
.filter(|line| line.starts_with("crank_http_requests_total{"))
.count(),
counter_series,
"counter sample count обязан совпасть с проекцией admin"
);
assert_eq!(
response
.lines()
.filter(|line| line.starts_with("crank_http_request_duration_seconds_count{"))
.count(),
histogram_series
);
assert_eq!(
response
.lines()
.filter(|line| line.starts_with("crank_http_request_duration_seconds_sum{"))
.count(),
histogram_series
);
assert!(
response.contains("route=\"/api/admin/workspaces/{workspace_id}/resources\""),
"Resource collection обязан быть точной identity: {}",
&response[..response.len().min(400)]
);
assert!(
!response.contains("res_metrics_"),
"raw идентификаторы не могут стать label'ом"
);
}
/// TD-E3i — negotiation OpenMetrics 1.0 и завершающий `# EOF`.
#[tokio::test(flavor = "multi_thread")]
async fn openmetrics_negotiation_and_eof() {
if route_to_child("mcp-server", "openmetrics_negotiation_and_eof") {
return;
}
let (address, task) = spawn_listener("mcp-server").await;
crank_metrics::record_http_request(
HttpRoute::from_matched_path("/v1/{workspace_slug}/{agent_slug}"),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(2),
);
let response = raw_get(address, Some("application/openmetrics-text; version=1.0.0")).await;
task.abort();
let _ = task.await;
assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
assert!(response.contains("content-type: application/openmetrics-text; version=1.0.0"));
assert!(
response.ends_with("# EOF\n"),
"OpenMetrics обязан завершаться # EOF"
);
assert!(
response.contains("crank_http_requests_total{") && response.contains("le=\"+Inf\""),
"OpenMetrics обязан нести те же series: {}",
&response[..response.len().min(400)]
);
}
/// TD-E4i — реальный listener: одновременные scrape'ы обслуживаются, каждый
/// получает ответ, permit освобождается после завершения burst'а.
///
/// Точный cap-oracle (ровно два допущены, третий отвергнут при двух занятых
/// permit'ах, release) требует детерминированной точки синхронизации у permit
/// seam'а и проверяется в
/// `prometheus::rendering_tests::deterministic_scrape_cap_admits_exactly_two_and_releases`
/// (`crank-observability --lib`, cfg(test)-барьер, реальный listener). Здесь
/// намеренно НЕ утверждается «хотя бы один 503»: при быстром рендере три
/// одновременных запроса могут быть обслужены последовательно (три честных 200),
/// поэтому такой оракул был бы тайминговым и не доказывал бы cap.
#[tokio::test(flavor = "multi_thread")]
async fn concurrent_scrape_cap_two_denies_third() {
if route_to_child("admin-api", "concurrent_scrape_cap_two_denies_third") {
return;
}
let (address, task) = spawn_listener("admin-api").await;
// Тяжёлый, но permitted fixture: рендер занимает миллисекунды, поэтому
// одновременные запросы реально перекрываются по времени.
record_admin_cartesian();
let burst = 3;
for _ in 0..4 {
let barrier = Arc::new(Barrier::new(burst));
let mut handles = Vec::new();
for _ in 0..burst {
let barrier = Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).expect("thread connection");
stream
.set_read_timeout(Some(Duration::from_secs(30)))
.expect("read timeout");
barrier.wait();
use std::io::{Read, Write};
stream
.write_all(
format!(
"GET /metrics HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.expect("thread request");
let mut response = Vec::new();
stream.read_to_end(&mut response).expect("thread response");
String::from_utf8_lossy(&response)
.lines()
.next()
.unwrap_or_default()
.to_owned()
}));
}
let statuses = handles
.into_iter()
.map(|handle| handle.join().expect("scrape thread"))
.collect::<Vec<_>>();
let ok = statuses.iter().filter(|line| line.contains("200")).count();
let denied = statuses.iter().filter(|line| line.contains("503")).count();
assert_eq!(
ok + denied,
burst,
"каждый одновременный scrape обязан получить ответ: {statuses:?}"
);
assert!(ok >= 1, "минимум один scrape обязан пройти: {statuses:?}");
}
// Permit освобождается: последовательный scrape снова отвечает 200.
let after = raw_get(address, None).await;
task.abort();
let _ = task.await;
assert!(
after.starts_with("HTTP/1.1 200 OK"),
"permit обязан освободиться: {}",
&after[..after.len().min(200)]
);
}