Files
crank/crates/crank-metrics/tests/binding_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

296 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 — service binding и exact wrong-tuple policy.
//!
//! Binding процесса — это `OnceLock`, а не per-request состояние, поэтому
//! каждый сценарий, требующий другого сервиса (или вообще отсутствия binding),
//! исполняется в **fresh child** того же тест-бинаря: глобальный reset/rebind
//! отсутствует by design (CONTRACT §4/§5, фикстура F2).
//!
//! `TD-B1` unbound facade — безопасный no-op.
//! `TD-B2` повтор того же сервиса идемпотентен.
//! `TD-B3` конфликт разных сервисов: ровно один winner, loser — `ConflictingService`.
//! `TD-B4` known route чужого сервиса пишется как `unmatched` (counter+duration).
//! `TD-B5` прямой exemplar не может создать ключ чужого route.
use std::collections::BTreeSet;
use std::time::Duration;
use crank_metrics::{
ExemplarTraceId, HttpMethod, HttpRoute, HttpStatusClass, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
MetricBindingError, MetricService, bound_metric_service, exemplar_snapshot,
record_cache_outcome, record_http_request, record_http_request_with_exemplar,
record_invocation_history_lost, record_mcp_request, record_tool_invocation,
record_upstream_request, set_catalog, set_db_pool_connections, set_mcp_active_sessions,
};
use metrics_util::debugging::DebuggingRecorder;
const BINDING_ROLE_ENV: &str = "CRANK_METRICS_TEST_BINDING_ROLE";
const MCP_ONLY_ROUTE: &str = "/v1/{workspace_slug}/{agent_slug}";
const ADMIN_ROUTE: &str = "/api/admin/workspaces/{workspace_id}/operations";
fn route_to_child(role: &str, test: &str) -> bool {
match std::env::var(BINDING_ROLE_ENV).ok().as_deref() {
Some(actual) if actual == role => false,
Some(actual) => panic!("child for {test} runs with role {actual}, expected {role}"),
None => {
let output =
std::process::Command::new(std::env::current_exe().expect("current test binary"))
.args([test, "--exact", "--nocapture"])
.env(BINDING_ROLE_ENV, role)
.output()
.expect("re-executed binding child");
assert!(
output.status.success(),
"binding child {role}/{test} failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
true
}
}
}
type Samples = Vec<(
metrics_util::CompositeKey,
Option<metrics::Unit>,
Option<metrics::SharedString>,
metrics_util::debugging::DebugValue,
)>;
fn rendered_keys(samples: &Samples) -> BTreeSet<String> {
samples
.iter()
.map(|(key, _, _, _)| {
let mut labels = key
.key()
.labels()
.map(|label| format!("{}={}", label.key(), label.value()))
.collect::<Vec<_>>();
labels.sort();
format!("{}{{{}}}", key.key().name(), labels.join(","))
})
.collect()
}
fn trace() -> ExemplarTraceId {
ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").expect("valid trace id")
}
/// TD-B1 — до binding все facade-пути (включая guards и exemplar) — безопасный
/// no-op: ни одного handle, ни одной series, ни одного exemplar entry.
#[test]
fn unbound_facade_is_a_no_op() {
if route_to_child("unbound", "unbound_facade_is_a_no_op") {
return;
}
assert_eq!(bound_metric_service(), None);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
record_http_request(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(1),
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(1),
Some(trace()),
);
record_mcp_request(
crank_metrics::McpMethod::ToolsCall,
crank_metrics::McpResponseMode::Json,
crank_metrics::McpOutcome::Success,
Duration::from_millis(1),
);
record_tool_invocation(
crank_metrics::InvocationSource::AgentToolCall,
crank_metrics::ToolOutcome::Success,
crank_metrics::ToolErrorKind::None,
Duration::from_millis(1),
);
record_upstream_request(
crank_metrics::UpstreamOperationKind::Rest,
crank_metrics::UpstreamOutcome::Success,
Duration::from_millis(1),
);
record_cache_outcome(crank_metrics::CacheOutcome::Hit);
record_invocation_history_lost();
set_db_pool_connections(crank_metrics::DbPoolState::Idle, 1);
set_mcp_active_sessions(1);
set_catalog(1, 1, 1);
let _http = crank_metrics::InFlightGuard::http();
let _runtime = crank_metrics::InFlightGuard::runtime();
let _stream = crank_metrics::InFlightGuard::mcp_stream();
let _tool = crank_metrics::ToolInvocationMetrics::start(
crank_metrics::InvocationSource::AgentToolCall,
);
let _upstream = crank_metrics::UpstreamRequestMetrics::start(
crank_metrics::UpstreamOperationKind::Rest,
);
});
let samples = snapshotter.snapshot().into_vec();
assert!(
samples.is_empty(),
"unbound facade не может регистрировать series: {:?}",
rendered_keys(&samples)
);
assert!(
exemplar_snapshot().is_empty(),
"unbound facade не может создавать exemplar entries"
);
}
/// TD-B2 — повтор того же сервиса идемпотентен.
#[test]
fn same_service_bind_is_idempotent() {
if route_to_child("admin_api", "same_service_bind_is_idempotent") {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("first bind");
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("same-service rebind");
assert_eq!(bound_metric_service(), Some(MetricService::AdminApi));
assert_eq!(
crank_metrics::bind_metric_service(MetricService::McpServer),
Err(MetricBindingError::ConflictingService)
);
assert_eq!(
bound_metric_service(),
Some(MetricService::AdminApi),
"конфликт не меняет уже опубликованный сервис"
);
}
/// TD-B3 — concurrent конфликт разных сервисов: ровно один winner.
#[test]
fn conflicting_concurrent_bind_has_one_winner() {
if route_to_child("conflict", "conflicting_concurrent_bind_has_one_winner") {
return;
}
let results = std::thread::scope(|scope| {
let admin = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::AdminApi));
let mcp = scope.spawn(|| crank_metrics::bind_metric_service(MetricService::McpServer));
vec![
("admin_api", admin.join().expect("admin bind thread")),
("mcp_server", mcp.join().expect("mcp bind thread")),
]
});
let winners = results
.iter()
.filter(|(_, result)| result.is_ok())
.collect::<Vec<_>>();
assert_eq!(
winners.len(),
1,
"ровно один сервис может победить: {results:?}"
);
for (role, result) in &results {
if let Err(error) = result {
assert_eq!(
*error,
MetricBindingError::ConflictingService,
"loser {role} обязан получить типизированный конфликт"
);
}
}
let winner = winners[0].0;
let expected = match winner {
"admin_api" => Some(MetricService::AdminApi),
_ => Some(MetricService::McpServer),
};
assert_eq!(bound_metric_service(), expected);
}
/// TD-B4 — known route чужого сервиса degraded в `unmatched`, запрос сохраняется.
#[test]
fn wrong_service_route_records_unmatched() {
if route_to_child("admin_api", "wrong_service_route_records_unmatched") {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
metrics::with_local_recorder(&recorder, || {
record_http_request(
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_secs_f64(0.004),
);
});
let samples = snapshotter.snapshot().into_vec();
let keys = rendered_keys(&samples);
assert!(
keys.contains("crank_http_requests_total{method=GET,route=unmatched,status_class=2xx}"),
"чужой known route обязан стать unmatched с сохранением method/status: {keys:?}"
);
assert!(
keys.contains("crank_http_request_duration_seconds{method=GET,route=unmatched}"),
"duration обязан идти в тот же unmatched series: {keys:?}"
);
assert!(
keys.iter().all(|key| !key.contains("workspace_slug")),
"ни одна series не может нести ключ чужого route: {keys:?}"
);
assert_eq!(
keys.len(),
2,
"wrong tuple не создаёт новых families: {keys:?}"
);
}
/// TD-B5 — прямой exemplar не создаёт ключ чужого route.
#[test]
fn direct_exemplar_cannot_create_foreign_route_key() {
if route_to_child(
"admin_api",
"direct_exemplar_cannot_create_foreign_route_key",
) {
return;
}
crank_metrics::bind_metric_service(MetricService::AdminApi).expect("admin bind");
assert!(
exemplar_snapshot().is_empty(),
"fixture требует чистый exemplar store"
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(MCP_ONLY_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(4),
Some(trace()),
);
record_http_request_with_exemplar(
HttpRoute::from_matched_path(ADMIN_ROUTE),
HttpMethod::Get,
HttpStatusClass::Success,
Duration::from_millis(4),
Some(trace()),
);
let observations = exemplar_snapshot();
assert_eq!(
observations.len(),
2,
"exemplar обязан попасть в unmatched и в собственную admin-серию: {observations:#?}"
);
assert!(
observations.iter().all(
|observation| observation.labels.contains(&("route", "unmatched"))
|| observation.labels.contains(&("route", ADMIN_ROUTE))
),
"ни один exemplar не может нести чужой route: {observations:#?}"
);
assert!(
observations
.iter()
.all(|observation| !observation.labels.contains(&("route", MCP_ONLY_ROUTE))),
"foreign route key не может быть создан"
);
assert!(
MAX_EXEMPLAR_SLOTS_PER_PROCESS
>= crank_metrics::max_exemplar_slots(MetricService::AdminApi)
);
}