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,531 @@
|
||||
//! Typed execution-admission seam (Story 4.1, FR-21/FR-24).
|
||||
//!
|
||||
//! Admission is the single gate in front of every real Tool execution: it decides whether the
|
||||
//! caller receives a scoped permit or a durable enqueue decision, and it owns the deployment-wide
|
||||
//! global/per-Agent/per-Tool capacity and the bounded waiting queue. The authoritative state lives
|
||||
//! in PostgreSQL (`crank-registry`), so several processes share one budget.
|
||||
//!
|
||||
//! Deliberately absent from this contract: credentials, connection or protocol revision (they must
|
||||
//! never widen a quota), request bodies and prepared headers (payload ownership is Story 4.2).
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{NoTasksFallback, ToolExecutionMode};
|
||||
|
||||
pub const ADMISSION_FINGERPRINT_MAX_BYTES: usize = 128;
|
||||
pub const ADMISSION_OWNER_TOKEN_MAX_BYTES: usize = 64;
|
||||
pub const MAX_RETRY_AFTER_MS: u64 = 60_000;
|
||||
/// Bounded retry guidance for an admission refusal (capacity or queue wait exhausted). One value for
|
||||
/// the store and every runtime so the client contract stays stable.
|
||||
pub const ADMISSION_OVERLOAD_RETRY_AFTER_MS: u64 = 250;
|
||||
|
||||
/// Current wall clock in unix milliseconds (absolute deadlines are persisted as unix ms).
|
||||
pub fn current_unix_ms() -> i64 {
|
||||
i64::try_from(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|elapsed| elapsed.as_millis())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
/// Bucket used for an execution that has no Agent (admin draft/test-run): an explicit admin origin
|
||||
/// bucket that is still bounded by the global limit.
|
||||
pub const ADMIN_ORIGIN_KEY: &str = "admin";
|
||||
|
||||
/// Exact execution identity pinned at admission time.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AdmissionScope {
|
||||
pub workspace_id: String,
|
||||
/// Agent id, or [`ADMIN_ORIGIN_KEY`] for an Agent-less administrative execution.
|
||||
pub agent_key: String,
|
||||
pub operation_id: String,
|
||||
/// Quota keys exclude the version; the version is pinned for execution semantics only.
|
||||
pub operation_version: u32,
|
||||
}
|
||||
|
||||
impl AdmissionScope {
|
||||
/// Quota key of the Agent bucket: `(workspace, agent)`.
|
||||
pub fn agent_bucket(&self) -> String {
|
||||
format!("{}:{}", self.workspace_id, self.agent_key)
|
||||
}
|
||||
|
||||
/// Quota key of the Tool bucket: `(workspace, operation)` without version.
|
||||
pub fn tool_bucket(&self) -> String {
|
||||
format!("{}:{}", self.workspace_id, self.operation_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AdmissionMode {
|
||||
/// The caller waits for a scoped permit and dispatches inside it.
|
||||
Synchronous,
|
||||
/// The store commits a durable enqueue decision and reserves queue capacity.
|
||||
Background,
|
||||
}
|
||||
|
||||
impl AdmissionMode {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Synchronous => "synchronous",
|
||||
Self::Background => "background",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-consuming approval evidence gathered by the runtime before admission.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ApprovalEvidence {
|
||||
/// The operation does not require confirmation.
|
||||
NotRequired,
|
||||
/// A verified approval exists for this exact scope and input.
|
||||
Granted,
|
||||
/// Confirmation is required and no verified approval exists yet.
|
||||
NotGranted,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionRequest {
|
||||
pub scope: AdmissionScope,
|
||||
pub mode: AdmissionMode,
|
||||
/// Published policy mode that produced this request.
|
||||
pub policy_mode: ToolExecutionMode,
|
||||
pub no_tasks_fallback: NoTasksFallback,
|
||||
pub approval: ApprovalEvidence,
|
||||
/// Bounded request identity used only to correlate one admission entry.
|
||||
pub fingerprint: String,
|
||||
/// Absolute deadline (unix milliseconds), already including queue waiting time.
|
||||
pub expires_at_unix_ms: i64,
|
||||
}
|
||||
|
||||
impl AdmissionRequest {
|
||||
pub fn validate(&self) -> Result<(), AdmissionStoreError> {
|
||||
if self.fingerprint.is_empty()
|
||||
|| self.fingerprint.len() > ADMISSION_FINGERPRINT_MAX_BYTES
|
||||
|| self
|
||||
.fingerprint
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_control() || byte == b' ')
|
||||
{
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission fingerprint is outside its allowed bounds",
|
||||
));
|
||||
}
|
||||
if self.scope.workspace_id.is_empty() || self.scope.workspace_id.len() > 160 {
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission workspace is invalid",
|
||||
));
|
||||
}
|
||||
if self.scope.agent_key.is_empty() || self.scope.agent_key.len() > 160 {
|
||||
return Err(AdmissionStoreError::invalid("admission agent is invalid"));
|
||||
}
|
||||
if self.scope.operation_id.is_empty() || self.scope.operation_id.len() > 160 {
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission operation is invalid",
|
||||
));
|
||||
}
|
||||
if self.scope.operation_version == 0 {
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission operation version must be positive",
|
||||
));
|
||||
}
|
||||
if self.expires_at_unix_ms <= 0 {
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission deadline is invalid",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Scoped permit. Held for the whole local execution future (including retries) and released
|
||||
/// explicitly; a dropped permit is cleaned up by a bounded owner-token CAS, never reused by TTL.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionPermit {
|
||||
pub ticket_id: u64,
|
||||
pub owner_token: String,
|
||||
pub scope: AdmissionScope,
|
||||
pub mode: AdmissionMode,
|
||||
pub policy_mode: ToolExecutionMode,
|
||||
}
|
||||
|
||||
/// Durable enqueue decision: a reserved queue slot with exact Published Version semantics.
|
||||
/// It is not a public Task id and it never authorises a worker dispatch (Story 4.2).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionDecision {
|
||||
pub ticket_id: u64,
|
||||
pub scope: AdmissionScope,
|
||||
pub expires_at_unix_ms: i64,
|
||||
pub policy_mode: ToolExecutionMode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AdmissionOutcome {
|
||||
Permitted(AdmissionPermit),
|
||||
Enqueued(AdmissionDecision),
|
||||
/// Capacity or queue bounds were exhausted before any unbounded allocation.
|
||||
Overloaded {
|
||||
retry_after_ms: u64,
|
||||
},
|
||||
/// The queue wait reached the absolute deadline; nothing was dispatched.
|
||||
DeadlineElapsed,
|
||||
/// Confirmation is mandatory for this operation and no verified approval exists.
|
||||
ApprovalRequired,
|
||||
/// The published policy does not advertise durable Tasks and refuses the fallback.
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AdmissionQueueSnapshot {
|
||||
pub waiting: u64,
|
||||
pub executing: u64,
|
||||
/// Age of the oldest waiting request in the authoritative queue, in milliseconds.
|
||||
pub oldest_waiting_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum AdmissionStoreError {
|
||||
/// The mandatory safety/capacity store cannot confirm state; every dependent path fails closed.
|
||||
#[error("execution admission store is unavailable: {message}")]
|
||||
Unavailable { message: String },
|
||||
/// The store rejected a malformed admission request.
|
||||
#[error("execution admission request is invalid: {message}")]
|
||||
Invalid { message: String },
|
||||
}
|
||||
|
||||
impl AdmissionStoreError {
|
||||
pub fn unavailable(message: impl Into<String>) -> Self {
|
||||
Self::Unavailable {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn invalid(message: impl Into<String>) -> Self {
|
||||
Self::Invalid {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ExecutionAdmission: Send + Sync {
|
||||
/// Proves the mandatory admission state is usable (schema and operations reachable).
|
||||
async fn health(&self) -> Result<(), AdmissionStoreError>;
|
||||
|
||||
/// Waits (bounded by `expires_at_unix_ms`) for a scoped permit, or commits a durable enqueue
|
||||
/// decision for a background request, or returns a typed refusal.
|
||||
async fn admit(
|
||||
&self,
|
||||
request: AdmissionRequest,
|
||||
) -> Result<AdmissionOutcome, AdmissionStoreError>;
|
||||
|
||||
/// Releases the caller's own permit. Idempotent: a repeated release returns `false`.
|
||||
async fn release(&self, permit: &AdmissionPermit) -> Result<bool, AdmissionStoreError>;
|
||||
|
||||
/// Removes the caller's own waiting ticket. Idempotent and never touches a foreign ticket.
|
||||
async fn cancel(&self, ticket_id: u64, owner_token: &str) -> Result<bool, AdmissionStoreError>;
|
||||
|
||||
/// Bounded authoritative queue readings for low-cardinality metrics.
|
||||
async fn snapshot(&self) -> Result<AdmissionQueueSnapshot, AdmissionStoreError>;
|
||||
}
|
||||
|
||||
/// One waiting entry as seen by the fairness scheduler.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionQueueEntry {
|
||||
pub ticket_id: u64,
|
||||
/// Authoritative insertion order inside `(Agent, Tool)`; never rewritten.
|
||||
pub sequence: u64,
|
||||
pub agent_key: String,
|
||||
pub operation_id: String,
|
||||
}
|
||||
|
||||
/// Weighted round-robin state persisted with the authoritative queue.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct AdmissionCursor {
|
||||
pub agent: Option<String>,
|
||||
pub agent_credit: u32,
|
||||
pub tool: Option<String>,
|
||||
pub tool_credit: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionSchedulerConfig {
|
||||
pub agent_weight: u32,
|
||||
pub tool_weight: u32,
|
||||
}
|
||||
|
||||
impl Default for AdmissionSchedulerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
agent_weight: 1,
|
||||
tool_weight: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AdmissionSchedulerConfig {
|
||||
pub fn validate(&self) -> Result<(), AdmissionStoreError> {
|
||||
if !(1..=64).contains(&self.agent_weight) || !(1..=64).contains(&self.tool_weight) {
|
||||
return Err(AdmissionStoreError::invalid(
|
||||
"admission weights must be between 1 and 64",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of one fair-selection step: the queue index to grant and the cursor to persist when the
|
||||
/// grant actually happens. The cursor is not mutated on a blocked head, so a blocked head keeps its
|
||||
/// turn instead of being skipped by newer arrivals.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AdmissionSelection {
|
||||
pub index: usize,
|
||||
pub cursor: AdmissionCursor,
|
||||
}
|
||||
|
||||
/// Hierarchical weighted round-robin: Agents first, then the Tools of the chosen Agent, FIFO inside
|
||||
/// `(Agent, Tool)`. A new waiter never resets the cursor and never inherits idle credit.
|
||||
pub fn select_next_grant(
|
||||
queue: &[AdmissionQueueEntry],
|
||||
cursor: &AdmissionCursor,
|
||||
config: AdmissionSchedulerConfig,
|
||||
) -> Option<AdmissionSelection> {
|
||||
if queue.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let agent_weight = config.agent_weight.max(1);
|
||||
let tool_weight = config.tool_weight.max(1);
|
||||
let mut agents: Vec<&str> = queue.iter().map(|entry| entry.agent_key.as_str()).collect();
|
||||
agents.sort_unstable();
|
||||
agents.dedup();
|
||||
|
||||
let mut next = cursor.clone();
|
||||
let agent = match cursor.agent.as_deref() {
|
||||
Some(current) if cursor.agent_credit > 0 && agents.contains(¤t) => current.to_owned(),
|
||||
_ => {
|
||||
let chosen = match cursor.agent.as_deref() {
|
||||
None => agents[0].to_owned(),
|
||||
Some(current) => agents
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|candidate| *candidate > current)
|
||||
.unwrap_or(agents[0])
|
||||
.to_owned(),
|
||||
};
|
||||
if cursor.agent.as_deref() != Some(chosen.as_str()) {
|
||||
next.tool = None;
|
||||
next.tool_credit = 0;
|
||||
}
|
||||
next.agent = Some(chosen.clone());
|
||||
next.agent_credit = agent_weight;
|
||||
chosen
|
||||
}
|
||||
};
|
||||
|
||||
let mut tools: Vec<&str> = queue
|
||||
.iter()
|
||||
.filter(|entry| entry.agent_key == agent)
|
||||
.map(|entry| entry.operation_id.as_str())
|
||||
.collect();
|
||||
tools.sort_unstable();
|
||||
tools.dedup();
|
||||
|
||||
let tool = match cursor.tool.as_deref() {
|
||||
Some(current) if cursor.tool_credit > 0 && tools.contains(¤t) => current.to_owned(),
|
||||
_ => {
|
||||
let chosen = match cursor.tool.as_deref() {
|
||||
None => tools[0].to_owned(),
|
||||
Some(current) => tools
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|candidate| *candidate > current)
|
||||
.unwrap_or(tools[0])
|
||||
.to_owned(),
|
||||
};
|
||||
next.tool = Some(chosen.clone());
|
||||
next.tool_credit = tool_weight;
|
||||
chosen
|
||||
}
|
||||
};
|
||||
|
||||
let index = queue
|
||||
.iter()
|
||||
.position(|entry| entry.agent_key == agent && entry.operation_id == tool)?;
|
||||
next.agent_credit = next.agent_credit.saturating_sub(1);
|
||||
next.tool_credit = next.tool_credit.saturating_sub(1);
|
||||
Some(AdmissionSelection {
|
||||
index,
|
||||
cursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
ADMIN_ORIGIN_KEY, AdmissionCursor, AdmissionMode, AdmissionRequest,
|
||||
AdmissionSchedulerConfig, AdmissionScope, AdmissionStoreError, ApprovalEvidence,
|
||||
select_next_grant,
|
||||
};
|
||||
use crate::{NoTasksFallback, ToolExecutionMode};
|
||||
|
||||
fn entry(ticket_id: u64, agent: &str, tool: &str) -> super::AdmissionQueueEntry {
|
||||
super::AdmissionQueueEntry {
|
||||
ticket_id,
|
||||
sequence: ticket_id,
|
||||
agent_key: agent.to_owned(),
|
||||
operation_id: tool.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn request() -> AdmissionRequest {
|
||||
AdmissionRequest {
|
||||
scope: AdmissionScope {
|
||||
workspace_id: "ws_default".to_owned(),
|
||||
agent_key: ADMIN_ORIGIN_KEY.to_owned(),
|
||||
operation_id: "op_leads".to_owned(),
|
||||
operation_version: 3,
|
||||
},
|
||||
mode: AdmissionMode::Synchronous,
|
||||
policy_mode: ToolExecutionMode::Synchronous,
|
||||
no_tasks_fallback: NoTasksFallback::Synchronous,
|
||||
approval: ApprovalEvidence::NotRequired,
|
||||
fingerprint: "fp_0123456789".to_owned(),
|
||||
expires_at_unix_ms: 1_790_000_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_keys_exclude_version_and_keep_agent_bucket() {
|
||||
let scope = request().scope;
|
||||
assert_eq!(scope.agent_bucket(), "ws_default:admin");
|
||||
assert_eq!(scope.tool_bucket(), "ws_default:op_leads");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_validation_rejects_zero_deadline_and_oversized_fingerprint() {
|
||||
let mut invalid = request();
|
||||
invalid.expires_at_unix_ms = 0;
|
||||
assert!(matches!(
|
||||
invalid.validate(),
|
||||
Err(AdmissionStoreError::Invalid { .. })
|
||||
));
|
||||
|
||||
let mut invalid = request();
|
||||
invalid.fingerprint = "x".repeat(super::ADMISSION_FINGERPRINT_MAX_BYTES + 1);
|
||||
assert!(invalid.validate().is_err());
|
||||
|
||||
let mut invalid = request();
|
||||
invalid.scope.operation_version = 0;
|
||||
assert!(invalid.validate().is_err());
|
||||
|
||||
assert!(request().validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_are_bounded_positive_configuration() {
|
||||
assert!(
|
||||
AdmissionSchedulerConfig {
|
||||
agent_weight: 0,
|
||||
tool_weight: 1
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
AdmissionSchedulerConfig {
|
||||
agent_weight: 1,
|
||||
tool_weight: 65
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(AdmissionSchedulerConfig::default().validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weighted_round_robin_serves_each_agent_its_quantum() {
|
||||
let mut queue = vec![
|
||||
entry(1, "agent_a", "op_1"),
|
||||
entry(2, "agent_a", "op_1"),
|
||||
entry(3, "agent_a", "op_1"),
|
||||
entry(4, "agent_b", "op_1"),
|
||||
entry(5, "agent_b", "op_1"),
|
||||
];
|
||||
let config = AdmissionSchedulerConfig {
|
||||
agent_weight: 2,
|
||||
tool_weight: 1,
|
||||
};
|
||||
let mut cursor = AdmissionCursor::default();
|
||||
let mut order = Vec::new();
|
||||
while !queue.is_empty() {
|
||||
let selection = select_next_grant(&queue, &cursor, config).unwrap();
|
||||
order.push(queue.remove(selection.index).agent_key.clone());
|
||||
cursor = selection.cursor;
|
||||
}
|
||||
assert_eq!(
|
||||
order,
|
||||
vec!["agent_a", "agent_a", "agent_b", "agent_b", "agent_a"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fifo_inside_one_tool_and_round_robin_between_tools() {
|
||||
let mut queue = vec![
|
||||
entry(1, "agent_a", "op_1"),
|
||||
entry(2, "agent_a", "op_1"),
|
||||
entry(3, "agent_a", "op_2"),
|
||||
];
|
||||
let config = AdmissionSchedulerConfig::default();
|
||||
let mut cursor = AdmissionCursor::default();
|
||||
let mut order = Vec::new();
|
||||
while !queue.is_empty() {
|
||||
let selection = select_next_grant(&queue, &cursor, config).unwrap();
|
||||
// A granted ticket leaves the waiting queue: granted entries are never re-granted.
|
||||
order.push(queue.remove(selection.index).ticket_id);
|
||||
cursor = selection.cursor;
|
||||
}
|
||||
// One grant per Tool per round; FIFO is preserved inside each `(Agent, Tool)` queue.
|
||||
assert_eq!(order, vec![1, 3, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_arrival_does_not_reset_cursor_or_receive_idle_credit() {
|
||||
let queue = vec![entry(1, "agent_a", "op_1")];
|
||||
let config = AdmissionSchedulerConfig {
|
||||
agent_weight: 2,
|
||||
tool_weight: 1,
|
||||
};
|
||||
let cursor = AdmissionCursor::default();
|
||||
let first = select_next_grant(&queue, &cursor, config).unwrap();
|
||||
assert_eq!(first.cursor.agent.as_deref(), Some("agent_a"));
|
||||
assert_eq!(first.cursor.agent_credit, 1);
|
||||
|
||||
// A later Agent joins; the cursor keeps its remaining quantum for `agent_a`.
|
||||
let queue = vec![entry(1, "agent_a", "op_1"), entry(2, "agent_b", "op_9")];
|
||||
let second = select_next_grant(&queue, &first.cursor, config).unwrap();
|
||||
assert_eq!(queue[second.index].agent_key, "agent_a");
|
||||
assert_eq!(second.cursor.agent_credit, 0);
|
||||
|
||||
let third = select_next_grant(&queue, &second.cursor, config).unwrap();
|
||||
assert_eq!(queue[third.index].agent_key, "agent_b");
|
||||
assert_eq!(third.cursor.agent_credit, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_queue_keeps_cursor_untouched() {
|
||||
let cursor = AdmissionCursor {
|
||||
agent: Some("agent_b".to_owned()),
|
||||
agent_credit: 1,
|
||||
tool: Some("op_1".to_owned()),
|
||||
tool_credit: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
select_next_grant(&[], &cursor, AdmissionSchedulerConfig::default()),
|
||||
None
|
||||
);
|
||||
assert_eq!(cursor.agent.as_deref(), Some("agent_b"));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod access;
|
||||
pub mod admission;
|
||||
pub mod agent;
|
||||
pub mod approval;
|
||||
pub mod auth;
|
||||
@@ -60,10 +61,11 @@ pub mod domain {
|
||||
pub use crate::onboarding::{OnboardingProjection, OnboardingStep, OnboardingStepId};
|
||||
pub use crate::operation::{
|
||||
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
|
||||
IdempotencyMode, IdempotencyPolicy, NoTasksFallback, Operation, OperationApprovalMode,
|
||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, ResponseCachePolicy,
|
||||
RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample, WizardState,
|
||||
RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample, ToolExecutionMode,
|
||||
ToolExecutionPolicy, WizardState,
|
||||
};
|
||||
pub use crate::product_event::{
|
||||
OnboardingMilestone, PRODUCT_EVENT_IDEMPOTENCY_KEY_MAX_BYTES, PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
@@ -114,6 +116,13 @@ pub use access::{
|
||||
InvitationStatus, InvitationToken, Membership, MembershipRole, PlatformApiKey,
|
||||
PlatformApiKeyKind, PlatformApiKeyScope, PlatformApiKeyStatus, User, UserStatus,
|
||||
};
|
||||
pub use admission::{
|
||||
ADMIN_ORIGIN_KEY, ADMISSION_FINGERPRINT_MAX_BYTES, ADMISSION_OVERLOAD_RETRY_AFTER_MS,
|
||||
AdmissionCursor, AdmissionDecision, AdmissionMode, AdmissionOutcome, AdmissionPermit,
|
||||
AdmissionQueueEntry, AdmissionQueueSnapshot, AdmissionRequest, AdmissionSchedulerConfig,
|
||||
AdmissionScope, AdmissionSelection, AdmissionStoreError, ApprovalEvidence, ExecutionAdmission,
|
||||
MAX_RETRY_AFTER_MS, current_unix_ms, select_next_grant,
|
||||
};
|
||||
pub use agent::{
|
||||
Agent, AgentOperationBinding, AgentStatus, AgentVersion, ToolAccessMode, ToolGroup,
|
||||
ToolSearchSettings, ToolSelectionPolicy, ToolSelectionPolicyError,
|
||||
@@ -168,13 +177,14 @@ pub use observability::{
|
||||
pub use onboarding::{OnboardingProjection, OnboardingStep, OnboardingStepId};
|
||||
pub use operation::{
|
||||
ConfigExport, ConfirmationPolicy, ExecutionConfig, GeneratedDraft, GeneratedDraftStatus,
|
||||
IdempotencyMode, IdempotencyPolicy, Operation, OperationApprovalMode,
|
||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||
OperationAvailability, OperationLifecycle, OperationLifecycleAction, OperationLifecycleError,
|
||||
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, OperationVersionState,
|
||||
ResponseCachePolicy, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
|
||||
RestResponseDescriptor, RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample,
|
||||
WizardState,
|
||||
IdempotencyMode, IdempotencyPolicy, MAX_TOOL_DEADLINE_MS, NoTasksFallback, Operation,
|
||||
OperationApprovalMode, OperationApprovalPayloadPreviewMode, OperationApprovalPolicy,
|
||||
OperationApprovalRiskLevel, OperationAvailability, OperationLifecycle,
|
||||
OperationLifecycleAction, OperationLifecycleError, OperationSafetyClass, OperationSafetyPolicy,
|
||||
OperationStatus, OperationVersionState, ResponseCachePolicy, RestRequestContract,
|
||||
RestRequestContractVersion, RestRequestDescriptor, RestResponseDescriptor, RestTarget,
|
||||
RetryPolicy, Samples, Target, ToolDescription, ToolExample, ToolExecutionMode,
|
||||
ToolExecutionPolicy, ToolExecutionPolicyError, WizardState,
|
||||
};
|
||||
pub use product_event::{
|
||||
OnboardingMilestone, PRODUCT_EVENT_IDEMPOTENCY_KEY_MAX_BYTES, PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
|
||||
@@ -270,6 +270,72 @@ pub struct OperationApprovalPolicy {
|
||||
pub elicitation_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Published execution mode of one Tool (Story 4.1, FR-21).
|
||||
///
|
||||
/// This is a scheduling policy of the Published Tool version. It is deliberately separate from
|
||||
/// `ext::protocol::ExecutionMode`, which describes the protocol adapter (streaming vs unary).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ToolExecutionMode {
|
||||
#[default]
|
||||
Synchronous,
|
||||
Background,
|
||||
Adaptive,
|
||||
}
|
||||
|
||||
/// Behaviour promised to a client that does not negotiate durable Tasks (Story 4.1).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum NoTasksFallback {
|
||||
/// Execute through the same synchronous admission path.
|
||||
#[default]
|
||||
Synchronous,
|
||||
/// Reject with a typed unsupported-execution-mode failure; never a Task ID.
|
||||
Unsupported,
|
||||
}
|
||||
|
||||
pub const MAX_TOOL_DEADLINE_MS: u64 = 3_600_000;
|
||||
|
||||
/// Execution policy pinned by a Published Tool version.
|
||||
///
|
||||
/// Absence of the policy keeps the pre-4.1 behaviour: synchronous execution bounded by
|
||||
/// `ExecutionConfig::timeout_ms`, with no background path.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ToolExecutionPolicy {
|
||||
#[serde(default)]
|
||||
pub mode: ToolExecutionMode,
|
||||
/// Absolute budget of one execution, counted from the start of admission.
|
||||
pub deadline_ms: u64,
|
||||
#[serde(default)]
|
||||
pub no_tasks_fallback: NoTasksFallback,
|
||||
}
|
||||
|
||||
impl Default for ToolExecutionPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: ToolExecutionMode::Synchronous,
|
||||
deadline_ms: 30_000,
|
||||
no_tasks_fallback: NoTasksFallback::Synchronous,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolExecutionPolicy {
|
||||
pub fn validate(&self) -> Result<(), ToolExecutionPolicyError> {
|
||||
if !(1..=MAX_TOOL_DEADLINE_MS).contains(&self.deadline_ms) {
|
||||
return Err(ToolExecutionPolicyError::DeadlineOutOfRange);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ToolExecutionPolicyError {
|
||||
#[error("tool execution deadline must be between 1 and {MAX_TOOL_DEADLINE_MS} ms")]
|
||||
DeadlineOutOfRange,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExecutionConfig {
|
||||
@@ -285,6 +351,8 @@ pub struct ExecutionConfig {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub approval_policy: Option<OperationApprovalPolicy>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub execution_policy: Option<ToolExecutionPolicy>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub auth_profile_ref: Option<AuthProfileId>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub headers: BTreeMap<String, String>,
|
||||
@@ -444,9 +512,10 @@ mod tests {
|
||||
edition::OperationSecurityLevel,
|
||||
ids::{AuthProfileId, OperationId},
|
||||
operation::{
|
||||
ConfigExport, ExecutionConfig, Operation, OperationAvailability, OperationLifecycle,
|
||||
OperationLifecycleAction, OperationLifecycleError, OperationStatus,
|
||||
ConfigExport, ExecutionConfig, NoTasksFallback, Operation, OperationAvailability,
|
||||
OperationLifecycle, OperationLifecycleAction, OperationLifecycleError, OperationStatus,
|
||||
OperationVersionState, RestTarget, Samples, Target, ToolDescription, ToolExample,
|
||||
ToolExecutionMode, ToolExecutionPolicy,
|
||||
},
|
||||
protocol::{AuthKind, ExportMode, HttpMethod, Protocol},
|
||||
};
|
||||
@@ -664,6 +733,7 @@ updated_at: 2026-03-25T08:10:00Z
|
||||
idempotency: None,
|
||||
safety: None,
|
||||
approval_policy: None,
|
||||
execution_policy: None,
|
||||
auth_profile_ref: Some(AuthProfileId::new("auth_01")),
|
||||
headers: BTreeMap::new(),
|
||||
},
|
||||
@@ -684,4 +754,76 @@ updated_at: 2026-03-25T08:10:00Z
|
||||
published_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execution_policy_round_trips_all_modes_and_fallbacks() {
|
||||
for (mode, fallback) in [
|
||||
(ToolExecutionMode::Synchronous, NoTasksFallback::Synchronous),
|
||||
(ToolExecutionMode::Background, NoTasksFallback::Synchronous),
|
||||
(ToolExecutionMode::Background, NoTasksFallback::Unsupported),
|
||||
(ToolExecutionMode::Adaptive, NoTasksFallback::Unsupported),
|
||||
] {
|
||||
let config = ExecutionConfig {
|
||||
execution_policy: Some(ToolExecutionPolicy {
|
||||
mode,
|
||||
deadline_ms: 45_000,
|
||||
no_tasks_fallback: fallback,
|
||||
}),
|
||||
..ExecutionConfig::default()
|
||||
};
|
||||
let encoded = serde_json::to_value(&config).unwrap();
|
||||
assert_eq!(encoded["execution_policy"]["deadline_ms"], json!(45_000));
|
||||
let decoded: ExecutionConfig = serde_json::from_value(encoded).unwrap();
|
||||
assert_eq!(decoded, config);
|
||||
assert_eq!(
|
||||
decoded.execution_policy.unwrap().mode,
|
||||
mode,
|
||||
"the published mode must survive the JSON round-trip"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_execution_config_without_policy_stays_synchronous() {
|
||||
let legacy: ExecutionConfig =
|
||||
serde_json::from_value(json!({ "timeout_ms": 12_000 })).unwrap();
|
||||
assert_eq!(legacy.execution_policy, None);
|
||||
assert_eq!(legacy.timeout_ms, 12_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execution_policy_rejects_explicit_invalid_deadline() {
|
||||
assert!(
|
||||
ToolExecutionPolicy {
|
||||
mode: ToolExecutionMode::Background,
|
||||
deadline_ms: 0,
|
||||
no_tasks_fallback: NoTasksFallback::Synchronous,
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
ToolExecutionPolicy {
|
||||
mode: ToolExecutionMode::Adaptive,
|
||||
deadline_ms: crate::operation::MAX_TOOL_DEADLINE_MS + 1,
|
||||
no_tasks_fallback: NoTasksFallback::Unsupported,
|
||||
}
|
||||
.validate()
|
||||
.is_err()
|
||||
);
|
||||
assert!(ToolExecutionPolicy::default().validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn execution_policy_rejects_unknown_fields() {
|
||||
assert!(
|
||||
serde_json::from_value::<ToolExecutionPolicy>(json!({
|
||||
"mode": "background",
|
||||
"deadline_ms": 1000,
|
||||
"no_tasks_fallback": "synchronous",
|
||||
"task_queue": "default"
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user