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

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:
bsodfather committed 2026-10-26 21:08:08 +00:00
1 parent 44774883a0
commit e80d30ddb0
72 files changed
+4157 -121

No files matched your search

@@ -0,0 +1,618 @@
//! PostgreSQL implementation of the mandatory execution-admission store (Story 4.1, FR-21/FR-24).
//!
//! Source of truth for capacity and durable enqueue decisions of every process: a short transaction
//! locks one deployment controller row and one workspace controller row in a fixed order, then reads
//! bounded counters, inserts/transitions at most one entry and persists the weighted round-robin
//! cursor. No network call happens under the transaction and no connection is held while a waiter is
//! idle between attempts.
use std::collections::BTreeMap;
use std::time::Duration;
use async_trait::async_trait;
use crank_core::{
AdmissionCursor, AdmissionDecision, AdmissionMode, AdmissionOutcome, AdmissionPermit,
AdmissionQueueEntry, AdmissionQueueSnapshot, AdmissionRequest, AdmissionSchedulerConfig,
AdmissionStoreError, ApprovalEvidence, ExecutionAdmission, NoTasksFallback, select_next_grant,
};
use sqlx::{PgPool, Postgres, Row, Transaction};
use uuid::Uuid;
const DEPLOYMENT_CONTROLLER: &str = "*";
const OVERLOAD_RETRY_AFTER_MS: u64 = crank_core::ADMISSION_OVERLOAD_RETRY_AFTER_MS;
const MAX_WAIT_BACKOFF_MS: u64 = 250;
const INITIAL_WAIT_BACKOFF_MS: u64 = 5;
const EXPIRED_CLEANUP_BATCH: i64 = 128;
const QUEUE_READ_LIMIT: i64 = 1024;
/// Deployment-wide bounds of one admission store. They come from validated deployment
/// configuration, never from a request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AdmissionLimits {
pub global_limit: usize,
pub agent_limit: usize,
pub tool_limit: usize,
pub queue_limit: usize,
}
impl Default for AdmissionLimits {
fn default() -> Self {
Self {
global_limit: 64,
agent_limit: 16,
tool_limit: 8,
queue_limit: 32,
}
}
}
impl AdmissionLimits {
pub fn validate(&self) -> Result<(), AdmissionStoreError> {
for (field, value) in [
("global_limit", self.global_limit),
("agent_limit", self.agent_limit),
("tool_limit", self.tool_limit),
] {
if !(1..=65_535).contains(&value) {
return Err(AdmissionStoreError::invalid(format!(
"admission {field} is outside its allowed bounds"
)));
}
}
if !(1..=1_024).contains(&self.queue_limit) {
return Err(AdmissionStoreError::invalid(
"admission queue_limit is outside its allowed bounds",
));
}
Ok(())
}
}
#[derive(Clone)]
pub struct PostgresExecutionAdmission {
pool: PgPool,
limits: AdmissionLimits,
scheduler: AdmissionSchedulerConfig,
}
impl PostgresExecutionAdmission {
pub fn new(
pool: PgPool,
limits: AdmissionLimits,
scheduler: AdmissionSchedulerConfig,
) -> Result<Self, AdmissionStoreError> {
limits.validate()?;
scheduler.validate()?;
Ok(Self {
pool,
limits,
scheduler,
})
}
fn unavailable(error: impl std::fmt::Display) -> AdmissionStoreError {
AdmissionStoreError::unavailable(format!(
"execution admission store is unavailable: {error}"
))
}
}
struct AttemptContext<'a> {
request: &'a AdmissionRequest,
owner_token: &'a str,
}
enum Attempt {
Granted,
Enqueued(u64),
Waiting,
Overloaded,
Expired,
}
#[async_trait]
impl ExecutionAdmission for PostgresExecutionAdmission {
async fn health(&self) -> Result<(), AdmissionStoreError> {
admission_health(&self.pool).await
}
async fn admit(
&self,
request: AdmissionRequest,
) -> Result<AdmissionOutcome, AdmissionStoreError> {
request.validate()?;
if request.approval == ApprovalEvidence::NotGranted {
return Ok(AdmissionOutcome::ApprovalRequired);
}
if request.mode == AdmissionMode::Background
&& request.no_tasks_fallback == NoTasksFallback::Unsupported
{
return Ok(AdmissionOutcome::Unsupported);
}
let owner_token = format!("adm_{}", Uuid::now_v7().simple());
let mut ticket: Option<u64> = None;
let mut backoff = INITIAL_WAIT_BACKOFF_MS;
loop {
if crank_core::current_unix_ms() >= request.expires_at_unix_ms {
if let Some(ticket_id) = ticket {
self.cancel(ticket_id, &owner_token).await?;
}
return Ok(AdmissionOutcome::DeadlineElapsed);
}
let attempt = self
.attempt(
AttemptContext {
request: &request,
owner_token: &owner_token,
},
&mut ticket,
)
.await?;
match attempt {
Attempt::Granted => {
return Ok(AdmissionOutcome::Permitted(AdmissionPermit {
ticket_id: ticket.unwrap_or_default(),
owner_token,
scope: request.scope.clone(),
mode: request.mode,
policy_mode: request.policy_mode,
}));
}
Attempt::Enqueued(ticket_id) => {
return Ok(AdmissionOutcome::Enqueued(AdmissionDecision {
ticket_id,
scope: request.scope.clone(),
expires_at_unix_ms: request.expires_at_unix_ms,
policy_mode: request.policy_mode,
}));
}
Attempt::Expired => {
return Ok(AdmissionOutcome::DeadlineElapsed);
}
Attempt::Overloaded => {
return Ok(AdmissionOutcome::Overloaded {
retry_after_ms: OVERLOAD_RETRY_AFTER_MS,
});
}
Attempt::Waiting => {
let remaining = request
.expires_at_unix_ms
.saturating_sub(crank_core::current_unix_ms())
.max(1);
let sleep_ms = i64::try_from(backoff).unwrap_or(remaining).min(remaining);
tokio::time::sleep(Duration::from_millis(
u64::try_from(sleep_ms).unwrap_or(backoff),
))
.await;
backoff = (backoff * 2).min(MAX_WAIT_BACKOFF_MS);
}
}
}
}
async fn release(&self, permit: &AdmissionPermit) -> Result<bool, AdmissionStoreError> {
let result = sqlx::query(
"delete from execution_admission_entries
where ticket_id = $1 and owner_token = $2 and state = 'executing'",
)
.bind(i64::try_from(permit.ticket_id).unwrap_or(i64::MAX))
.bind(&permit.owner_token)
.execute(&self.pool)
.await
.map_err(Self::unavailable)?;
Ok(result.rows_affected() > 0)
}
async fn cancel(&self, ticket_id: u64, owner_token: &str) -> Result<bool, AdmissionStoreError> {
let result = sqlx::query(
"delete from execution_admission_entries
where ticket_id = $1 and owner_token = $2 and state in ('waiting', 'reserved')",
)
.bind(i64::try_from(ticket_id).unwrap_or(i64::MAX))
.bind(owner_token)
.execute(&self.pool)
.await
.map_err(Self::unavailable)?;
Ok(result.rows_affected() > 0)
}
async fn snapshot(&self) -> Result<AdmissionQueueSnapshot, AdmissionStoreError> {
admission_snapshot(&self.pool).await
}
}
/// Readiness probe of the mandatory admission state: both tables must be reachable and readable.
pub async fn admission_health(pool: &PgPool) -> Result<(), AdmissionStoreError> {
sqlx::query(
"select count(*)::bigint from execution_admission_controllers where workspace_id = $1",
)
.bind(DEPLOYMENT_CONTROLLER)
.fetch_one(pool)
.await
.map_err(PostgresExecutionAdmission::unavailable)?;
sqlx::query("select count(*)::bigint from execution_admission_entries where false")
.fetch_one(pool)
.await
.map_err(PostgresExecutionAdmission::unavailable)?;
Ok(())
}
/// Authoritative queue readings of the deployment-wide admission state.
pub async fn admission_snapshot(
pool: &PgPool,
) -> Result<AdmissionQueueSnapshot, AdmissionStoreError> {
let row = sqlx::query(
"select
count(*) filter (where state in ('waiting', 'reserved')) as queued,
count(*) filter (where state = 'executing') as executing,
coalesce(
(extract(epoch from (now() - min(created_at) filter (where state in ('waiting', 'reserved')))) * 1000)::bigint,
-1
) as oldest_waiting_ms
from execution_admission_entries",
)
.fetch_one(pool)
.await
.map_err(PostgresExecutionAdmission::unavailable)?;
let queued: i64 = row
.try_get("queued")
.map_err(PostgresExecutionAdmission::unavailable)?;
let executing: i64 = row
.try_get("executing")
.map_err(PostgresExecutionAdmission::unavailable)?;
let oldest: i64 = row
.try_get("oldest_waiting_ms")
.map_err(PostgresExecutionAdmission::unavailable)?;
Ok(AdmissionQueueSnapshot {
waiting: u64::try_from(queued).unwrap_or_default(),
executing: u64::try_from(executing).unwrap_or_default(),
oldest_waiting_ms: (oldest >= 0).then(|| u64::try_from(oldest).unwrap_or_default()),
})
}
impl PostgresExecutionAdmission {
async fn attempt(
&self,
context: AttemptContext<'_>,
ticket: &mut Option<u64>,
) -> Result<Attempt, AdmissionStoreError> {
let mut transaction = self.pool.begin().await.map_err(Self::unavailable)?;
sqlx::query("set local lock_timeout = '3000ms'")
.execute(&mut *transaction)
.await
.map_err(Self::unavailable)?;
sqlx::query("set local statement_timeout = '5000ms'")
.execute(&mut *transaction)
.await
.map_err(Self::unavailable)?;
match self.attempt_locked(&mut transaction, context, ticket).await {
Ok(attempt) => {
transaction.commit().await.map_err(Self::unavailable)?;
Ok(attempt)
}
Err(AttemptError::Contended) => {
transaction.rollback().await.ok();
Ok(Attempt::Waiting)
}
Err(AttemptError::Overloaded) => {
transaction.rollback().await.ok();
Ok(Attempt::Overloaded)
}
Err(AttemptError::Failure(error)) => {
transaction.rollback().await.ok();
Err(error)
}
}
}
async fn attempt_locked(
&self,
transaction: &mut Transaction<'_, Postgres>,
context: AttemptContext<'_>,
ticket: &mut Option<u64>,
) -> Result<Attempt, AttemptError> {
let workspace_id = context.request.scope.workspace_id.as_str();
sqlx::query(
"insert into execution_admission_controllers (workspace_id)
values ($1), ($2)
on conflict (workspace_id) do nothing",
)
.bind(DEPLOYMENT_CONTROLLER)
.bind(workspace_id)
.execute(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
// Fixed lock order: deployment controller first, then the workspace controller.
lock_controller(transaction, DEPLOYMENT_CONTROLLER).await?;
let cursor = lock_controller(transaction, workspace_id).await?;
// Expired queue decisions and waiting tickets leave the bounded queue; held permits never do.
sqlx::query(
"delete from execution_admission_entries
where ticket_id in (
select ticket_id from execution_admission_entries
where state in ('waiting', 'reserved') and expires_at <= now()
order by ticket_id
limit $1
)",
)
.bind(EXPIRED_CLEANUP_BATCH)
.execute(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
if ticket.is_none() {
let queued: i64 = sqlx::query(
"select count(*)::bigint as count from execution_admission_entries
where state in ('waiting', 'reserved')",
)
.fetch_one(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?
.try_get("count")
.map_err(AttemptError::from_sql)?;
if u64::try_from(queued).unwrap_or(u64::MAX)
>= u64::try_from(self.limits.queue_limit).unwrap_or(u64::MAX)
{
return Err(AttemptError::Overloaded);
}
let state = match context.request.mode {
AdmissionMode::Synchronous => "waiting",
AdmissionMode::Background => "reserved",
};
let row = sqlx::query(
"insert into execution_admission_entries (
workspace_id, agent_key, operation_id, operation_version, mode, policy_mode,
state, owner_token, fingerprint, expires_at
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9,
to_timestamp($10::double precision / 1000.0))
returning ticket_id",
)
.bind(workspace_id)
.bind(&context.request.scope.agent_key)
.bind(&context.request.scope.operation_id)
.bind(i32::try_from(context.request.scope.operation_version).unwrap_or(i32::MAX))
.bind(context.request.mode.as_str())
.bind(policy_mode_str(context.request))
.bind(state)
.bind(context.owner_token)
.bind(&context.request.fingerprint)
.bind(context.request.expires_at_unix_ms)
.fetch_one(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
let ticket_id: i64 = row.try_get("ticket_id").map_err(AttemptError::from_sql)?;
*ticket = Some(u64::try_from(ticket_id).unwrap_or_default());
if context.request.mode == AdmissionMode::Background {
return Ok(Attempt::Enqueued(
u64::try_from(ticket_id).unwrap_or_default(),
));
}
}
self.grant_next(transaction, workspace_id, &cursor).await?;
let Some(ticket_id) = *ticket else {
return Ok(Attempt::Waiting);
};
let state: Option<String> =
sqlx::query("select state from execution_admission_entries where ticket_id = $1")
.bind(i64::try_from(ticket_id).unwrap_or(i64::MAX))
.fetch_optional(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?
.map(|row| row.try_get("state"))
.transpose()
.map_err(AttemptError::from_sql)?;
match state.as_deref() {
Some("executing") => Ok(Attempt::Granted),
Some(_) => Ok(Attempt::Waiting),
// The ticket expired inside the store (or was removed by another cleanup).
None => Ok(Attempt::Expired),
}
}
/// Grants at most one waiting ticket per transaction, following the persisted weighted
/// round-robin cursor. A blocked head keeps its turn: nothing later is granted in its place.
async fn grant_next(
&self,
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &str,
cursor: &AdmissionCursor,
) -> Result<(), AttemptError> {
let rows = sqlx::query(
"select ticket_id, agent_key, operation_id from execution_admission_entries
where workspace_id = $1 and state = 'waiting'
order by ticket_id
limit $2",
)
.bind(workspace_id)
.bind(QUEUE_READ_LIMIT)
.fetch_all(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
if rows.is_empty() {
return Ok(());
}
let queue = rows
.iter()
.map(|row| {
Ok(AdmissionQueueEntry {
ticket_id: u64::try_from(
row.try_get::<i64, _>("ticket_id")
.map_err(AttemptError::from_sql)?,
)
.unwrap_or_default(),
sequence: 0,
agent_key: row.try_get("agent_key").map_err(AttemptError::from_sql)?,
operation_id: row
.try_get("operation_id")
.map_err(AttemptError::from_sql)?,
})
})
.collect::<Result<Vec<_>, AttemptError>>()?;
let Some(selection) = select_next_grant(&queue, cursor, self.scheduler) else {
return Ok(());
};
let head = &queue[selection.index];
let global_executing: i64 = sqlx::query(
"select count(*)::bigint as count from execution_admission_entries
where state = 'executing'",
)
.fetch_one(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?
.try_get("count")
.map_err(AttemptError::from_sql)?;
let agent_counts = scoped_counts(transaction, workspace_id, "agent_key").await?;
let tool_counts = scoped_counts(transaction, workspace_id, "operation_id").await?;
if u64::try_from(global_executing).unwrap_or(u64::MAX)
>= u64::try_from(self.limits.global_limit).unwrap_or(u64::MAX)
{
return Ok(());
}
let agent_executing = agent_counts
.get(head.agent_key.as_str())
.copied()
.unwrap_or_default();
if agent_executing >= u64::try_from(self.limits.agent_limit).unwrap_or(u64::MAX) {
return Ok(());
}
let tool_executing = tool_counts
.get(head.operation_id.as_str())
.copied()
.unwrap_or_default();
if tool_executing >= u64::try_from(self.limits.tool_limit).unwrap_or(u64::MAX) {
return Ok(());
}
sqlx::query(
"update execution_admission_entries
set state = 'executing', granted_at = now()
where ticket_id = $1 and state = 'waiting'",
)
.bind(i64::try_from(head.ticket_id).unwrap_or(i64::MAX))
.execute(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
sqlx::query(
"update execution_admission_controllers
set cursor_agent = $2,
cursor_agent_credit = $3,
cursor_tool = $4,
cursor_tool_credit = $5,
updated_at = now()
where workspace_id = $1",
)
.bind(workspace_id)
.bind(selection.cursor.agent.as_deref())
.bind(i32::try_from(selection.cursor.agent_credit).unwrap_or_default())
.bind(selection.cursor.tool.as_deref())
.bind(i32::try_from(selection.cursor.tool_credit).unwrap_or_default())
.execute(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
Ok(())
}
}
enum AttemptError {
/// Lock or statement timeout: the transaction made no decision and the waiter retries.
Contended,
/// Bounded queue capacity is exhausted: a typed overload outcome, never an unbounded wait.
Overloaded,
Failure(AdmissionStoreError),
}
impl AttemptError {
fn from_sql(error: sqlx::Error) -> Self {
if let Some(database) = error.as_database_error()
&& matches!(database.code().as_deref(), Some("55P03" | "57014"))
{
return Self::Contended;
}
Self::Failure(PostgresExecutionAdmission::unavailable(error))
}
}
async fn lock_controller(
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &str,
) -> Result<AdmissionCursor, AttemptError> {
sqlx::query(
"update execution_admission_controllers set updated_at = updated_at
where workspace_id = $1",
)
.bind(workspace_id)
.execute(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
let row = sqlx::query(
"select cursor_agent, cursor_agent_credit, cursor_tool, cursor_tool_credit
from execution_admission_controllers where workspace_id = $1",
)
.bind(workspace_id)
.fetch_one(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
Ok(AdmissionCursor {
agent: row
.try_get("cursor_agent")
.map_err(AttemptError::from_sql)?,
agent_credit: u32::try_from(
row.try_get::<i32, _>("cursor_agent_credit")
.map_err(AttemptError::from_sql)?
.max(0),
)
.unwrap_or_default(),
tool: row.try_get("cursor_tool").map_err(AttemptError::from_sql)?,
tool_credit: u32::try_from(
row.try_get::<i32, _>("cursor_tool_credit")
.map_err(AttemptError::from_sql)?
.max(0),
)
.unwrap_or_default(),
})
}
async fn scoped_counts(
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &str,
column: &str,
) -> Result<BTreeMap<String, u64>, AttemptError> {
let statement = if column == "agent_key" {
"select agent_key as key, count(*)::bigint as count
from execution_admission_entries
where workspace_id = $1 and state = 'executing'
group by agent_key"
} else {
"select operation_id as key, count(*)::bigint as count
from execution_admission_entries
where workspace_id = $1 and state = 'executing'
group by operation_id"
};
let rows = sqlx::query(statement)
.bind(workspace_id)
.fetch_all(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
let mut counts = BTreeMap::new();
for row in rows {
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
counts.insert(key, u64::try_from(count).unwrap_or_default());
}
Ok(counts)
}
fn policy_mode_str(request: &AdmissionRequest) -> &'static str {
match request.policy_mode {
crank_core::ToolExecutionMode::Synchronous => "synchronous",
crank_core::ToolExecutionMode::Background => "background",
crank_core::ToolExecutionMode::Adaptive => "adaptive",
}
}
@@ -46,6 +46,19 @@ impl PostgresRegistry {
Ok(())
}
/// Readiness probe of the mandatory execution-admission state (Story 4.1). A missing or
/// unreadable admission schema is a dependency failure, never a degraded-but-ready state.
pub async fn execution_admission_health(&self) -> Result<(), crank_core::AdmissionStoreError> {
super::admission::admission_health(&self.pool).await
}
/// Authoritative admission queue readings for low-cardinality metrics.
pub async fn execution_admission_snapshot(
&self,
) -> Result<crank_core::AdmissionQueueSnapshot, crank_core::AdmissionStoreError> {
super::admission::admission_snapshot(&self.pool).await
}
async fn connect_in_schema(
database_url: &str,
schema: Option<&str>,
@@ -1,3 +1,4 @@
mod admission;
mod agent;
mod agent_catalog;
mod agent_prompt_bindings;
@@ -36,6 +37,9 @@ use serde_json::Value;
use sqlx::{PgPool, Postgres, Row, Transaction, postgres::PgRow, types::Json};
use time::OffsetDateTime;
pub use admission::{
AdmissionLimits, PostgresExecutionAdmission, admission_health, admission_snapshot,
};
pub use pool_config::{PostgresPoolConfig, PostgresPoolConfigError};
pub use resource::{AuthorizedResourceRead, BoundResourceAdmission};