feat(epic4): публиковать execution mode и применять общий admission (Story 4.1, FR-21, FR-24)
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
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
This commit is contained in:
1 parent
44774883a0
commit
e80d30ddb0
72 files changed
+4157
-121
No files matched your search
@@ -0,0 +1,255 @@
|
||||
//! Common execution admission seam of the runtime (Story 4.1, FR-21/FR-24).
|
||||
//!
|
||||
//! Every real execution — synchronous, or a published `background`/`adaptive` policy that falls back
|
||||
//! to synchronous because no durable Task transport exists yet — passes this one gate before any
|
||||
//! adapter work. The gate asks the authoritative store for a scoped permit bounded by the published
|
||||
//! Tool policy, the verified approval state of the exact Published Version/scope/input and the caller
|
||||
//! deadline, and it releases the permit explicitly when the local execution future ends.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crank_core::{
|
||||
ADMIN_ORIGIN_KEY, AdmissionMode, AdmissionOutcome, AdmissionPermit, AdmissionRequest,
|
||||
AdmissionScope, CoordinationStateStore, ExecutionAdmission, NoTasksFallback, ToolExecutionMode,
|
||||
current_unix_ms,
|
||||
};
|
||||
use crank_metrics::{
|
||||
AdmissionModeLabel, RejectionReason, ScopeKind, record_admission_queue_wait,
|
||||
record_admission_rejection,
|
||||
};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{RuntimeError, RuntimeOperation, RuntimeRequestContext};
|
||||
|
||||
/// Effective absolute deadline of one execution: the published policy deadline never extends the
|
||||
/// caller deadline and always includes queue waiting time.
|
||||
pub(crate) fn effective_deadline(
|
||||
operation: &RuntimeOperation,
|
||||
caller_deadline: Instant,
|
||||
) -> Instant {
|
||||
match operation.execution_config.execution_policy {
|
||||
Some(policy) => {
|
||||
caller_deadline.min(Instant::now() + Duration::from_millis(policy.deadline_ms))
|
||||
}
|
||||
None => caller_deadline,
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective execution path for this deployment.
|
||||
///
|
||||
/// Story 4.1 has no Task transport, so a `background` or `adaptive` policy resolves through its
|
||||
/// published `no_tasks_fallback`: either the same synchronous admission path, or a typed
|
||||
/// unsupported refusal with no admission entry, no Task id and no outbound call.
|
||||
pub(crate) fn effective_mode(
|
||||
operation: &RuntimeOperation,
|
||||
) -> Result<ToolExecutionMode, RuntimeError> {
|
||||
let Some(policy) = operation.execution_config.execution_policy else {
|
||||
return Ok(ToolExecutionMode::Synchronous);
|
||||
};
|
||||
match policy.mode {
|
||||
ToolExecutionMode::Synchronous => Ok(ToolExecutionMode::Synchronous),
|
||||
mode => match policy.no_tasks_fallback {
|
||||
NoTasksFallback::Synchronous => Ok(ToolExecutionMode::Synchronous),
|
||||
NoTasksFallback::Unsupported => Err(RuntimeError::ExecutionPolicyUnsupported {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
mode,
|
||||
}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AdmissionLease {
|
||||
store: Arc<dyn ExecutionAdmission>,
|
||||
permit: Option<AdmissionPermit>,
|
||||
runtime: tokio::runtime::Handle,
|
||||
}
|
||||
|
||||
impl AdmissionLease {
|
||||
fn new(store: Arc<dyn ExecutionAdmission>, permit: AdmissionPermit) -> Self {
|
||||
Self {
|
||||
store,
|
||||
permit: Some(permit),
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit release on the normal/error path of the local execution. The `Drop` cleanup stays as
|
||||
/// the cancellation path; both CAS on the same owner token, so only one of them can free it.
|
||||
pub(crate) async fn release(&mut self) {
|
||||
let Some(permit) = self.permit.take() else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = self.store.release(&permit).await {
|
||||
warn!(
|
||||
name: "runtime.admission.release_failed",
|
||||
error = %error,
|
||||
"failed to release an admission permit; the reservation stays fail-closed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AdmissionLease {
|
||||
fn drop(&mut self) {
|
||||
let Some(permit) = self.permit.take() else {
|
||||
return;
|
||||
};
|
||||
let store = Arc::clone(&self.store);
|
||||
// Bounded cleanup: the explicit release path already ran on success/error; cancellation
|
||||
// reaches here and releases by owner token without ever freeing a foreign permit. A failed
|
||||
// release keeps the reservation fail-closed (no TTL reuse of an active permit).
|
||||
self.runtime.spawn(async move {
|
||||
match store.release(&permit).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => warn!(
|
||||
name: "runtime.admission.release_skipped",
|
||||
"admission permit was already released"
|
||||
),
|
||||
Err(error) => warn!(
|
||||
name: "runtime.admission.release_failed",
|
||||
error = %error,
|
||||
"failed to release an admission permit; the reservation stays fail-closed"
|
||||
),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquires a scoped permit from the authoritative store. Returns `None` when this deployment has no
|
||||
/// admission store wired (embedded/unit-test executors keep the pre-4.1 local limiter).
|
||||
pub(crate) async fn acquire(
|
||||
store: Option<&Arc<dyn ExecutionAdmission>>,
|
||||
coordination_store: Option<&dyn CoordinationStateStore>,
|
||||
request: &crate::RuntimeExecutionRequest<'_>,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<AdmissionLease>, RuntimeError> {
|
||||
let Some(store) = store else {
|
||||
return Ok(None);
|
||||
};
|
||||
let operation = request.operation();
|
||||
let input = request.input();
|
||||
let request_context = request.request_context();
|
||||
let operation_id = operation.operation_id.as_str().to_owned();
|
||||
let policy_mode = effective_mode(operation)?;
|
||||
// The one admission snapshot carries the authoritative approval state of this exact Published
|
||||
// Version, scope, input and deadline. A confirmation-requiring request without a verified
|
||||
// approval never takes capacity and never dispatches: the pending human decision is answered
|
||||
// here with the existing challenge, and the single-use token is consumed only at dispatch.
|
||||
let approval = crate::confirmation::approval_evidence(
|
||||
coordination_store,
|
||||
operation,
|
||||
input,
|
||||
Some(request_context),
|
||||
)
|
||||
.await?;
|
||||
let agent_key = request.agent_id().map(|agent| agent.as_str());
|
||||
let workspace_id = request.workspace_id().as_str().to_owned();
|
||||
let request = AdmissionRequest {
|
||||
scope: AdmissionScope {
|
||||
workspace_id,
|
||||
agent_key: agent_key.unwrap_or(ADMIN_ORIGIN_KEY).to_owned(),
|
||||
operation_id: operation_id.clone(),
|
||||
operation_version: operation.operation_version,
|
||||
},
|
||||
mode: AdmissionMode::Synchronous,
|
||||
policy_mode,
|
||||
no_tasks_fallback: operation
|
||||
.execution_config
|
||||
.execution_policy
|
||||
.map(|policy| policy.no_tasks_fallback)
|
||||
.unwrap_or(NoTasksFallback::Synchronous),
|
||||
approval,
|
||||
fingerprint: admission_fingerprint(request_context, operation),
|
||||
expires_at_unix_ms: current_unix_ms().saturating_add(
|
||||
deadline_remaining_ms(deadline)
|
||||
.try_into()
|
||||
.unwrap_or(i64::MAX),
|
||||
),
|
||||
};
|
||||
let started = Instant::now();
|
||||
let outcome = store.admit(request).await.map_err(|error| {
|
||||
record_admission_rejection(RejectionReason::DependencyUnavailable, ScopeKind::Global);
|
||||
RuntimeError::AdmissionStoreUnavailable {
|
||||
operation_id: operation_id.clone(),
|
||||
details: error.to_string(),
|
||||
}
|
||||
})?;
|
||||
let waited_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or_default();
|
||||
match outcome {
|
||||
AdmissionOutcome::Permitted(permit) => {
|
||||
record_admission_queue_wait(AdmissionModeLabel::Synchronous, waited_ms);
|
||||
Ok(Some(AdmissionLease::new(Arc::clone(store), permit)))
|
||||
}
|
||||
AdmissionOutcome::Overloaded { retry_after_ms } => {
|
||||
record_admission_rejection(RejectionReason::Capacity, ScopeKind::Global);
|
||||
Err(RuntimeError::AdmissionOverloaded {
|
||||
operation_id,
|
||||
retry_after_ms,
|
||||
})
|
||||
}
|
||||
AdmissionOutcome::DeadlineElapsed => {
|
||||
// Queue wait exhausted the absolute deadline before a permit was granted: nothing was
|
||||
// dispatched, so this is an admission refusal, not an upstream timeout.
|
||||
Err(deadline_refusal(operation))
|
||||
}
|
||||
AdmissionOutcome::ApprovalRequired => {
|
||||
// The store refused before reserving any capacity or queue entry. Answer with the
|
||||
// existing single-use challenge so the caller can confirm out of band.
|
||||
record_admission_rejection(RejectionReason::Unsupported, ScopeKind::Global);
|
||||
Err(crate::confirmation::challenge(
|
||||
coordination_store,
|
||||
operation,
|
||||
input,
|
||||
Some(request_context),
|
||||
)
|
||||
.await)
|
||||
}
|
||||
AdmissionOutcome::Unsupported | AdmissionOutcome::Enqueued(_) => {
|
||||
// No Task transport exists in this deployment: an enqueue decision can never become a
|
||||
// runnable execution here, so it must not be reported as accepted work.
|
||||
record_admission_rejection(RejectionReason::Unsupported, ScopeKind::Global);
|
||||
Err(RuntimeError::ExecutionPolicyUnsupported {
|
||||
operation_id,
|
||||
mode: policy_mode,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed refusal for an admission that never granted a permit within the absolute deadline. Reuses the
|
||||
/// existing `execution_overloaded` vocabulary (stage `admission`, retry guidance, certain outcome) so
|
||||
/// no new client error code or API shape appears, while reporting zero dispatch truthfully.
|
||||
pub(crate) fn deadline_refusal(operation: &RuntimeOperation) -> RuntimeError {
|
||||
record_admission_rejection(RejectionReason::Deadline, ScopeKind::Global);
|
||||
RuntimeError::AdmissionOverloaded {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
retry_after_ms: crank_core::ADMISSION_OVERLOAD_RETRY_AFTER_MS,
|
||||
}
|
||||
}
|
||||
|
||||
fn deadline_remaining_ms(deadline: Instant) -> u64 {
|
||||
u64::try_from(
|
||||
deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_millis(),
|
||||
)
|
||||
.unwrap_or_default()
|
||||
.max(1)
|
||||
}
|
||||
|
||||
/// Bounded request identity for correlating one admission entry. Never contains payload, headers or
|
||||
/// credentials.
|
||||
fn admission_fingerprint(
|
||||
request_context: &RuntimeRequestContext,
|
||||
operation: &RuntimeOperation,
|
||||
) -> String {
|
||||
let mut fingerprint = format!(
|
||||
"{}:{}:{}",
|
||||
operation.operation_id.as_str(),
|
||||
operation.operation_version,
|
||||
request_context.request_id
|
||||
);
|
||||
fingerprint.truncate(crank_core::ADMISSION_FINGERPRINT_MAX_BYTES);
|
||||
fingerprint
|
||||
}
|
||||
@@ -2,8 +2,8 @@ use std::time::Duration;
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use crank_core::{
|
||||
CacheScope, CoordinationStateStore, CoordinationStateValue, HttpMethod, OperationSafetyClass,
|
||||
OperationSafetyPolicy, Target,
|
||||
ApprovalEvidence, CacheScope, CoordinationStateStore, CoordinationStateValue, HttpMethod,
|
||||
OperationSafetyClass, OperationSafetyPolicy, Target,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -26,32 +26,14 @@ pub async fn confirm_operation(
|
||||
}
|
||||
|
||||
let Some(store) = store else {
|
||||
return Err(RuntimeError::ConfirmationStoreUnavailable {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
});
|
||||
return Err(confirmation_store_unavailable(operation));
|
||||
};
|
||||
|
||||
let scope = confirmation_scope(operation, request_context)?;
|
||||
let input_hash = hash_json(input)?;
|
||||
let provided_token = request_context
|
||||
.and_then(RuntimeRequestContext::confirmation_token)
|
||||
.or_else(|| confirmation_token_from_input(input));
|
||||
|
||||
let Some(provided_token) = provided_token else {
|
||||
let token = issue_confirmation_token(
|
||||
store,
|
||||
operation.operation_id.as_str(),
|
||||
&scope,
|
||||
&input_hash,
|
||||
&safety,
|
||||
)
|
||||
.await?;
|
||||
return Err(RuntimeError::ConfirmationRequired {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
safety_class: safety.class,
|
||||
confirmation_token: token,
|
||||
expires_in_ms: confirmation_ttl_ms(&safety),
|
||||
});
|
||||
let Some(provided_token) = provided_confirmation_token(request_context, input) else {
|
||||
return Err(confirmation_required(store, operation, &scope, &input_hash, &safety).await);
|
||||
};
|
||||
|
||||
consume_confirmation_token(
|
||||
@@ -64,6 +46,121 @@ pub async fn confirm_operation(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Read-only approval proof for the shared admission gate (Story 4.1, AC2).
|
||||
///
|
||||
/// It reports the authoritative approval state of this exact Published Version, scope and input and
|
||||
/// never consumes the single-use confirmation token: the authoritative consumption stays in
|
||||
/// [`confirm_operation`] immediately before the adapter call. A missing approval is `NotGranted`, so
|
||||
/// admission refuses the request before taking execution capacity while the human decision is
|
||||
/// pending; an unusable token or an unreachable safety store is a typed refusal too, never a permit.
|
||||
pub(crate) async fn approval_evidence(
|
||||
store: Option<&dyn CoordinationStateStore>,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
) -> Result<ApprovalEvidence, RuntimeError> {
|
||||
let safety = effective_safety_policy(operation);
|
||||
if !safety.class.requires_confirmation() {
|
||||
return Ok(ApprovalEvidence::NotRequired);
|
||||
}
|
||||
if request_context.is_some_and(RuntimeRequestContext::approval_granted) {
|
||||
return Ok(ApprovalEvidence::Granted);
|
||||
}
|
||||
let Some(store) = store else {
|
||||
return Err(confirmation_store_unavailable(operation));
|
||||
};
|
||||
let scope = confirmation_scope(operation, request_context)?;
|
||||
let input_hash = hash_json(input)?;
|
||||
|
||||
let Some(token) = provided_confirmation_token(request_context, input) else {
|
||||
return Ok(ApprovalEvidence::NotGranted);
|
||||
};
|
||||
|
||||
let stored = store
|
||||
.get_value(
|
||||
CacheScope::Coordination,
|
||||
&confirmation_cache_key(&scope, token),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| confirmation_store_unavailable(operation))?;
|
||||
let verified = stored.is_some_and(|value| {
|
||||
value.payload.get("scope").and_then(Value::as_str) == Some(scope.as_str())
|
||||
&& value.payload.get("input_hash").and_then(Value::as_str) == Some(input_hash.as_str())
|
||||
});
|
||||
if verified {
|
||||
Ok(ApprovalEvidence::Granted)
|
||||
} else {
|
||||
Err(RuntimeError::InvalidConfirmationToken {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Issues the existing single-use confirmation challenge and returns the typed refusal that carries
|
||||
/// it. Admission calls this when no verified approval exists yet, so waiting for the human decision
|
||||
/// never holds execution capacity.
|
||||
pub(crate) async fn challenge(
|
||||
store: Option<&dyn CoordinationStateStore>,
|
||||
operation: &RuntimeOperation,
|
||||
input: &Value,
|
||||
request_context: Option<&RuntimeRequestContext>,
|
||||
) -> RuntimeError {
|
||||
let safety = effective_safety_policy(operation);
|
||||
let Some(store) = store else {
|
||||
return confirmation_store_unavailable(operation);
|
||||
};
|
||||
let scope = match confirmation_scope(operation, request_context) {
|
||||
Ok(scope) => scope,
|
||||
Err(error) => return error,
|
||||
};
|
||||
let input_hash = match hash_json(input) {
|
||||
Ok(input_hash) => input_hash,
|
||||
Err(error) => return error,
|
||||
};
|
||||
confirmation_required(store, operation, &scope, &input_hash, &safety).await
|
||||
}
|
||||
|
||||
fn provided_confirmation_token<'a>(
|
||||
request_context: Option<&'a RuntimeRequestContext>,
|
||||
input: &'a Value,
|
||||
) -> Option<&'a str> {
|
||||
request_context
|
||||
.and_then(RuntimeRequestContext::confirmation_token)
|
||||
.or_else(|| confirmation_token_from_input(input))
|
||||
}
|
||||
|
||||
fn confirmation_store_unavailable(operation: &RuntimeOperation) -> RuntimeError {
|
||||
RuntimeError::ConfirmationStoreUnavailable {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn confirmation_required(
|
||||
store: &dyn CoordinationStateStore,
|
||||
operation: &RuntimeOperation,
|
||||
scope: &str,
|
||||
input_hash: &str,
|
||||
safety: &OperationSafetyPolicy,
|
||||
) -> RuntimeError {
|
||||
match issue_confirmation_token(
|
||||
store,
|
||||
operation.operation_id.as_str(),
|
||||
scope,
|
||||
input_hash,
|
||||
safety,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(token) => RuntimeError::ConfirmationRequired {
|
||||
operation_id: operation.operation_id.as_str().to_owned(),
|
||||
safety_class: safety.class,
|
||||
confirmation_token: token,
|
||||
expires_in_ms: confirmation_ttl_ms(safety),
|
||||
},
|
||||
Err(error) => error,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_applicable(operation: &RuntimeOperation) -> bool {
|
||||
effective_safety_policy(operation)
|
||||
.class
|
||||
|
||||
@@ -43,6 +43,27 @@ pub enum RuntimeError {
|
||||
confirmation_token: String,
|
||||
expires_in_ms: u64,
|
||||
},
|
||||
#[error(
|
||||
"execution mode {mode:?} of operation {operation_id} is unavailable without a durable Task transport"
|
||||
)]
|
||||
ExecutionPolicyUnsupported {
|
||||
operation_id: String,
|
||||
mode: crank_core::ToolExecutionMode,
|
||||
},
|
||||
#[error(
|
||||
"execution admission is overloaded for operation {operation_id}; retry after {retry_after_ms} ms"
|
||||
)]
|
||||
AdmissionOverloaded {
|
||||
operation_id: String,
|
||||
retry_after_ms: u64,
|
||||
},
|
||||
#[error("execution admission requires a verified approval for operation {operation_id}")]
|
||||
AdmissionApprovalRequired { operation_id: String },
|
||||
#[error("execution admission store is unavailable for operation {operation_id}: {details}")]
|
||||
AdmissionStoreUnavailable {
|
||||
operation_id: String,
|
||||
details: String,
|
||||
},
|
||||
#[error("confirmation token for operation {operation_id} is invalid, expired, or already used")]
|
||||
InvalidConfirmationToken { operation_id: String },
|
||||
#[error("confirmation store is unavailable for operation {operation_id}")]
|
||||
|
||||
@@ -57,6 +57,11 @@ fn normalize_runtime_error_with_effect(
|
||||
| RuntimeError::IdempotencyCompletionUnknown { .. } => {
|
||||
failure = failure.with_dispatch_uncertainty();
|
||||
}
|
||||
RuntimeError::AdmissionOverloaded { retry_after_ms, .. } => {
|
||||
if let Ok(with_retry) = failure.clone().try_with_retry_after_ms(*retry_after_ms) {
|
||||
failure = with_retry;
|
||||
}
|
||||
}
|
||||
RuntimeError::ConfirmationRequired {
|
||||
confirmation_token,
|
||||
expires_in_ms,
|
||||
@@ -113,6 +118,14 @@ fn error_code(error: &RuntimeError) -> ExecutionErrorCode {
|
||||
RuntimeError::UnsupportedExecutionMode { .. } => {
|
||||
ExecutionErrorCode::ExecutionModeUnsupported
|
||||
}
|
||||
RuntimeError::ExecutionPolicyUnsupported { .. } => {
|
||||
ExecutionErrorCode::ExecutionModeUnsupported
|
||||
}
|
||||
RuntimeError::AdmissionOverloaded { .. } => ExecutionErrorCode::ExecutionOverloaded,
|
||||
RuntimeError::AdmissionApprovalRequired { .. } => ExecutionErrorCode::ConfirmationRequired,
|
||||
RuntimeError::AdmissionStoreUnavailable { .. } => {
|
||||
ExecutionErrorCode::SafetyStoreUnavailable
|
||||
}
|
||||
RuntimeError::ConcurrencyLimitExceeded { .. } => ExecutionErrorCode::ExecutionOverloaded,
|
||||
RuntimeError::InvalidPreparedRequest { .. } => ExecutionErrorCode::PreparedRequestInvalid,
|
||||
RuntimeError::ConfirmationRequired { .. } => ExecutionErrorCode::ConfirmationRequired,
|
||||
|
||||
@@ -220,6 +220,7 @@ mod tests {
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
execution_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
|
||||
@@ -7,9 +7,9 @@ use std::time::{Duration, Instant};
|
||||
const RESPONSE_CACHE_IO_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
|
||||
use crank_core::{
|
||||
AdapterRegistry, CoordinationStateStore, ExecutionMode, HttpMethod, InvocationSource,
|
||||
InvocationStatus, MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter,
|
||||
Target,
|
||||
AdapterRegistry, CoordinationStateStore, ExecutionAdmission, ExecutionMode, HttpMethod,
|
||||
InvocationSource, InvocationStatus, MeteringEvent, ResponseCacheStore, SharedMeteringSink,
|
||||
SharedProtocolAdapter, Target,
|
||||
};
|
||||
use crank_metrics::{
|
||||
CacheOutcome, ConfirmationOutcome, IdempotencyOutcome, InFlightGuard,
|
||||
@@ -41,6 +41,7 @@ pub struct RuntimeExecutor {
|
||||
unary_limiter: Arc<Semaphore>,
|
||||
response_cache: Option<Arc<dyn ResponseCacheStore>>,
|
||||
coordination_store: Option<Arc<dyn CoordinationStateStore>>,
|
||||
admission: Option<Arc<dyn ExecutionAdmission>>,
|
||||
metering_sink: SharedMeteringSink,
|
||||
}
|
||||
|
||||
@@ -139,6 +140,7 @@ impl RuntimeExecutor {
|
||||
adapters: AdapterRegistry,
|
||||
response_cache: Option<Arc<dyn ResponseCacheStore>>,
|
||||
coordination_store: Option<Arc<dyn CoordinationStateStore>>,
|
||||
admission: Option<Arc<dyn ExecutionAdmission>>,
|
||||
metering_sink: SharedMeteringSink,
|
||||
) -> Self {
|
||||
Self {
|
||||
@@ -147,6 +149,7 @@ impl RuntimeExecutor {
|
||||
limits,
|
||||
response_cache,
|
||||
coordination_store,
|
||||
admission,
|
||||
metering_sink,
|
||||
}
|
||||
}
|
||||
@@ -167,6 +170,11 @@ impl RuntimeExecutor {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_admission(mut self, admission: Arc<dyn ExecutionAdmission>) -> Self {
|
||||
self.admission = Some(admission);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_request(
|
||||
&self,
|
||||
request: RuntimeExecutionRequest<'_>,
|
||||
@@ -188,11 +196,16 @@ impl RuntimeExecutor {
|
||||
request.agent_id()
|
||||
);
|
||||
let operation_may_mutate = operation_may_mutate(operation);
|
||||
let execution_deadline =
|
||||
crate::admission::effective_deadline(operation, request.deadline());
|
||||
let runtime_span = Stage::RuntimeExecute.span();
|
||||
set_parent_from_trace_context(&runtime_span, &request_context.trace_context);
|
||||
log_runtime_event("unary.execute", operation, Some(request_context));
|
||||
let started_at = Instant::now();
|
||||
let dispatch_started = Arc::new(AtomicBool::new(false));
|
||||
// True until the admission gate answered. A deadline that fires while the request is still
|
||||
// waiting for a permit is an admission refusal with zero dispatch, never an upstream timeout.
|
||||
let admission_pending = Arc::new(AtomicBool::new(self.admission.is_some()));
|
||||
let invocation_metrics = ToolInvocationMetrics::start_with_exemplar(
|
||||
metric_invocation_source(Some(request_context)),
|
||||
request_context
|
||||
@@ -206,6 +219,17 @@ impl RuntimeExecutor {
|
||||
.flatten(),
|
||||
);
|
||||
let execution = async {
|
||||
// One admission gate for every executable path (Story 4.1): the published policy decides
|
||||
// the effective mode, the absolute deadline includes queue waiting and the scoped permit
|
||||
// is held for the whole local execution future, including retries.
|
||||
let mut lease = crate::admission::acquire(
|
||||
self.admission.as_ref(),
|
||||
self.coordination_store.as_deref(),
|
||||
&request,
|
||||
execution_deadline,
|
||||
)
|
||||
.await?;
|
||||
admission_pending.store(false, Ordering::Release);
|
||||
let _permit = self.acquire_unary_permit(operation)?;
|
||||
let _inflight = InFlightGuard::runtime();
|
||||
let mapping_span = Stage::RuntimeArgumentsMap.span();
|
||||
@@ -215,7 +239,7 @@ impl RuntimeExecutor {
|
||||
let prepared_request = prepared_request?;
|
||||
let request_preview = sanitized_request_preview(&prepared_request);
|
||||
let prepared_request = apply_resolved_auth(prepared_request, request.resolved_auth());
|
||||
let output = self
|
||||
let result = self
|
||||
.execute_prepared(
|
||||
operation,
|
||||
input,
|
||||
@@ -223,19 +247,27 @@ impl RuntimeExecutor {
|
||||
Some(request_context),
|
||||
Arc::clone(&dispatch_started),
|
||||
)
|
||||
.await?;
|
||||
.await;
|
||||
if let Some(lease) = lease.as_mut() {
|
||||
lease.release().await;
|
||||
}
|
||||
let output = result?;
|
||||
Ok((output, request_preview))
|
||||
};
|
||||
let result = tokio::time::timeout_at(
|
||||
request.deadline().into(),
|
||||
execution_deadline.into(),
|
||||
execution.instrument(runtime_span.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|_| {
|
||||
Err(RuntimeError::ExecutionDeadlineElapsed {
|
||||
may_have_dispatched: operation_may_mutate
|
||||
&& dispatch_started.load(Ordering::Acquire),
|
||||
})
|
||||
if admission_pending.load(Ordering::Acquire) {
|
||||
Err(crate::admission::deadline_refusal(operation))
|
||||
} else {
|
||||
Err(RuntimeError::ExecutionDeadlineElapsed {
|
||||
may_have_dispatched: operation_may_mutate
|
||||
&& dispatch_started.load(Ordering::Acquire),
|
||||
})
|
||||
}
|
||||
});
|
||||
record_runtime_result(&runtime_span, &result);
|
||||
drop(runtime_span);
|
||||
@@ -952,6 +984,10 @@ fn runtime_error_category(error: &RuntimeError) -> ErrorCategory {
|
||||
| RuntimeError::UnsupportedProtocol { .. }
|
||||
| RuntimeError::UnsupportedExecutionMode { .. } => ErrorCategory::Upstream,
|
||||
RuntimeError::ConcurrencyLimitExceeded { .. } => ErrorCategory::Concurrency,
|
||||
RuntimeError::AdmissionOverloaded { .. }
|
||||
| RuntimeError::AdmissionStoreUnavailable { .. } => ErrorCategory::Concurrency,
|
||||
RuntimeError::ExecutionPolicyUnsupported { .. } => ErrorCategory::Configuration,
|
||||
RuntimeError::AdmissionApprovalRequired { .. } => ErrorCategory::Approval,
|
||||
RuntimeError::ConfirmationRequired { .. }
|
||||
| RuntimeError::InvalidConfirmationToken { .. }
|
||||
| RuntimeError::ConfirmationStoreUnavailable { .. } => ErrorCategory::Approval,
|
||||
@@ -1008,6 +1044,13 @@ fn runtime_error_kind(error: &RuntimeError) -> ToolErrorKind {
|
||||
RuntimeError::UnsupportedProtocol { .. } => ToolErrorKind::UnsupportedProtocol,
|
||||
RuntimeError::UnsupportedExecutionMode { .. } => ToolErrorKind::UnsupportedExecutionMode,
|
||||
RuntimeError::ConcurrencyLimitExceeded { .. } => ToolErrorKind::ConcurrencyLimit,
|
||||
// Story 4.1: admission failures reuse the closed error-kind vocabulary so the tool-invocation
|
||||
// label domain stays fixed; the precise code lives in the execution failure/invocation log
|
||||
// (`ExecutionOverloaded`, `SafetyStoreUnavailable`, `ExecutionModeUnsupported`).
|
||||
RuntimeError::AdmissionOverloaded { .. } => ToolErrorKind::ConcurrencyLimit,
|
||||
RuntimeError::AdmissionStoreUnavailable { .. } => ToolErrorKind::ConfirmationStore,
|
||||
RuntimeError::AdmissionApprovalRequired { .. } => ToolErrorKind::ConfirmationRequired,
|
||||
RuntimeError::ExecutionPolicyUnsupported { .. } => ToolErrorKind::UnsupportedExecutionMode,
|
||||
RuntimeError::InvalidPreparedRequest { .. } => ToolErrorKind::InvalidPreparedRequest,
|
||||
RuntimeError::ConfirmationRequired { .. } => ToolErrorKind::ConfirmationRequired,
|
||||
RuntimeError::InvalidConfirmationToken { .. } => ToolErrorKind::InvalidConfirmationToken,
|
||||
|
||||
@@ -2,8 +2,8 @@ use std::sync::Arc;
|
||||
|
||||
use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter};
|
||||
use crank_core::{
|
||||
AdapterRegistry, CoordinationStateStore, MeteringSink, NoopMeteringSink, ResponseCacheStore,
|
||||
SharedMeteringSink, SharedProtocolAdapter,
|
||||
AdapterRegistry, CoordinationStateStore, ExecutionAdmission, MeteringSink, NoopMeteringSink,
|
||||
ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter,
|
||||
};
|
||||
|
||||
use crate::{RuntimeExecutor, RuntimeLimits};
|
||||
@@ -13,6 +13,7 @@ pub struct RuntimeExecutorBuilder {
|
||||
adapters: AdapterRegistry,
|
||||
response_cache: Option<Arc<dyn ResponseCacheStore>>,
|
||||
coordination_store: Option<Arc<dyn CoordinationStateStore>>,
|
||||
admission: Option<Arc<dyn ExecutionAdmission>>,
|
||||
metering_sink: SharedMeteringSink,
|
||||
}
|
||||
|
||||
@@ -23,6 +24,7 @@ impl RuntimeExecutorBuilder {
|
||||
adapters: AdapterRegistry::empty(),
|
||||
response_cache: None,
|
||||
coordination_store: None,
|
||||
admission: None,
|
||||
metering_sink: Arc::new(NoopMeteringSink) as Arc<dyn MeteringSink>,
|
||||
}
|
||||
}
|
||||
@@ -47,6 +49,13 @@ impl RuntimeExecutorBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Wires the mandatory deployment-wide admission store (Story 4.1). Production processes wire
|
||||
/// the PostgreSQL implementation; an executor without it keeps the pre-4.1 local limit.
|
||||
pub fn with_admission(mut self, admission: Arc<dyn ExecutionAdmission>) -> Self {
|
||||
self.admission = Some(admission);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_metering_sink(mut self, sink: SharedMeteringSink) -> Self {
|
||||
self.metering_sink = sink;
|
||||
self
|
||||
@@ -58,6 +67,7 @@ impl RuntimeExecutorBuilder {
|
||||
self.adapters,
|
||||
self.response_cache,
|
||||
self.coordination_store,
|
||||
self.admission,
|
||||
self.metering_sink,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -446,6 +446,7 @@ mod tests {
|
||||
}),
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
execution_policy: None,
|
||||
auth_profile_ref: None,
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod admission;
|
||||
mod auth;
|
||||
mod cache;
|
||||
mod cache_factory;
|
||||
|
||||
Reference in new issue
Block a user