CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 12m45s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Community Release / release (push) Successful in 40m35s
Tool Draft фиксирует synchronous/background/adaptive, deadline и fallback; runtime применяет единый снимок политики (concurrency, очередь, approval, deadline) до внешнего действия. Насыщение отклоняется typed overload с retry guidance, mandatory safety store fail closed, background/adaptive используют опубликованный synchronous/unsupported fallback. Refs: #29
875 lines
30 KiB
Rust
875 lines
30 KiB
Rust
//! ATDD Story 4.1 (FR-21/FR-24): the runtime asks one authoritative store for admission.
|
|
//!
|
|
//! Real PostgreSQL state, two independent `RuntimeExecutor` instances (the multi-process shape) and a
|
|
//! counted adapter: one shared global budget, typed overload with retry guidance, typed unsupported
|
|
//! fallback, deadline that includes queue waiting and zero outbound calls on every refusal.
|
|
//!
|
|
//! Lives in the `mcp-server` app crate because the runtime must not depend on the registry crate; this
|
|
//! app already wires both and this is the real deployment shape.
|
|
|
|
use std::{
|
|
collections::BTreeMap,
|
|
sync::{
|
|
Arc, Mutex,
|
|
atomic::{AtomicUsize, Ordering},
|
|
},
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use async_trait::async_trait;
|
|
use crank_core::{
|
|
AdapterResponse, AdmissionMode, AdmissionRequest, AdmissionScope, ApprovalEvidence,
|
|
ConfirmationPolicy, ExecutionAdmission, ExecutionConfig, ExecutionErrorCode, ExecutionMode,
|
|
ExecutionOrigin, ExecutionStage, HttpMethod, InvocationSource, NoTasksFallback, Operation,
|
|
OperationId, OperationSafetyClass, OperationSafetyPolicy, OperationSecurityLevel,
|
|
OperationStatus, OutcomeCertainty, Protocol, ProtocolAdapter, RestTarget,
|
|
RuntimeRequestContext, Target, ToolDescription, ToolExecutionMode, ToolExecutionPolicy,
|
|
WorkspaceId,
|
|
};
|
|
use crank_mapping::MappingSet;
|
|
use crank_registry::{AdmissionLimits, PostgresExecutionAdmission};
|
|
use crank_runtime::{RuntimeExecutor, RuntimeExecutorBuilder, RuntimeLimits};
|
|
use crank_schema::{Schema, SchemaKind};
|
|
use serde_json::json;
|
|
use sqlx::PgPool;
|
|
use time::OffsetDateTime;
|
|
|
|
struct CountingAdapter {
|
|
calls: Arc<AtomicUsize>,
|
|
current: Arc<AtomicUsize>,
|
|
peak: Arc<AtomicUsize>,
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ProtocolAdapter for CountingAdapter {
|
|
fn protocol(&self) -> Protocol {
|
|
Protocol::Rest
|
|
}
|
|
|
|
fn supports_mode(&self, mode: ExecutionMode) -> bool {
|
|
mode == ExecutionMode::Unary
|
|
}
|
|
|
|
async fn invoke_unary(
|
|
&self,
|
|
_target: &Target,
|
|
_prepared: &crank_core::PreparedRequest,
|
|
context: &RuntimeRequestContext,
|
|
) -> Result<AdapterResponse, crank_core::ProtocolAdapterError> {
|
|
context.mark_dispatch_started();
|
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
|
let current = self.current.fetch_add(1, Ordering::SeqCst) + 1;
|
|
self.peak.fetch_max(current, Ordering::SeqCst);
|
|
tokio::time::sleep(Duration::from_millis(150)).await;
|
|
self.current.fetch_sub(1, Ordering::SeqCst);
|
|
Ok(AdapterResponse {
|
|
status_code: 200,
|
|
headers: BTreeMap::new(),
|
|
body: json!({"ok": true}),
|
|
data: json!({"ok": true}),
|
|
})
|
|
}
|
|
}
|
|
|
|
fn schema(kind: SchemaKind) -> Schema {
|
|
Schema {
|
|
kind,
|
|
format: None,
|
|
description: None,
|
|
required: false,
|
|
nullable: false,
|
|
default_value: None,
|
|
fields: BTreeMap::new(),
|
|
items: None,
|
|
enum_values: Vec::new(),
|
|
variants: Vec::new(),
|
|
}
|
|
}
|
|
|
|
fn operation(policy: Option<ToolExecutionPolicy>) -> Operation<Schema, MappingSet> {
|
|
Operation {
|
|
id: OperationId::new("op_admission_budget"),
|
|
name: "admission_budget".to_owned(),
|
|
display_name: "Admission budget".to_owned(),
|
|
category: "general".to_owned(),
|
|
protocol: Protocol::Rest,
|
|
security_level: OperationSecurityLevel::Standard,
|
|
status: OperationStatus::Published,
|
|
version: 7,
|
|
target: Target::Rest(RestTarget {
|
|
base_url: "https://api.example.com".to_owned(),
|
|
method: HttpMethod::Get,
|
|
path_template: "/v1/items".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
}),
|
|
input_schema: schema(SchemaKind::Object),
|
|
output_schema: schema(SchemaKind::Object),
|
|
input_mapping: MappingSet::default(),
|
|
output_mapping: MappingSet::default(),
|
|
execution_config: ExecutionConfig {
|
|
timeout_ms: 5_000,
|
|
execution_policy: policy,
|
|
..ExecutionConfig::default()
|
|
},
|
|
tool_description: ToolDescription {
|
|
title: "Admission".to_owned(),
|
|
description: "Admission budget probe".to_owned(),
|
|
tags: Vec::new(),
|
|
examples: Vec::new(),
|
|
},
|
|
samples: None,
|
|
generated_draft: None,
|
|
config_export: None,
|
|
wizard_state: None,
|
|
created_at: OffsetDateTime::now_utc(),
|
|
updated_at: OffsetDateTime::now_utc(),
|
|
published_at: None,
|
|
}
|
|
}
|
|
|
|
async fn execute(
|
|
executor: &RuntimeExecutor,
|
|
operation: &crank_runtime::RuntimeOperation,
|
|
input: &serde_json::Value,
|
|
) -> Result<serde_json::Value, crank_core::ExecutionFailure> {
|
|
let workspace = WorkspaceId::new("ws_test");
|
|
let context = crank_runtime::RuntimeRequestContext::from_correlation(
|
|
&crank_core::CorrelationContext::generate(),
|
|
)
|
|
.with_metering_context(workspace.clone(), None, InvocationSource::AdminTestRun);
|
|
execute_in(executor, operation, input, &context).await
|
|
}
|
|
|
|
async fn execute_in(
|
|
executor: &RuntimeExecutor,
|
|
operation: &crank_runtime::RuntimeOperation,
|
|
input: &serde_json::Value,
|
|
context: &crank_runtime::RuntimeRequestContext,
|
|
) -> Result<serde_json::Value, crank_core::ExecutionFailure> {
|
|
let workspace = context
|
|
.metering_context()
|
|
.map(|metering| metering.workspace_id.clone())
|
|
.unwrap_or_else(|| WorkspaceId::new("ws_test"));
|
|
let request = crank_runtime::RuntimeExecutionRequest::try_new(
|
|
&workspace,
|
|
ExecutionOrigin::AdminDraft,
|
|
None,
|
|
operation,
|
|
input,
|
|
crank_runtime::ExecutionAuthorization::Authorized,
|
|
None,
|
|
context,
|
|
Instant::now() + Duration::from_secs(30),
|
|
)
|
|
.map_err(|_| {
|
|
crank_core::ExecutionFailure::new(
|
|
ExecutionErrorCode::RuntimeInternal,
|
|
crank_core::CorrelationContext::new(
|
|
context.request_id.clone(),
|
|
context.trace_context.clone(),
|
|
),
|
|
)
|
|
})?;
|
|
executor
|
|
.execute_outcome(request)
|
|
.await
|
|
.map(|success| success.output)
|
|
}
|
|
|
|
async fn schema_pool(schema_url: &str) -> PgPool {
|
|
let pool = PgPool::connect(schema_url)
|
|
.await
|
|
.expect("admission schema pool");
|
|
crank_registry::MigrationAuthority::apply(&pool)
|
|
.await
|
|
.expect("migration authority applies the admission schema");
|
|
pool
|
|
}
|
|
|
|
fn admission_store(pool: PgPool, global: usize, queue: usize) -> Arc<PostgresExecutionAdmission> {
|
|
Arc::new(
|
|
PostgresExecutionAdmission::new(
|
|
pool,
|
|
AdmissionLimits {
|
|
global_limit: global,
|
|
agent_limit: 8,
|
|
tool_limit: 8,
|
|
queue_limit: queue,
|
|
},
|
|
crank_core::AdmissionSchedulerConfig::default(),
|
|
)
|
|
.expect("valid admission limits"),
|
|
)
|
|
}
|
|
|
|
fn executor(
|
|
store: Arc<PostgresExecutionAdmission>,
|
|
calls: Arc<AtomicUsize>,
|
|
current: Arc<AtomicUsize>,
|
|
peak: Arc<AtomicUsize>,
|
|
) -> RuntimeExecutor {
|
|
RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CountingAdapter {
|
|
calls,
|
|
current,
|
|
peak,
|
|
}))
|
|
.with_limits(RuntimeLimits::try_new(8, 2).expect("local limits"))
|
|
.with_admission(store)
|
|
.build()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn two_executors_share_one_global_budget() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_budget").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let store = admission_store(pool.clone(), 2, 8);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let current = Arc::new(AtomicUsize::new(0));
|
|
let peak = Arc::new(AtomicUsize::new(0));
|
|
let first = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
let second = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
|
|
let operation: crank_runtime::RuntimeOperation = operation(None).into();
|
|
let mut tasks = Vec::new();
|
|
for index in 0..4 {
|
|
let executor = if index % 2 == 0 {
|
|
first.clone()
|
|
} else {
|
|
second.clone()
|
|
};
|
|
let operation = operation.clone();
|
|
tasks.push(tokio::spawn(async move {
|
|
execute(&executor, &operation, &json!({})).await
|
|
}));
|
|
}
|
|
let mut completed = 0;
|
|
for task in tasks {
|
|
match task.await.expect("execution task") {
|
|
Ok(_) => completed += 1,
|
|
Err(failure) => panic!("admission must grant every request: {failure:?}"),
|
|
}
|
|
}
|
|
assert_eq!(completed, 4);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 4);
|
|
assert!(
|
|
peak.load(Ordering::SeqCst) <= 2,
|
|
"peak concurrency {} exceeded the shared global limit",
|
|
peak.load(Ordering::SeqCst)
|
|
);
|
|
assert_eq!(store.snapshot().await.unwrap().executing, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn saturation_returns_typed_overload_without_an_outbound_call() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_overload").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let store = admission_store(pool, 1, 1);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let current = Arc::new(AtomicUsize::new(0));
|
|
let peak = Arc::new(AtomicUsize::new(0));
|
|
let runtime = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
|
|
// Another process already holds the only global permit.
|
|
let held = match store
|
|
.admit(AdmissionRequest {
|
|
scope: AdmissionScope {
|
|
workspace_id: "ws_test".to_owned(),
|
|
agent_key: "admin".to_owned(),
|
|
operation_id: "op_admission_budget".to_owned(),
|
|
operation_version: 7,
|
|
},
|
|
mode: AdmissionMode::Synchronous,
|
|
policy_mode: ToolExecutionMode::Synchronous,
|
|
no_tasks_fallback: NoTasksFallback::Synchronous,
|
|
approval: ApprovalEvidence::NotRequired,
|
|
fingerprint: "fp_holder".to_owned(),
|
|
expires_at_unix_ms: crank_core::current_unix_ms() + 10_000,
|
|
})
|
|
.await
|
|
.expect("admission store is reachable")
|
|
{
|
|
crank_core::AdmissionOutcome::Permitted(permit) => permit,
|
|
other => panic!("expected a permit, got {other:?}"),
|
|
};
|
|
|
|
let waiting_operation: crank_runtime::RuntimeOperation = operation(Some(ToolExecutionPolicy {
|
|
mode: ToolExecutionMode::Synchronous,
|
|
deadline_ms: 250,
|
|
no_tasks_fallback: NoTasksFallback::Synchronous,
|
|
}))
|
|
.into();
|
|
let waiting_runtime = runtime.clone();
|
|
let first_waiting_operation = waiting_operation.clone();
|
|
let waiting = tokio::spawn(async move {
|
|
execute(&waiting_runtime, &first_waiting_operation, &json!({})).await
|
|
});
|
|
// Let the first request occupy the bounded queue before the next one arrives.
|
|
while store.snapshot().await.unwrap().waiting == 0 {
|
|
tokio::time::sleep(Duration::from_millis(5)).await;
|
|
}
|
|
let overloaded = execute(&runtime, &waiting_operation, &json!({})).await;
|
|
let failure = overloaded.expect_err("a full queue must refuse the request");
|
|
assert_eq!(
|
|
failure.error_code(),
|
|
ExecutionErrorCode::ExecutionOverloaded
|
|
);
|
|
assert_eq!(failure.stage(), ExecutionStage::Admission);
|
|
assert_eq!(failure.retry_after_ms(), Some(250));
|
|
|
|
// The queued request hits its absolute deadline instead of dispatching. That refusal happened
|
|
// inside admission (nothing was ever dispatched), so the client must see an admission-stage
|
|
// overload with retry guidance — not an `upstream_timeout`.
|
|
let expired = waiting
|
|
.await
|
|
.expect("waiting task")
|
|
.expect_err("deadline must refuse");
|
|
assert_eq!(
|
|
expired.error_code(),
|
|
ExecutionErrorCode::ExecutionOverloaded,
|
|
"queue waiting counts against the published deadline"
|
|
);
|
|
assert_eq!(expired.stage(), ExecutionStage::Admission);
|
|
assert_eq!(expired.retry_after_ms(), Some(250));
|
|
assert_eq!(expired.outcome_certainty(), OutcomeCertainty::Certain);
|
|
assert_eq!(
|
|
calls.load(Ordering::SeqCst),
|
|
0,
|
|
"no outbound call on refusal"
|
|
);
|
|
assert!(store.release(&held).await.unwrap());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn background_policy_without_a_task_transport_is_typed_unsupported() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_unsupported").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let store = admission_store(pool, 2, 4);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let current = Arc::new(AtomicUsize::new(0));
|
|
let peak = Arc::new(AtomicUsize::new(0));
|
|
let runtime = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
|
|
let operation: crank_runtime::RuntimeOperation = operation(Some(ToolExecutionPolicy {
|
|
mode: ToolExecutionMode::Background,
|
|
deadline_ms: 2_000,
|
|
no_tasks_fallback: NoTasksFallback::Unsupported,
|
|
}))
|
|
.into();
|
|
let failure = execute(&runtime, &operation, &json!({}))
|
|
.await
|
|
.expect_err("no Task transport exists in Story 4.1");
|
|
assert_eq!(
|
|
failure.error_code(),
|
|
ExecutionErrorCode::ExecutionModeUnsupported
|
|
);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
let snapshot = store.snapshot().await.unwrap();
|
|
assert_eq!(snapshot.waiting, 0);
|
|
assert_eq!(snapshot.executing, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn background_policy_with_a_synchronous_fallback_keeps_the_sync_response_shape() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_fallback").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let store = admission_store(pool, 2, 4);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let current = Arc::new(AtomicUsize::new(0));
|
|
let peak = Arc::new(AtomicUsize::new(0));
|
|
let runtime = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
|
|
let operation: crank_runtime::RuntimeOperation = operation(Some(ToolExecutionPolicy {
|
|
mode: ToolExecutionMode::Adaptive,
|
|
deadline_ms: 2_000,
|
|
no_tasks_fallback: NoTasksFallback::Synchronous,
|
|
}))
|
|
.into();
|
|
let output = execute(&runtime, &operation, &json!({}))
|
|
.await
|
|
.expect("adaptive resolves through the published synchronous fallback");
|
|
// The response shape is unchanged by admission: an operation without output mapping still
|
|
// returns the same mapped output object it returned before Story 4.1.
|
|
assert_eq!(output, json!({}));
|
|
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
|
assert_eq!(store.snapshot().await.unwrap().executing, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn admission_store_outage_fails_closed_before_dispatch() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_outage").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let store = admission_store(pool.clone(), 2, 4);
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let current = Arc::new(AtomicUsize::new(0));
|
|
let peak = Arc::new(AtomicUsize::new(0));
|
|
let runtime = executor(
|
|
Arc::clone(&store),
|
|
Arc::clone(&calls),
|
|
Arc::clone(¤t),
|
|
Arc::clone(&peak),
|
|
);
|
|
// The mandatory state disappears after the store was built: every execution must fail closed.
|
|
sqlx::query("drop table execution_admission_entries")
|
|
.execute(&pool)
|
|
.await
|
|
.expect("drop the mandatory admission state");
|
|
let operation: crank_runtime::RuntimeOperation = operation(None).into();
|
|
let failure = execute(&runtime, &operation, &json!({}))
|
|
.await
|
|
.expect_err("a missing mandatory store must fail closed");
|
|
assert_eq!(
|
|
failure.error_code(),
|
|
ExecutionErrorCode::SafetyStoreUnavailable
|
|
);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
assert!(store.health().await.is_err());
|
|
}
|
|
|
|
/// Admission store that records the snapshot it was asked to decide on (Story 4.1, AC2/F2).
|
|
struct RecordingAdmission {
|
|
inner: Arc<PostgresExecutionAdmission>,
|
|
requests: Mutex<Vec<AdmissionRequest>>,
|
|
permits: AtomicUsize,
|
|
releases: AtomicUsize,
|
|
}
|
|
|
|
impl RecordingAdmission {
|
|
fn new(inner: Arc<PostgresExecutionAdmission>) -> Self {
|
|
Self {
|
|
inner,
|
|
requests: Mutex::new(Vec::new()),
|
|
permits: AtomicUsize::new(0),
|
|
releases: AtomicUsize::new(0),
|
|
}
|
|
}
|
|
|
|
fn requests(&self) -> Vec<AdmissionRequest> {
|
|
self.requests.lock().expect("admission log").clone()
|
|
}
|
|
|
|
fn permits(&self) -> usize {
|
|
self.permits.load(Ordering::SeqCst)
|
|
}
|
|
|
|
fn releases(&self) -> usize {
|
|
self.releases.load(Ordering::SeqCst)
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ExecutionAdmission for RecordingAdmission {
|
|
async fn health(&self) -> Result<(), crank_core::AdmissionStoreError> {
|
|
self.inner.health().await
|
|
}
|
|
|
|
async fn admit(
|
|
&self,
|
|
request: AdmissionRequest,
|
|
) -> Result<crank_core::AdmissionOutcome, crank_core::AdmissionStoreError> {
|
|
self.requests
|
|
.lock()
|
|
.expect("admission log")
|
|
.push(request.clone());
|
|
let outcome = self.inner.admit(request).await?;
|
|
if matches!(outcome, crank_core::AdmissionOutcome::Permitted(_)) {
|
|
self.permits.fetch_add(1, Ordering::SeqCst);
|
|
}
|
|
Ok(outcome)
|
|
}
|
|
|
|
async fn release(
|
|
&self,
|
|
permit: &crank_core::AdmissionPermit,
|
|
) -> Result<bool, crank_core::AdmissionStoreError> {
|
|
let released = self.inner.release(permit).await?;
|
|
if released {
|
|
self.releases.fetch_add(1, Ordering::SeqCst);
|
|
}
|
|
Ok(released)
|
|
}
|
|
|
|
async fn cancel(
|
|
&self,
|
|
ticket_id: u64,
|
|
owner_token: &str,
|
|
) -> Result<bool, crank_core::AdmissionStoreError> {
|
|
self.inner.cancel(ticket_id, owner_token).await
|
|
}
|
|
|
|
async fn snapshot(
|
|
&self,
|
|
) -> Result<crank_core::AdmissionQueueSnapshot, crank_core::AdmissionStoreError> {
|
|
self.inner.snapshot().await
|
|
}
|
|
}
|
|
|
|
fn confirmation_operation(version: u32) -> crank_runtime::RuntimeOperation {
|
|
let mut source = operation(None);
|
|
source.id = OperationId::new("op_admission_confirmation");
|
|
source.name = "admission_confirmation".to_owned();
|
|
source.version = version;
|
|
let Target::Rest(target) = &mut source.target;
|
|
target.method = HttpMethod::Delete;
|
|
source.execution_config.safety = Some(OperationSafetyPolicy {
|
|
class: OperationSafetyClass::Destructive,
|
|
confirmation: Some(ConfirmationPolicy { ttl_ms: 60_000 }),
|
|
});
|
|
source.into()
|
|
}
|
|
|
|
fn confirmation_runtime(
|
|
admission: Arc<RecordingAdmission>,
|
|
coordination: Option<Arc<dyn crank_core::CoordinationStateStore>>,
|
|
calls: Arc<AtomicUsize>,
|
|
) -> RuntimeExecutor {
|
|
let store: Arc<dyn ExecutionAdmission> = admission;
|
|
let builder = RuntimeExecutorBuilder::new()
|
|
.register_adapter(Arc::new(CountingAdapter {
|
|
calls,
|
|
current: Arc::new(AtomicUsize::new(0)),
|
|
peak: Arc::new(AtomicUsize::new(0)),
|
|
}))
|
|
.with_limits(RuntimeLimits::try_new(8, 2).expect("local limits"))
|
|
.with_admission(store);
|
|
match coordination {
|
|
Some(coordination) => builder.with_coordination_store(coordination).build(),
|
|
None => builder.build(),
|
|
}
|
|
}
|
|
|
|
fn confirmation_context() -> crank_runtime::RuntimeRequestContext {
|
|
crank_runtime::RuntimeRequestContext::from_correlation(
|
|
&crank_core::CorrelationContext::generate(),
|
|
)
|
|
.with_response_cache_scope("ws_test", "agent_a")
|
|
.with_metering_context(
|
|
WorkspaceId::new("ws_test"),
|
|
None,
|
|
InvocationSource::AdminTestRun,
|
|
)
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn confirmation_requiring_call_takes_a_permit_only_with_verified_approval() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_confirmation").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let recording = Arc::new(RecordingAdmission::new(Arc::new(
|
|
PostgresExecutionAdmission::new(
|
|
pool,
|
|
AdmissionLimits {
|
|
global_limit: 4,
|
|
agent_limit: 4,
|
|
tool_limit: 4,
|
|
queue_limit: 8,
|
|
},
|
|
crank_core::AdmissionSchedulerConfig::default(),
|
|
)
|
|
.expect("valid admission limits"),
|
|
)));
|
|
let coordination: Arc<dyn crank_core::CoordinationStateStore> =
|
|
Arc::new(crank_runtime::InMemoryCoordinationStateStore::default());
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let runtime = confirmation_runtime(
|
|
Arc::clone(&recording),
|
|
Some(Arc::clone(&coordination)),
|
|
Arc::clone(&calls),
|
|
);
|
|
let operation = confirmation_operation(3);
|
|
let context = confirmation_context();
|
|
let input = json!({ "reason": "remove the stale item" });
|
|
|
|
// 1. No approval yet: the existing challenge is returned and no execution capacity is taken.
|
|
let challenge = execute_in(&runtime, &operation, &input, &context)
|
|
.await
|
|
.expect_err("an unapproved destructive call must only stage confirmation");
|
|
assert_eq!(
|
|
challenge.error_code(),
|
|
ExecutionErrorCode::ConfirmationRequired
|
|
);
|
|
let token = challenge
|
|
.confirmation()
|
|
.expect("expected the confirmation challenge")
|
|
.token()
|
|
.to_owned();
|
|
assert_eq!(
|
|
recording.permits(),
|
|
0,
|
|
"an unapproved request must not take an execution permit"
|
|
);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
let requests = recording.requests();
|
|
assert_eq!(
|
|
requests.len(),
|
|
1,
|
|
"the one admission snapshot is consulted once"
|
|
);
|
|
assert_eq!(
|
|
requests[0].approval,
|
|
ApprovalEvidence::NotGranted,
|
|
"admission must see the real approval state, not a fixed NotRequired"
|
|
);
|
|
assert_eq!(requests[0].scope.operation_version, 3);
|
|
let snapshot = recording.snapshot().await.expect("admission snapshot");
|
|
assert_eq!((snapshot.executing, snapshot.waiting), (0, 0));
|
|
|
|
// 2. An approval issued for another published version never opens this execution.
|
|
let other_version = confirmation_operation(4);
|
|
let foreign = execute_in(
|
|
&runtime,
|
|
&other_version,
|
|
&input,
|
|
&context.clone().with_confirmation_token(token.clone()),
|
|
)
|
|
.await
|
|
.expect_err("a foreign approval must not authorise this version");
|
|
assert_eq!(
|
|
foreign.error_code(),
|
|
ExecutionErrorCode::ConfirmationInvalid
|
|
);
|
|
assert_eq!(recording.permits(), 0);
|
|
assert_eq!(
|
|
recording.requests().len(),
|
|
1,
|
|
"an unusable approval is refused before any capacity request"
|
|
);
|
|
|
|
// 3. An approval is bound to its exact input as well.
|
|
let mismatched_input = json!({ "reason": "remove another item" });
|
|
let mismatched = execute_in(
|
|
&runtime,
|
|
&operation,
|
|
&mismatched_input,
|
|
&context.clone().with_confirmation_token(token.clone()),
|
|
)
|
|
.await
|
|
.expect_err("a confirmation token must not authorise different input");
|
|
assert_eq!(
|
|
mismatched.error_code(),
|
|
ExecutionErrorCode::ConfirmationInvalid
|
|
);
|
|
assert_eq!(recording.permits(), 0);
|
|
assert_eq!(recording.requests().len(), 1);
|
|
|
|
// 4. The matching approval passes admission with truthful evidence and executes exactly once.
|
|
let executed = execute_in(
|
|
&runtime,
|
|
&operation,
|
|
&input,
|
|
&context.clone().with_confirmation_token(token.clone()),
|
|
)
|
|
.await
|
|
.expect("a verified approval executes");
|
|
assert!(executed.is_object());
|
|
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
|
let requests = recording.requests();
|
|
assert_eq!(requests.len(), 2);
|
|
assert_eq!(requests[1].approval, ApprovalEvidence::Granted);
|
|
assert_eq!(requests[1].scope.operation_version, 3);
|
|
assert_eq!(recording.permits(), 1);
|
|
assert_eq!(
|
|
recording.releases(),
|
|
1,
|
|
"the permit is released after execution"
|
|
);
|
|
assert_eq!(recording.snapshot().await.expect("snapshot").executing, 0);
|
|
|
|
// 5. Replay of the consumed confirmation is refused before capacity and without a side effect.
|
|
let replay = execute_in(
|
|
&runtime,
|
|
&operation,
|
|
&input,
|
|
&context.clone().with_confirmation_token(token),
|
|
)
|
|
.await
|
|
.expect_err("a confirmation token is single-use");
|
|
assert_eq!(replay.error_code(), ExecutionErrorCode::ConfirmationInvalid);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
|
assert_eq!(recording.permits(), 1);
|
|
assert_eq!(
|
|
recording.requests().len(),
|
|
2,
|
|
"a replayed approval never reaches admission"
|
|
);
|
|
|
|
// 6. The trusted approved-recovery path still passes the same gate with real evidence.
|
|
let approved = execute_in(
|
|
&runtime,
|
|
&operation,
|
|
&json!({ "reason": "approved by an operator" }),
|
|
&context.with_approval_granted(),
|
|
)
|
|
.await;
|
|
assert!(approved.is_ok());
|
|
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
|
let requests = recording.requests();
|
|
assert_eq!(requests.len(), 3);
|
|
assert_eq!(requests[2].approval, ApprovalEvidence::Granted);
|
|
assert_eq!(recording.permits(), 2);
|
|
assert_eq!(recording.snapshot().await.expect("snapshot").executing, 0);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn mandatory_safety_store_outage_fails_closed_before_admission() {
|
|
let schema_url = crank_test_support::postgres_schema_url("admission_confirmation_outage").await;
|
|
let pool = schema_pool(&schema_url).await;
|
|
let recording = Arc::new(RecordingAdmission::new(Arc::new(
|
|
PostgresExecutionAdmission::new(
|
|
pool,
|
|
AdmissionLimits {
|
|
global_limit: 4,
|
|
agent_limit: 4,
|
|
tool_limit: 4,
|
|
queue_limit: 8,
|
|
},
|
|
crank_core::AdmissionSchedulerConfig::default(),
|
|
)
|
|
.expect("valid admission limits"),
|
|
)));
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
// Confirmation is mandatory for this Tool, but no safety store is wired: the request must fail
|
|
// closed instead of reserving capacity and hoping for an in-memory fallback.
|
|
let runtime = confirmation_runtime(Arc::clone(&recording), None, Arc::clone(&calls));
|
|
let operation = confirmation_operation(3);
|
|
|
|
let failure = execute_in(
|
|
&runtime,
|
|
&operation,
|
|
&json!({ "reason": "no store" }),
|
|
&confirmation_context(),
|
|
)
|
|
.await
|
|
.expect_err("a mandatory safety store outage must fail closed");
|
|
assert_eq!(
|
|
failure.error_code(),
|
|
ExecutionErrorCode::SafetyStoreUnavailable
|
|
);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
assert_eq!(recording.permits(), 0);
|
|
let after_missing_store = recording.requests().len();
|
|
|
|
// The same Tool with a claimed approval and a *failing* safety store never reaches the capacity
|
|
// store at all: the approval claim stays unverified, so no permit and no outbound call exist.
|
|
let failing = confirmation_runtime(
|
|
Arc::clone(&recording),
|
|
Some(Arc::new(UnavailableSafetyStore)),
|
|
Arc::clone(&calls),
|
|
);
|
|
let outage = execute_in(
|
|
&failing,
|
|
&operation,
|
|
&json!({ "reason": "failing store" }),
|
|
&confirmation_context().with_confirmation_token("ct_unavailable"),
|
|
)
|
|
.await
|
|
.expect_err("an unreachable safety store must refuse the claimed approval");
|
|
assert_eq!(
|
|
outage.error_code(),
|
|
ExecutionErrorCode::SafetyStoreUnavailable
|
|
);
|
|
assert_eq!(
|
|
recording.requests().len(),
|
|
after_missing_store,
|
|
"an unverified approval never becomes a capacity request"
|
|
);
|
|
assert_eq!(recording.permits(), 0);
|
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
|
}
|
|
|
|
/// Coordination store whose mandatory backend is down: every operation fails closed.
|
|
struct UnavailableSafetyStore;
|
|
|
|
impl UnavailableSafetyStore {
|
|
fn error() -> crank_core::CacheStoreError {
|
|
crank_core::CacheStoreError::Unavailable {
|
|
message: "test backend unavailable".to_owned(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl crank_core::CoordinationStateStore for UnavailableSafetyStore {
|
|
async fn get_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
) -> Result<Option<crank_core::CoordinationStateValue>, crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
|
|
async fn put_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
_value: crank_core::CoordinationStateValue,
|
|
_ttl: Duration,
|
|
) -> Result<(), crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
|
|
async fn delete_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
) -> Result<(), crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
|
|
async fn take_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
) -> Result<Option<crank_core::CoordinationStateValue>, crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
|
|
async fn reserve_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
_value: crank_core::CoordinationStateValue,
|
|
_ttl: Duration,
|
|
) -> Result<crank_core::CoordinationStateReservation, crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
|
|
async fn compare_and_set_value(
|
|
&self,
|
|
_scope: crank_core::CacheScope,
|
|
_key: &str,
|
|
_expected: &crank_core::CoordinationStateValue,
|
|
_value: crank_core::CoordinationStateValue,
|
|
_ttl: Duration,
|
|
) -> Result<bool, crank_core::CacheStoreError> {
|
|
Err(Self::error())
|
|
}
|
|
}
|