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
@@ -116,6 +116,7 @@ pub use model::{
|
||||
YamlImportJob, YamlImportJobCompletion, YamlImportJobId, YamlImportJobStatus,
|
||||
};
|
||||
pub use postgres::{
|
||||
AuthorizedResourceRead, BoundResourceAdmission, PostgresPoolConfig, PostgresPoolConfigError,
|
||||
PostgresRegistry,
|
||||
AdmissionLimits, AuthorizedResourceRead, BoundResourceAdmission, PostgresExecutionAdmission,
|
||||
PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry, admission_health,
|
||||
admission_snapshot,
|
||||
};
|
||||
@@ -6,6 +6,7 @@ mod artifact_cleanup_indexes_v13;
|
||||
mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod execution_admission_v24;
|
||||
mod execution_outcome_v5;
|
||||
mod import_plan_v14;
|
||||
mod master_key_identity_v7;
|
||||
@@ -35,6 +36,7 @@ mod schema_guard_v19;
|
||||
mod schema_guard_v20;
|
||||
mod schema_guard_v22;
|
||||
mod schema_guard_v23;
|
||||
mod schema_guard_v24;
|
||||
mod schema_guard_v7;
|
||||
mod schema_guard_v8;
|
||||
mod schema_guard_v9;
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::agent_resource_bindings_v18;
|
||||
use super::approval_side_effects_v10;
|
||||
use super::artifact_cleanup_indexes_v13;
|
||||
use super::artifact_metadata_v12;
|
||||
use super::execution_admission_v24;
|
||||
use super::execution_outcome_v5;
|
||||
use super::import_plan_v14;
|
||||
use super::master_key_identity_v7;
|
||||
@@ -39,9 +40,9 @@ use preflight::*;
|
||||
use contract::baseline_source_digest;
|
||||
use contract::validate_descriptors;
|
||||
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
|
||||
const CURRENT_VERSION: i64 = 23;
|
||||
const CURRENT_VERSION: i64 = 24;
|
||||
const IMPLEMENTED_VERSIONS: &[i64] = &[
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
@@ -330,6 +331,12 @@ impl MigrationAuthority {
|
||||
prompt_dependencies_v23::SOURCE_SHA256,
|
||||
22,
|
||||
),
|
||||
expand_descriptor(
|
||||
24,
|
||||
execution_admission_v24::NAME,
|
||||
execution_admission_v24::SOURCE_SHA256,
|
||||
23,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -489,6 +496,9 @@ impl MigrationAuthority {
|
||||
if from < 23 {
|
||||
prompt_dependencies_v23::apply(&mut transaction, &Self::sequence()[22]).await?;
|
||||
}
|
||||
if from < 24 {
|
||||
execution_admission_v24::apply(&mut transaction, &Self::sequence()[23]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
|
||||
@@ -140,6 +140,8 @@ pub(super) fn validate_descriptors(
|
||||
!= agent_resource_bindings_v18::SOURCE_SHA256
|
||||
|| sha256_hex(resource_security_revocations_v19::SOURCE.as_bytes())
|
||||
!= resource_security_revocations_v19::SOURCE_SHA256
|
||||
|| sha256_hex(execution_admission_v24::SOURCE.as_bytes())
|
||||
!= execution_admission_v24::SOURCE_SHA256
|
||||
{
|
||||
return Err(MigrationError::new(
|
||||
"invalid_contract",
|
||||
|
||||
@@ -148,6 +148,7 @@ pub(super) async fn inspect(
|
||||
owned_relations::PROMPTS,
|
||||
owned_relations::PROMPT_PUBLICATIONS,
|
||||
owned_relations::PROMPT_DEPENDENCIES,
|
||||
owned_relations::EXECUTION_ADMISSION,
|
||||
] {
|
||||
validate_required_relations(connection, relations, CURRENT_VERSION).await?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "execution-admission-v24";
|
||||
pub(super) const SOURCE: &str = include_str!("execution_admission_v24.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"efe021ebcd68bbed64edaa1e90c3a851f7b167b94ba65d88f525d58160f02681";
|
||||
|
||||
pub(super) async fn apply(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
descriptor: &MigrationDescriptor,
|
||||
) -> Result<(), MigrationError> {
|
||||
sqlx::raw_sql(SOURCE)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.execution_admission_v24",
|
||||
Some(24),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
query(
|
||||
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
|
||||
values ($1, $2, $3, $4, $5)",
|
||||
)
|
||||
.bind(descriptor.version)
|
||||
.bind(descriptor.name)
|
||||
.bind(&descriptor.checksum)
|
||||
.bind(descriptor.phase)
|
||||
.bind(descriptor.compatibility)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
MigrationError::new(
|
||||
"apply_failed",
|
||||
"apply.canonical_ledger",
|
||||
Some(24),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
-- V24: authoritative execution admission state (Story 4.1, FR-21, FR-24).
|
||||
--
|
||||
-- Один deployment-wide admission: PostgreSQL хранит cursor/fairness state, ожидающие тикеты,
|
||||
-- выданные permits и durable enqueue decisions, поэтому несколько процессов делят общий бюджет.
|
||||
--
|
||||
-- `execution_admission_entries` — bounded набор: waiting (ожидает capacity), executing (scoped
|
||||
-- permit выдан, держится до явного release) и reserved (durable enqueue decision с зарезервированным
|
||||
-- queue slot; не исполняется и не рекламируется как Task до Story 4.2).
|
||||
--
|
||||
-- Строка не хранит ни credentials, ни connection/session id, ни prepared headers, ни тело запроса:
|
||||
-- quota key — (workspace, agent) и (workspace, operation) без version. `operation_version` пишется
|
||||
-- только как pin исполняемых semantics и не участвует в квотах.
|
||||
--
|
||||
-- `expires_at` — абсолютный deadline. Queue decisions без dispatch можно expire по deadline; активный
|
||||
-- permit НЕ освобождается по TTL (иначе paused/crashed owner обойдёт global limit): его снимает только
|
||||
-- явный release/cancel владельца.
|
||||
|
||||
create table execution_admission_controllers (
|
||||
workspace_id text not null,
|
||||
cursor_agent text,
|
||||
cursor_agent_credit integer not null default 0,
|
||||
cursor_tool text,
|
||||
cursor_tool_credit integer not null default 0,
|
||||
updated_at timestamptz not null default now(),
|
||||
constraint execution_admission_controllers_pkey primary key (workspace_id),
|
||||
constraint execution_admission_controllers_workspace_check check (
|
||||
octet_length(workspace_id) between 1 and 160
|
||||
),
|
||||
constraint execution_admission_controllers_agent_credit_check check (
|
||||
cursor_agent_credit between 0 and 64
|
||||
),
|
||||
constraint execution_admission_controllers_tool_credit_check check (
|
||||
cursor_tool_credit between 0 and 64
|
||||
)
|
||||
);
|
||||
|
||||
create table execution_admission_entries (
|
||||
ticket_id bigint generated always as identity,
|
||||
workspace_id text not null,
|
||||
agent_key text not null,
|
||||
operation_id text not null,
|
||||
operation_version integer not null,
|
||||
mode text not null,
|
||||
policy_mode text not null,
|
||||
state text not null,
|
||||
owner_token text not null,
|
||||
fingerprint text not null,
|
||||
created_at timestamptz not null default now(),
|
||||
expires_at timestamptz not null,
|
||||
granted_at timestamptz,
|
||||
constraint execution_admission_entries_pkey primary key (ticket_id),
|
||||
constraint execution_admission_entries_workspace_check check (
|
||||
octet_length(workspace_id) between 1 and 160
|
||||
),
|
||||
constraint execution_admission_entries_agent_check check (
|
||||
octet_length(agent_key) between 1 and 160
|
||||
),
|
||||
constraint execution_admission_entries_operation_check check (
|
||||
octet_length(operation_id) between 1 and 160
|
||||
),
|
||||
constraint execution_admission_entries_version_check check (operation_version >= 1),
|
||||
constraint execution_admission_entries_mode_check check (
|
||||
mode in ('synchronous', 'background')
|
||||
),
|
||||
constraint execution_admission_entries_policy_mode_check check (
|
||||
policy_mode in ('synchronous', 'background', 'adaptive')
|
||||
),
|
||||
constraint execution_admission_entries_state_check check (
|
||||
state in ('waiting', 'executing', 'reserved')
|
||||
),
|
||||
constraint execution_admission_entries_owner_check check (
|
||||
octet_length(owner_token) between 1 and 64
|
||||
),
|
||||
constraint execution_admission_entries_fingerprint_check check (
|
||||
octet_length(fingerprint) between 1 and 128
|
||||
),
|
||||
constraint execution_admission_entries_reserved_mode_check check (
|
||||
state <> 'reserved' or mode = 'background'
|
||||
)
|
||||
);
|
||||
|
||||
create unique index execution_admission_entries_owner_uidx
|
||||
on execution_admission_entries (owner_token);
|
||||
|
||||
create index execution_admission_entries_state_idx
|
||||
on execution_admission_entries (state, workspace_id, ticket_id);
|
||||
|
||||
create index execution_admission_entries_agent_idx
|
||||
on execution_admission_entries (state, workspace_id, agent_key);
|
||||
|
||||
create index execution_admission_entries_operation_idx
|
||||
on execution_admission_entries (state, workspace_id, operation_id);
|
||||
@@ -55,6 +55,11 @@ pub(super) const PROMPT_PUBLICATIONS: &[&str] = &["prompt_publications", "agent_
|
||||
pub(super) const PROMPT_DEPENDENCIES: &[&str] =
|
||||
&["prompt_dependencies", "prompt_message_resource_refs"];
|
||||
|
||||
pub(super) const EXECUTION_ADMISSION: &[&str] = &[
|
||||
"execution_admission_controllers",
|
||||
"execution_admission_entries",
|
||||
];
|
||||
|
||||
pub(super) const ARTIFACT_METADATA: &[&str] = &["artifact_blobs", "artifact_sources"];
|
||||
|
||||
pub(super) const IMPORT_PLAN: &[&str] = &["import_plans", "import_plan_applications"];
|
||||
|
||||
@@ -468,6 +468,13 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
} else {
|
||||
super::schema_guard_v23::validate_v23_prompt_dependencies(connection).await?;
|
||||
}
|
||||
if current_version < 24 {
|
||||
if !super::schema_guard_v24::validate_v24_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v24::validate_v24_execution_admission(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ pub(crate) const OWNED_RELATIONS: &[&str] = &[
|
||||
"prompt_messages",
|
||||
"prompt_dependencies",
|
||||
"prompt_message_resource_refs",
|
||||
"execution_admission_controllers",
|
||||
"execution_admission_entries",
|
||||
];
|
||||
|
||||
pub(crate) const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//! V24 schema guard: authoritative execution admission state (Story 4.1, FR-21/FR-24).
|
||||
//!
|
||||
//! Схема V24 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в
|
||||
//! ожидаемой форме: controller-row с weighted round-robin cursor и bounded entries с закрытым
|
||||
//! словарём mode/policy_mode/state, уникальным owner token и индексами квот.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::relation_exists;
|
||||
|
||||
const CONTROLLERS: &str = "execution_admission_controllers";
|
||||
const ENTRIES: &str = "execution_admission_entries";
|
||||
|
||||
const OWNED_RELATIONS: &[&str] = &[CONTROLLERS, ENTRIES];
|
||||
|
||||
const CONTROLLER_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("workspace_id", "text", false),
|
||||
("cursor_agent", "text", true),
|
||||
("cursor_agent_credit", "integer", false),
|
||||
("cursor_tool", "text", true),
|
||||
("cursor_tool_credit", "integer", false),
|
||||
("updated_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
const ENTRY_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("ticket_id", "bigint", false),
|
||||
("workspace_id", "text", false),
|
||||
("agent_key", "text", false),
|
||||
("operation_id", "text", false),
|
||||
("operation_version", "integer", false),
|
||||
("mode", "text", false),
|
||||
("policy_mode", "text", false),
|
||||
("state", "text", false),
|
||||
("owner_token", "text", false),
|
||||
("fingerprint", "text", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("expires_at", "timestamp with time zone", false),
|
||||
("granted_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
const CONSTRAINT_COUNT: &[(&str, usize)] = &[(CONTROLLERS, 4), (ENTRIES, 11)];
|
||||
|
||||
const UNIQUE_INDEXES: &[&str] = &["execution_admission_entries_owner_uidx"];
|
||||
|
||||
fn v24_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(24),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V24 отсутствует целиком (для current_version < 24).
|
||||
pub(super) async fn validate_v24_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if relation_exists(connection, relation).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
for index in UNIQUE_INDEXES {
|
||||
if index_exists(connection, index).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V24 присутствует в ожидаемой форме (для current_version >= 24).
|
||||
pub(super) async fn validate_v24_execution_admission(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
for relation in OWNED_RELATIONS {
|
||||
if !relation_exists(connection, relation).await? {
|
||||
return Err(v24_error("v24.relations"));
|
||||
}
|
||||
}
|
||||
for (table, columns) in [(CONTROLLERS, CONTROLLER_COLUMNS), (ENTRIES, ENTRY_COLUMNS)] {
|
||||
validate_columns(connection, table, columns).await?;
|
||||
}
|
||||
for (table, expected) in CONSTRAINT_COUNT {
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if count != i64::try_from(*expected).unwrap_or_default() {
|
||||
return Err(v24_error("v24.constraints"));
|
||||
}
|
||||
}
|
||||
for (table, constraint) in [
|
||||
(CONTROLLERS, "execution_admission_controllers_pkey"),
|
||||
(ENTRIES, "execution_admission_entries_pkey"),
|
||||
(ENTRIES, "execution_admission_entries_state_check"),
|
||||
] {
|
||||
if !constraint_exists(connection, table, constraint).await? {
|
||||
return Err(v24_error("v24.constraint_missing"));
|
||||
}
|
||||
}
|
||||
if !normalized_expression(
|
||||
connection,
|
||||
ENTRIES,
|
||||
"execution_admission_entries_state_check",
|
||||
)
|
||||
.await?
|
||||
.is_some_and(|expression| {
|
||||
super::schema_guard::enum_constraint_matches(
|
||||
&expression,
|
||||
"state",
|
||||
&["waiting", "executing", "reserved"],
|
||||
)
|
||||
}) {
|
||||
return Err(v24_error("v24.state_vocabulary"));
|
||||
}
|
||||
for index in UNIQUE_INDEXES {
|
||||
let unique = index_unique(connection, index).await?;
|
||||
if unique != Some(true) {
|
||||
return Err(v24_error("v24.indexes"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate_columns(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
columns: &[(&str, &str, bool)],
|
||||
) -> Result<(), MigrationError> {
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if count != i64::try_from(columns.len()).unwrap_or_default() {
|
||||
return Err(v24_error("v24.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in columns {
|
||||
let row = query(
|
||||
"select data_type, is_nullable from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
let valid = row.is_some_and(|row| {
|
||||
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
|
||||
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
|
||||
== Some(if *nullable { "YES" } else { "NO" })
|
||||
});
|
||||
if !valid {
|
||||
return Err(v24_error("v24.columns"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn constraint_exists(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2
|
||||
) as present",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn normalized_expression(
|
||||
connection: &mut PgConnection,
|
||||
table: &str,
|
||||
constraint: &str,
|
||||
) -> Result<Option<String>, MigrationError> {
|
||||
let row = query(
|
||||
"select pg_get_expr(c.conbin, c.conrelid) as expression
|
||||
from pg_catalog.pg_constraint c
|
||||
join pg_catalog.pg_class t on t.oid = c.conrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema() and t.relname = $1 and c.conname = $2
|
||||
and c.contype = 'c'",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(constraint)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
Ok(row.and_then(|row| row.try_get::<String, _>("expression").ok()))
|
||||
}
|
||||
|
||||
async fn index_exists(connection: &mut PgConnection, index: &str) -> Result<bool, MigrationError> {
|
||||
query(
|
||||
"select exists (
|
||||
select 1 from pg_catalog.pg_class idx
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema() and idx.relname = $1
|
||||
) as present",
|
||||
)
|
||||
.bind(index)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get::<bool, _>("present")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))
|
||||
}
|
||||
|
||||
async fn index_unique(
|
||||
connection: &mut PgConnection,
|
||||
index: &str,
|
||||
) -> Result<Option<bool>, MigrationError> {
|
||||
let row = query(
|
||||
"select i.indisunique, i.indisvalid
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema() and idx.relname = $1",
|
||||
)
|
||||
.bind(index)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
Ok(row.and_then(|row| {
|
||||
let unique = row.try_get::<bool, _>("indisunique").ok()?;
|
||||
let valid = row.try_get::<bool, _>("indisvalid").ok()?;
|
||||
Some(unique && valid)
|
||||
}))
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
|
||||
Reference in new issue
Block a user