//! 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, } #[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) -> Self { Self::Unavailable { message: message.into(), } } pub fn invalid(message: impl Into) -> 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; /// Releases the caller's own permit. Idempotent: a repeated release returns `false`. async fn release(&self, permit: &AdmissionPermit) -> Result; /// 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; /// Bounded authoritative queue readings for low-cardinality metrics. async fn snapshot(&self) -> Result; } /// 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, pub agent_credit: u32, pub tool: Option, 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 { 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")); } }