feat(epic4): подтверждать durable Task после атомарного PG-commit (Story 4.2)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
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
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
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
Application entry выдаёт Task ID только после атомарного PostgreSQL commit Task+intent+capacity; replay/conflict, owner scope, bounded envelope, terminal CAS и fail-closed readiness проверены на реальном PG. Также включён принятый план перехода на rmcp (только документ, миграция не запускается).
This commit is contained in:
1 parent
cc612516a2
commit
2219a7217d
37 files changed
+4028
-136
No files matched your search
@@ -117,6 +117,6 @@ pub use model::{
|
||||
};
|
||||
pub use postgres::{
|
||||
AdmissionLimits, AuthorizedResourceRead, BoundResourceAdmission, PostgresExecutionAdmission,
|
||||
PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry, admission_health,
|
||||
admission_snapshot,
|
||||
PostgresPoolConfig, PostgresPoolConfigError, PostgresRegistry, PostgresTaskStore,
|
||||
admission_health, admission_snapshot, tasks_health,
|
||||
};
|
||||
@@ -6,6 +6,7 @@ mod artifact_cleanup_indexes_v13;
|
||||
mod artifact_metadata_v12;
|
||||
mod authority;
|
||||
mod baseline_v1;
|
||||
mod durable_tasks_v25;
|
||||
mod execution_admission_v24;
|
||||
mod execution_outcome_v5;
|
||||
mod import_plan_v14;
|
||||
@@ -37,6 +38,7 @@ mod schema_guard_v20;
|
||||
mod schema_guard_v22;
|
||||
mod schema_guard_v23;
|
||||
mod schema_guard_v24;
|
||||
mod schema_guard_v25;
|
||||
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::durable_tasks_v25;
|
||||
use super::execution_admission_v24;
|
||||
use super::execution_outcome_v5;
|
||||
use super::import_plan_v14;
|
||||
@@ -40,9 +41,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 = 24;
|
||||
const CURRENT_VERSION: i64 = 25;
|
||||
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, 24,
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
|
||||
];
|
||||
const BASELINE_SOURCE_SHA256: &str =
|
||||
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
|
||||
@@ -337,6 +338,12 @@ impl MigrationAuthority {
|
||||
execution_admission_v24::SOURCE_SHA256,
|
||||
23,
|
||||
),
|
||||
expand_descriptor(
|
||||
25,
|
||||
durable_tasks_v25::NAME,
|
||||
durable_tasks_v25::SOURCE_SHA256,
|
||||
24,
|
||||
),
|
||||
]
|
||||
}
|
||||
pub fn validate_sequence() -> Result<(), MigrationError> {
|
||||
@@ -499,6 +506,9 @@ impl MigrationAuthority {
|
||||
if from < 24 {
|
||||
execution_admission_v24::apply(&mut transaction, &Self::sequence()[23]).await?;
|
||||
}
|
||||
if from < 25 {
|
||||
durable_tasks_v25::apply(&mut transaction, &Self::sequence()[24]).await?;
|
||||
}
|
||||
match inspect(&mut transaction).await? {
|
||||
MigrationPreflight::Current {
|
||||
version: CURRENT_VERSION,
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
use sqlx::{Postgres, Transaction, query};
|
||||
|
||||
use super::authority::{MigrationDescriptor, MigrationError};
|
||||
|
||||
pub(super) const NAME: &str = "durable-tasks-v25";
|
||||
pub(super) const SOURCE: &str = include_str!("durable_tasks_v25.sql");
|
||||
pub(super) const SOURCE_SHA256: &str =
|
||||
"ada48bfb7d7130c84ab38217795608cd368ccb28af66faafbdfc4fc7609f67cd";
|
||||
|
||||
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.durable_tasks_v25",
|
||||
Some(25),
|
||||
"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(25),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
-- V25: durable background Tasks (Story 4.2, FR-22, FR-23).
|
||||
--
|
||||
-- Одна строка `tasks` — принятая durable работа. Идентификатор Task (UUIDv7), owner scope,
|
||||
-- authorization scope, запрошенный Tool и точная published-версия, canonical fingerprint входа,
|
||||
-- support IDs (Request/Trace/parent TraceContext независимо от sampling) и bounded envelopes
|
||||
-- закрепляются в той же PostgreSQL transaction, что и dispatch intent
|
||||
-- (`execution_admission_entries.task_id`) и его queue slot. До commit наружу не выдаётся ни ID, ни ack.
|
||||
--
|
||||
-- `scoped_key` — digest caller-ключа по полному (workspace, owner kind/id, authorization scope,
|
||||
-- operation) scope; UNIQUE по этому набору и есть защита идемпотентности. Повтор того же ключа с тем
|
||||
-- же canonical fingerprint возвращает сохранённую Task, другой fingerprint — typed conflict.
|
||||
--
|
||||
-- `retain_until` — срок хранения записи, а не execution deadline: пока запись в retention, replay
|
||||
-- находит тот же Task. Удаление terminal-записей возможно только после retain_until; queued/working/
|
||||
-- input_required/outcome_unknown не удаляются никогда ради лимита.
|
||||
--
|
||||
-- Строка не хранит credentials, bearer/prepared headers и confirmation tokens: секретные поля входа
|
||||
-- редактируются до записи, а approval хранится безопасной ссылкой.
|
||||
|
||||
create table tasks (
|
||||
task_id uuid not null,
|
||||
workspace_id text not null,
|
||||
owner_kind text not null,
|
||||
owner_id text not null,
|
||||
authorization_scope text not null,
|
||||
operation_id text not null,
|
||||
operation_version integer not null,
|
||||
scoped_key text not null,
|
||||
input_fingerprint text not null,
|
||||
request_id text not null,
|
||||
trace_id text not null,
|
||||
traceparent text not null,
|
||||
trace_sampled boolean not null,
|
||||
policy_mode text not null,
|
||||
approval_reference text,
|
||||
state text not null,
|
||||
version integer not null default 1,
|
||||
attempts integer not null default 0,
|
||||
input_envelope jsonb not null,
|
||||
progress_envelope jsonb,
|
||||
result_envelope jsonb,
|
||||
error_envelope jsonb,
|
||||
execution_deadline timestamptz not null,
|
||||
retain_until timestamptz not null,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
constraint tasks_pkey primary key (task_id),
|
||||
constraint tasks_workspace_check check (octet_length(workspace_id) between 1 and 160),
|
||||
constraint tasks_owner_kind_check check (owner_kind in ('agent', 'admin')),
|
||||
constraint tasks_owner_check check (octet_length(owner_id) between 1 and 160),
|
||||
constraint tasks_authorization_scope_check check (
|
||||
octet_length(authorization_scope) between 1 and 160
|
||||
),
|
||||
constraint tasks_operation_check check (octet_length(operation_id) between 1 and 160),
|
||||
constraint tasks_operation_version_check check (operation_version >= 1),
|
||||
constraint tasks_scoped_key_check check (octet_length(scoped_key) between 16 and 128),
|
||||
constraint tasks_fingerprint_check check (octet_length(input_fingerprint) = 64),
|
||||
constraint tasks_request_check check (octet_length(request_id) between 1 and 128),
|
||||
constraint tasks_trace_check check (octet_length(trace_id) = 32),
|
||||
constraint tasks_traceparent_check check (octet_length(traceparent) = 55),
|
||||
constraint tasks_policy_mode_check check (
|
||||
policy_mode in ('synchronous', 'background', 'adaptive')
|
||||
),
|
||||
constraint tasks_state_check check (
|
||||
state in ('queued', 'working', 'input_required', 'outcome_unknown',
|
||||
'completed', 'failed', 'cancelled')
|
||||
),
|
||||
constraint tasks_lifecycle_check check (version >= 1 and attempts >= 0),
|
||||
constraint tasks_retention_check check (retain_until >= execution_deadline),
|
||||
constraint tasks_approval_check check (
|
||||
approval_reference is null or octet_length(approval_reference) between 1 and 160
|
||||
)
|
||||
);
|
||||
|
||||
create unique index tasks_scoped_key_uidx
|
||||
on tasks (workspace_id, owner_kind, owner_id, authorization_scope, operation_id, scoped_key);
|
||||
|
||||
create index tasks_retention_idx on tasks (state, retain_until, task_id);
|
||||
|
||||
create index tasks_deadline_idx on tasks (state, execution_deadline, task_id);
|
||||
|
||||
-- Dispatch intent: прежняя reserved-строка admission становится точкой связи Task и capacity.
|
||||
-- FK без cascade: удаление принятой Task не маскируется housekeeping-удалением intent.
|
||||
alter table execution_admission_entries
|
||||
add column task_id uuid,
|
||||
add constraint execution_admission_entries_task_fkey
|
||||
foreign key (task_id) references tasks (task_id);
|
||||
|
||||
create unique index execution_admission_entries_task_uidx
|
||||
on execution_admission_entries (task_id) where task_id is not null;
|
||||
@@ -473,7 +473,15 @@ pub(super) async fn validate_schema_fingerprint(
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v24::validate_v24_execution_admission(connection).await?;
|
||||
super::schema_guard_v24::validate_v24_execution_admission(connection, current_version)
|
||||
.await?;
|
||||
}
|
||||
if current_version < 25 {
|
||||
if !super::schema_guard_v25::validate_v25_absent(connection).await? {
|
||||
return Err(schema_error(current_version));
|
||||
}
|
||||
} else {
|
||||
super::schema_guard_v25::validate_v25_durable_tasks(connection).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -39,7 +39,24 @@ const ENTRY_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("granted_at", "timestamp with time zone", true),
|
||||
];
|
||||
|
||||
const CONSTRAINT_COUNT: &[(&str, usize)] = &[(CONTROLLERS, 4), (ENTRIES, 11)];
|
||||
/// V25 adds the nullable Task dispatch-intent link to the same reserved row. At version 24 the
|
||||
/// column must not exist yet, so the guard validates the shape of the version it describes.
|
||||
fn entry_columns(current_version: i64) -> Vec<(&'static str, &'static str, bool)> {
|
||||
let mut columns = ENTRY_COLUMNS.to_vec();
|
||||
if current_version >= 25 {
|
||||
columns.push(("task_id", "uuid", true));
|
||||
}
|
||||
columns
|
||||
}
|
||||
|
||||
fn constraint_count(table: &str, current_version: i64) -> Option<usize> {
|
||||
match table {
|
||||
CONTROLLERS => Some(4),
|
||||
ENTRIES if current_version >= 25 => Some(12),
|
||||
ENTRIES => Some(11),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
const UNIQUE_INDEXES: &[&str] = &["execution_admission_entries_owner_uidx"];
|
||||
|
||||
@@ -72,16 +89,22 @@ pub(super) async fn validate_v24_absent(
|
||||
/// Схема V24 присутствует в ожидаемой форме (для current_version >= 24).
|
||||
pub(super) async fn validate_v24_execution_admission(
|
||||
connection: &mut PgConnection,
|
||||
current_version: i64,
|
||||
) -> 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?;
|
||||
let tables = [
|
||||
(CONTROLLERS, CONTROLLER_COLUMNS.to_vec()),
|
||||
(ENTRIES, entry_columns(current_version)),
|
||||
];
|
||||
for (table, columns) in tables {
|
||||
validate_columns(connection, table, &columns).await?;
|
||||
}
|
||||
for (table, expected) in CONSTRAINT_COUNT {
|
||||
for table in [CONTROLLERS, ENTRIES] {
|
||||
let expected = constraint_count(table, current_version).unwrap_or_default();
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count
|
||||
from pg_catalog.pg_constraint c
|
||||
@@ -95,7 +118,7 @@ pub(super) async fn validate_v24_execution_admission(
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?
|
||||
.try_get("count")
|
||||
.map_err(|_| MigrationError::storage("preflight.schema"))?;
|
||||
if count != i64::try_from(*expected).unwrap_or_default() {
|
||||
if count != i64::try_from(expected).unwrap_or_default() {
|
||||
return Err(v24_error("v24.constraints"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
//! V25 schema guard: durable background Tasks (Story 4.2, FR-22/FR-23).
|
||||
//!
|
||||
//! Схема V25 либо полностью отсутствует (миграция ещё не применена), либо присутствует ровно в
|
||||
//! ожидаемой форме: таблица `tasks` с закрытым словарём state/policy_mode и scoped uniqueness, плюс
|
||||
//! nullable `task_id` на существующей reserved-строке admission с FK и UNIQUE-индексом.
|
||||
|
||||
use sqlx::{PgConnection, Row, query};
|
||||
|
||||
use super::authority::MigrationError;
|
||||
use super::schema_guard::relation_exists;
|
||||
|
||||
const TASKS: &str = "tasks";
|
||||
const ENTRIES: &str = "execution_admission_entries";
|
||||
const SCOPED_INDEX: &str = "tasks_scoped_key_uidx";
|
||||
const TASK_INDEX: &str = "execution_admission_entries_task_uidx";
|
||||
const TASK_FK: &str = "execution_admission_entries_task_fkey";
|
||||
|
||||
const TASK_COLUMNS: &[(&str, &str, bool)] = &[
|
||||
("task_id", "uuid", false),
|
||||
("workspace_id", "text", false),
|
||||
("owner_kind", "text", false),
|
||||
("owner_id", "text", false),
|
||||
("authorization_scope", "text", false),
|
||||
("operation_id", "text", false),
|
||||
("operation_version", "integer", false),
|
||||
("scoped_key", "text", false),
|
||||
("input_fingerprint", "text", false),
|
||||
("request_id", "text", false),
|
||||
("trace_id", "text", false),
|
||||
("traceparent", "text", false),
|
||||
("trace_sampled", "boolean", false),
|
||||
("policy_mode", "text", false),
|
||||
("approval_reference", "text", true),
|
||||
("state", "text", false),
|
||||
("version", "integer", false),
|
||||
("attempts", "integer", false),
|
||||
("input_envelope", "jsonb", false),
|
||||
("progress_envelope", "jsonb", true),
|
||||
("result_envelope", "jsonb", true),
|
||||
("error_envelope", "jsonb", true),
|
||||
("execution_deadline", "timestamp with time zone", false),
|
||||
("retain_until", "timestamp with time zone", false),
|
||||
("created_at", "timestamp with time zone", false),
|
||||
("updated_at", "timestamp with time zone", false),
|
||||
];
|
||||
|
||||
fn v25_error(stage: &'static str) -> MigrationError {
|
||||
MigrationError::new(
|
||||
"partial_sequence",
|
||||
stage,
|
||||
Some(25),
|
||||
"restore_known_good_backup",
|
||||
)
|
||||
}
|
||||
|
||||
/// Схема V25 отсутствует целиком (для current_version < 25).
|
||||
pub(super) async fn validate_v25_absent(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<bool, MigrationError> {
|
||||
if relation_exists(connection, TASKS).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
if super::schema_guard::column_exists(connection, ENTRIES, "task_id").await? {
|
||||
return Ok(false);
|
||||
}
|
||||
for index in [SCOPED_INDEX, TASK_INDEX] {
|
||||
if index_exists(connection, index).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Схема V25 присутствует в ожидаемой форме (для current_version >= 25).
|
||||
pub(super) async fn validate_v25_durable_tasks(
|
||||
connection: &mut PgConnection,
|
||||
) -> Result<(), MigrationError> {
|
||||
if !relation_exists(connection, TASKS).await? {
|
||||
return Err(v25_error("v25.relations"));
|
||||
}
|
||||
let count: i64 = query(
|
||||
"select count(*)::bigint as count from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1",
|
||||
)
|
||||
.bind(TASKS)
|
||||
.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(TASK_COLUMNS.len()).unwrap_or_default() {
|
||||
return Err(v25_error("v25.columns"));
|
||||
}
|
||||
for (column, data_type, nullable) in TASK_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(TASKS)
|
||||
.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(v25_error("v25.columns"));
|
||||
}
|
||||
}
|
||||
if !super::schema_guard::column_exists(connection, ENTRIES, "task_id").await? {
|
||||
return Err(v25_error("v25.intent_column"));
|
||||
}
|
||||
for (constraint, vocabulary) in [
|
||||
(
|
||||
"tasks_state_check",
|
||||
[
|
||||
"queued",
|
||||
"working",
|
||||
"input_required",
|
||||
"outcome_unknown",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
]
|
||||
.as_slice(),
|
||||
),
|
||||
(
|
||||
"tasks_policy_mode_check",
|
||||
["synchronous", "background", "adaptive"].as_slice(),
|
||||
),
|
||||
] {
|
||||
let expression = normalized_expression(connection, TASKS, constraint).await?;
|
||||
if !expression.is_some_and(|expression| {
|
||||
super::schema_guard::enum_constraint_matches(
|
||||
&expression,
|
||||
column_of(constraint),
|
||||
vocabulary,
|
||||
)
|
||||
}) {
|
||||
return Err(v25_error("v25.vocabulary"));
|
||||
}
|
||||
}
|
||||
for (index, table) in [(SCOPED_INDEX, TASKS), (TASK_INDEX, ENTRIES)] {
|
||||
if index_unique(connection, table, index).await? != Some(true) {
|
||||
return Err(v25_error("v25.indexes"));
|
||||
}
|
||||
}
|
||||
if !constraint_exists(connection, ENTRIES, TASK_FK).await? {
|
||||
return Err(v25_error("v25.intent_fk"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn column_of(constraint: &str) -> &'static str {
|
||||
if constraint.contains("policy_mode") {
|
||||
"policy_mode"
|
||||
} else {
|
||||
"state"
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
table: &str,
|
||||
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_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema() and idx.relname = $1 and t.relname = $2",
|
||||
)
|
||||
.bind(index)
|
||||
.bind(table)
|
||||
.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)
|
||||
}))
|
||||
}
|
||||
@@ -13,7 +13,8 @@ use async_trait::async_trait;
|
||||
use crank_core::{
|
||||
AdmissionCursor, AdmissionDecision, AdmissionMode, AdmissionOutcome, AdmissionPermit,
|
||||
AdmissionQueueEntry, AdmissionQueueSnapshot, AdmissionRequest, AdmissionSchedulerConfig,
|
||||
AdmissionStoreError, ApprovalEvidence, ExecutionAdmission, NoTasksFallback, select_next_grant,
|
||||
AdmissionStoreError, ApprovalEvidence, ExecutionAdmission, NoTasksFallback, TaskError,
|
||||
select_next_grant,
|
||||
};
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
@@ -194,7 +195,8 @@ impl ExecutionAdmission for PostgresExecutionAdmission {
|
||||
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'",
|
||||
where ticket_id = $1 and owner_token = $2 and state = 'executing'
|
||||
and task_id is null",
|
||||
)
|
||||
.bind(i64::try_from(permit.ticket_id).unwrap_or(i64::MAX))
|
||||
.bind(&permit.owner_token)
|
||||
@@ -207,7 +209,8 @@ impl ExecutionAdmission for PostgresExecutionAdmission {
|
||||
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')",
|
||||
where ticket_id = $1 and owner_token = $2 and state in ('waiting', 'reserved')
|
||||
and task_id is null",
|
||||
)
|
||||
.bind(i64::try_from(ticket_id).unwrap_or(i64::MAX))
|
||||
.bind(owner_token)
|
||||
@@ -301,9 +304,19 @@ impl PostgresExecutionAdmission {
|
||||
Ok(Attempt::Overloaded)
|
||||
}
|
||||
Err(AttemptError::Failure(error)) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(AdmissionStoreError::unavailable(error.to_string()))
|
||||
}
|
||||
Err(AttemptError::AdmissionFailure(error)) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(error)
|
||||
}
|
||||
Err(AttemptError::UniqueViolation) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(AdmissionStoreError::unavailable(
|
||||
"execution admission hit an unexpected unique conflict",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,82 +327,32 @@ impl PostgresExecutionAdmission {
|
||||
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)?;
|
||||
let cursor = lock_admission_in_tx(transaction, workspace_id).await?;
|
||||
|
||||
// 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)?;
|
||||
// Expired queue decisions and waiting tickets leave the bounded queue; held permits and
|
||||
// Task-linked dispatch intents never do (Story 4.2 owns the durable Task lifetime).
|
||||
cleanup_expired_unlinked(transaction).await?;
|
||||
|
||||
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)
|
||||
{
|
||||
let queued = bounded_queue_len(transaction).await?;
|
||||
if queued >= 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",
|
||||
let ticket_id = insert_admission_entry(
|
||||
transaction,
|
||||
context.request,
|
||||
context.owner_token,
|
||||
state,
|
||||
None,
|
||||
)
|
||||
.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());
|
||||
.await?;
|
||||
*ticket = Some(ticket_id);
|
||||
if context.request.mode == AdmissionMode::Background {
|
||||
return Ok(Attempt::Enqueued(
|
||||
u64::try_from(ticket_id).unwrap_or_default(),
|
||||
));
|
||||
return Ok(Attempt::Enqueued(ticket_id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,22 +483,121 @@ impl PostgresExecutionAdmission {
|
||||
}
|
||||
}
|
||||
|
||||
enum AttemptError {
|
||||
/// Takes both controller locks in the fixed `'*'` -> workspace order. Shared by the synchronous
|
||||
/// admission attempt and the durable Task repository, so both serialize on the same controller rows
|
||||
/// and one task/queue invariant holds. Callers own the transaction; nothing here commits or sleeps.
|
||||
pub(super) async fn lock_admission_in_tx(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> Result<AdmissionCursor, AttemptError> {
|
||||
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)?;
|
||||
|
||||
lock_controller(transaction, DEPLOYMENT_CONTROLLER).await?;
|
||||
lock_controller(transaction, workspace_id).await
|
||||
}
|
||||
|
||||
/// Bounded cleanup of expired waiting/reserved rows that are not a durable Task dispatch intent.
|
||||
pub(super) async fn cleanup_expired_unlinked(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> Result<(), AttemptError> {
|
||||
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()
|
||||
and task_id is null
|
||||
order by ticket_id
|
||||
limit $1
|
||||
)",
|
||||
)
|
||||
.bind(EXPIRED_CLEANUP_BATCH)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Authoritative bounded queue length: waiting and reserved rows share one budget.
|
||||
pub(super) async fn bounded_queue_len(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> Result<u64, AttemptError> {
|
||||
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)?;
|
||||
Ok(u64::try_from(queued).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
/// Inserts one bounded admission row. A Task-linked row is the durable dispatch intent of the Task
|
||||
/// accepted in the same transaction, so its capacity slot can never be silently reclaimed.
|
||||
pub(super) async fn insert_admission_entry(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
request: &AdmissionRequest,
|
||||
owner_token: &str,
|
||||
state: &str,
|
||||
task_id: Option<Uuid>,
|
||||
) -> Result<u64, AttemptError> {
|
||||
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, task_id
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9,
|
||||
to_timestamp($10::double precision / 1000.0), $11)
|
||||
returning ticket_id",
|
||||
)
|
||||
.bind(&request.scope.workspace_id)
|
||||
.bind(&request.scope.agent_key)
|
||||
.bind(&request.scope.operation_id)
|
||||
.bind(i32::try_from(request.scope.operation_version).unwrap_or(i32::MAX))
|
||||
.bind(request.mode.as_str())
|
||||
.bind(policy_mode_str(request))
|
||||
.bind(state)
|
||||
.bind(owner_token)
|
||||
.bind(&request.fingerprint)
|
||||
.bind(request.expires_at_unix_ms)
|
||||
.bind(task_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let ticket_id: i64 = row.try_get("ticket_id").map_err(AttemptError::from_sql)?;
|
||||
Ok(u64::try_from(ticket_id).unwrap_or_default())
|
||||
}
|
||||
|
||||
pub(super) 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),
|
||||
/// A foreign unique constraint aborted the transaction; the caller rolls back and rereads.
|
||||
UniqueViolation,
|
||||
/// Durable-Task side failure (the Task repository maps it to its own typed error).
|
||||
Failure(TaskError),
|
||||
/// Admission side failure.
|
||||
AdmissionFailure(AdmissionStoreError),
|
||||
}
|
||||
|
||||
impl AttemptError {
|
||||
fn from_sql(error: sqlx::Error) -> Self {
|
||||
pub(super) 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))
|
||||
Self::AdmissionFailure(PostgresExecutionAdmission::unavailable(error))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,11 @@ impl PostgresRegistry {
|
||||
super::admission::admission_health(&self.pool).await
|
||||
}
|
||||
|
||||
/// Readiness probe of the durable Task state (Story 4.2).
|
||||
pub async fn durable_tasks_health(&self) -> Result<(), crank_core::TaskError> {
|
||||
super::tasks::tasks_health(&self.pool).await
|
||||
}
|
||||
|
||||
/// Authoritative admission queue readings for low-cardinality metrics.
|
||||
pub async fn execution_admission_snapshot(
|
||||
&self,
|
||||
|
||||
@@ -21,6 +21,7 @@ mod product_event;
|
||||
mod prompt;
|
||||
mod resource;
|
||||
mod secret;
|
||||
mod tasks;
|
||||
mod upstream;
|
||||
mod workspace;
|
||||
mod yaml_import;
|
||||
@@ -42,6 +43,8 @@ pub use admission::{
|
||||
};
|
||||
pub use pool_config::{PostgresPoolConfig, PostgresPoolConfigError};
|
||||
pub use resource::{AuthorizedResourceRead, BoundResourceAdmission};
|
||||
pub use tasks::PostgresTaskStore;
|
||||
pub use tasks::tasks_health;
|
||||
|
||||
use crate::{
|
||||
error::RegistryError,
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
//! PostgreSQL implementation of the durable Task store (Story 4.2, FR-22/FR-23).
|
||||
//!
|
||||
//! One PostgreSQL transaction owns the whole acceptance: Task record, dispatch intent
|
||||
//! (`execution_admission_entries.task_id`) and its queue slot commit together, so no Task ID and no
|
||||
//! acknowledgement can exist without the durable record. The transaction reuses the transaction-aware
|
||||
//! primitives of the execution-admission store (`lock_admission_in_tx`, `bounded_queue_len`,
|
||||
//! `insert_admission_entry`) instead of copying capacity SQL or starting a nested transaction.
|
||||
//!
|
||||
//! Replay is resolved before any capacity mutation and never touches the accepted row. An ambiguous
|
||||
//! COMMIT is reported as an unavailable store: it is never treated as a proven rollback, so no
|
||||
//! compensating delete and no synchronous fallback can happen after an uncertain acceptance.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use crank_core::{
|
||||
AdmissionMode, AdmissionRequest, AdmissionScope, ApprovalEvidence, NoTasksFallback,
|
||||
TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError, TaskFinishRequest,
|
||||
TaskId, TaskOwnerKind, TaskPins, TaskPurgeReport, TaskRecord, TaskState, TaskStore,
|
||||
TaskSupportIds, ToolExecutionMode,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::admission::{
|
||||
AdmissionLimits, AttemptError, bounded_queue_len, cleanup_expired_unlinked,
|
||||
insert_admission_entry, lock_admission_in_tx,
|
||||
};
|
||||
|
||||
const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_id,
|
||||
authorization_scope, operation_id, input_fingerprint, operation_version, policy_mode,
|
||||
approval_reference,
|
||||
request_id, trace_id, traceparent, trace_sampled, input_envelope, progress_envelope,
|
||||
result_envelope, error_envelope, attempts, version,
|
||||
(extract(epoch from execution_deadline) * 1000)::bigint as execution_deadline_ms,
|
||||
(extract(epoch from retain_until) * 1000)::bigint as retain_until_ms,
|
||||
(extract(epoch from created_at) * 1000)::bigint as created_ms,
|
||||
(extract(epoch from updated_at) * 1000)::bigint as updated_ms";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PostgresTaskStore {
|
||||
pool: PgPool,
|
||||
limits: AdmissionLimits,
|
||||
}
|
||||
|
||||
impl PostgresTaskStore {
|
||||
pub fn new(
|
||||
pool: PgPool,
|
||||
limits: AdmissionLimits,
|
||||
scheduler: crank_core::AdmissionSchedulerConfig,
|
||||
) -> Result<Self, TaskError> {
|
||||
limits
|
||||
.validate()
|
||||
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
||||
scheduler
|
||||
.validate()
|
||||
.map_err(|error| TaskError::invalid(error.to_string()))?;
|
||||
Ok(Self { pool, limits })
|
||||
}
|
||||
|
||||
fn unavailable(error: impl std::fmt::Display) -> TaskError {
|
||||
TaskError::unavailable(format!("durable task store is unavailable: {error}"))
|
||||
}
|
||||
|
||||
async fn start(&self) -> Result<Transaction<'_, Postgres>, TaskError> {
|
||||
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)?;
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
/// Scoped lookup of an accepted Task. The full owner/authorization/Tool predicate is part of the
|
||||
/// query, so a foreign row is never fetched.
|
||||
async fn stored_acceptance(
|
||||
&self,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
request: &TaskAcceptRequest,
|
||||
) -> Result<Option<(TaskAcceptance, String)>, AttemptError> {
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks
|
||||
where workspace_id = $1 and owner_kind = $2 and owner_id = $3
|
||||
and authorization_scope = $4 and operation_id = $5 and scoped_key = $6"
|
||||
)))
|
||||
.bind(&request.workspace_id)
|
||||
.bind(request.owner_kind.as_str())
|
||||
.bind(&request.owner_id)
|
||||
.bind(&request.authorization_scope)
|
||||
.bind(&request.operation_id)
|
||||
.bind(&request.scoped_key)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
let Some(row) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(AttemptError::Failure)?;
|
||||
Ok(Some((
|
||||
acceptance_from_record(&record),
|
||||
record.input_fingerprint,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn acceptance_from_record(record: &TaskRecord) -> TaskAcceptance {
|
||||
TaskAcceptance {
|
||||
task_id: record.task_id,
|
||||
state: record.state,
|
||||
operation_version: record.pins.operation_version,
|
||||
support: record.support.clone(),
|
||||
created_at_unix_ms: record.created_at_unix_ms,
|
||||
retain_until_unix_ms: record.pins.retain_until_unix_ms,
|
||||
replayed: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Readiness probe of the durable Task state: the table must be reachable and readable. A missing or
|
||||
/// unreadable schema is a dependency failure, never a degraded-but-ready state.
|
||||
pub async fn tasks_health(pool: &PgPool) -> Result<(), TaskError> {
|
||||
sqlx::query("select count(*)::bigint from tasks where false")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(PostgresTaskStore::unavailable)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One transaction's decision of the acceptance path.
|
||||
enum Accepted {
|
||||
Created(TaskAcceptance),
|
||||
Replayed(TaskAcceptance),
|
||||
Conflict,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TaskStore for PostgresTaskStore {
|
||||
async fn health(&self) -> Result<(), TaskError> {
|
||||
sqlx::query("select count(*)::bigint from tasks where false")
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
super::admission::admission_health(&self.pool)
|
||||
.await
|
||||
.map_err(|error| TaskError::unavailable(error.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn accept(&self, request: TaskAcceptRequest) -> Result<TaskAcceptance, TaskError> {
|
||||
request.validate()?;
|
||||
let mut transaction = self.start().await?;
|
||||
let outcome = self.accept_locked(&mut transaction, &request).await;
|
||||
match outcome {
|
||||
Ok(Accepted::Created(acceptance) | Accepted::Replayed(acceptance)) => {
|
||||
// The acknowledgement of a created Task is only possible after a real COMMIT.
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(TaskAcceptance {
|
||||
replayed: acceptance.replayed,
|
||||
..acceptance
|
||||
})
|
||||
}
|
||||
Ok(Accepted::Conflict) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(TaskError::FingerprintConflict)
|
||||
}
|
||||
Err(AttemptError::Overloaded) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(TaskError::Overloaded {
|
||||
retry_after_ms: crank_core::ADMISSION_OVERLOAD_RETRY_AFTER_MS,
|
||||
})
|
||||
}
|
||||
Err(AttemptError::Contended) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(TaskError::unavailable(
|
||||
"durable task acceptance could not take the admission locks",
|
||||
))
|
||||
}
|
||||
Err(AttemptError::UniqueViolation) => {
|
||||
// Roll back the aborted transaction, then reread the scoped key once outside it.
|
||||
transaction.rollback().await.ok();
|
||||
self.reread_after_unique(&request).await
|
||||
}
|
||||
Err(AttemptError::Failure(error)) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(error)
|
||||
}
|
||||
Err(AttemptError::AdmissionFailure(error)) => {
|
||||
transaction.rollback().await.ok();
|
||||
Err(TaskError::unavailable(error.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read(&self, access: &TaskAccess, task_id: TaskId) -> Result<TaskRecord, TaskError> {
|
||||
access.validate()?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks
|
||||
where task_id = $1 and workspace_id = $2 and owner_kind = $3
|
||||
and owner_id = $4 and authorization_scope = $5"
|
||||
)))
|
||||
.bind(task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Err(TaskError::NotFound);
|
||||
};
|
||||
record_from_row(&row).map_err(Self::unavailable)
|
||||
}
|
||||
|
||||
async fn find(
|
||||
&self,
|
||||
access: &TaskAccess,
|
||||
operation_id: &str,
|
||||
scoped_key: &str,
|
||||
) -> Result<Option<TaskRecord>, TaskError> {
|
||||
access.validate()?;
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks
|
||||
where workspace_id = $1 and owner_kind = $2 and owner_id = $3
|
||||
and authorization_scope = $4 and operation_id = $5 and scoped_key = $6"
|
||||
)))
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.bind(operation_id)
|
||||
.bind(scoped_key)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
row.map(|row| record_from_row(&row)).transpose()
|
||||
}
|
||||
|
||||
async fn finish(&self, request: TaskFinishRequest) -> Result<TaskRecord, TaskError> {
|
||||
request.validate()?;
|
||||
let mut transaction = self.start().await?;
|
||||
let access = &request.access;
|
||||
let update = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"update tasks
|
||||
set state = $1,
|
||||
result_envelope = $2,
|
||||
error_envelope = $3,
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id = $4 and workspace_id = $5 and owner_kind = $6
|
||||
and owner_id = $7 and authorization_scope = $8
|
||||
and state = $9 and version = $10
|
||||
returning {TASK_PROJECTION}"
|
||||
)))
|
||||
.bind(request.target_state.as_str())
|
||||
.bind(request.result.as_ref().map(|value| value.value().clone()))
|
||||
.bind(request.error.as_ref().map(|value| value.value().clone()))
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.bind(request.expected_state.as_str())
|
||||
.bind(i64::from(request.expected_version))
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = update else {
|
||||
transaction.rollback().await.ok();
|
||||
return Err(self.classify_missed_finish(&request).await);
|
||||
};
|
||||
let record = record_from_row(&row).map_err(Self::unavailable)?;
|
||||
// Terminal Task and its dispatch intent leave together: a half-done release is rolled back.
|
||||
sqlx::query("delete from execution_admission_entries where task_id = $1")
|
||||
.bind(request.task_id.as_uuid())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
async fn purge_expired(&self, batch: u32) -> Result<TaskPurgeReport, TaskError> {
|
||||
let batch = i64::from(batch.clamp(1, crank_core::TASK_PURGE_BATCH_LIMIT));
|
||||
let mut transaction = self.start().await?;
|
||||
let expired = sqlx::query(
|
||||
"with expired as (
|
||||
update tasks
|
||||
set state = 'failed',
|
||||
error_envelope = jsonb_build_object('reason', 'execution_deadline_elapsed'),
|
||||
version = version + 1,
|
||||
updated_at = now()
|
||||
where task_id in (
|
||||
select task_id from tasks
|
||||
where state = 'queued' and execution_deadline <= now()
|
||||
order by task_id
|
||||
limit $1
|
||||
)
|
||||
returning task_id
|
||||
), released as (
|
||||
delete from execution_admission_entries
|
||||
where task_id in (select task_id from expired)
|
||||
returning task_id
|
||||
)
|
||||
select (select count(*) from expired)::bigint as expired_queued",
|
||||
)
|
||||
.bind(batch)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let expired_queued: i64 = expired
|
||||
.try_get("expired_queued")
|
||||
.map_err(Self::unavailable)?;
|
||||
let purged = sqlx::query(
|
||||
"delete from tasks
|
||||
where task_id in (
|
||||
select task_id from tasks
|
||||
where state in ('completed', 'failed', 'cancelled') and retain_until <= now()
|
||||
order by task_id
|
||||
limit $1
|
||||
)",
|
||||
)
|
||||
.bind(batch)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
transaction.commit().await.map_err(Self::unavailable)?;
|
||||
Ok(TaskPurgeReport {
|
||||
expired_queued: u64::try_from(expired_queued).unwrap_or_default(),
|
||||
expired_terminal: purged.rows_affected(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PostgresTaskStore {
|
||||
async fn accept_locked(
|
||||
&self,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
request: &TaskAcceptRequest,
|
||||
) -> Result<Accepted, AttemptError> {
|
||||
// Replay first: an already accepted Task is returned without capacity mutation, so it works
|
||||
// with a full queue and after the original execution deadline while the record is retained.
|
||||
if let Some((acceptance, fingerprint)) =
|
||||
self.stored_acceptance(transaction, request).await?
|
||||
{
|
||||
return Ok(if fingerprint == request.input_fingerprint {
|
||||
Accepted::Replayed(acceptance)
|
||||
} else {
|
||||
Accepted::Conflict
|
||||
});
|
||||
}
|
||||
|
||||
// Serialize with synchronous admission and any concurrent acceptance of the same scope.
|
||||
lock_admission_in_tx(transaction, &request.workspace_id).await?;
|
||||
|
||||
// The competitor may have committed while this transaction waited for the controller lock.
|
||||
if let Some((acceptance, fingerprint)) =
|
||||
self.stored_acceptance(transaction, request).await?
|
||||
{
|
||||
return Ok(if fingerprint == request.input_fingerprint {
|
||||
Accepted::Replayed(acceptance)
|
||||
} else {
|
||||
Accepted::Conflict
|
||||
});
|
||||
}
|
||||
|
||||
cleanup_expired_unlinked(transaction).await?;
|
||||
let queued = bounded_queue_len(transaction).await?;
|
||||
if queued >= u64::try_from(self.limits.queue_limit).unwrap_or(u64::MAX) {
|
||||
return Err(AttemptError::Overloaded);
|
||||
}
|
||||
|
||||
let created_ms: i64 = sqlx::query(
|
||||
"insert into tasks (
|
||||
task_id, workspace_id, owner_kind, owner_id, authorization_scope, operation_id,
|
||||
operation_version, scoped_key, input_fingerprint, request_id, trace_id, traceparent,
|
||||
trace_sampled, policy_mode, approval_reference, state, input_envelope,
|
||||
execution_deadline, retain_until
|
||||
) values (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, 'queued',
|
||||
$16, to_timestamp($17::double precision / 1000.0),
|
||||
to_timestamp($18::double precision / 1000.0)
|
||||
)
|
||||
returning (extract(epoch from created_at) * 1000)::bigint as created_ms",
|
||||
)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&request.workspace_id)
|
||||
.bind(request.owner_kind.as_str())
|
||||
.bind(&request.owner_id)
|
||||
.bind(&request.authorization_scope)
|
||||
.bind(&request.operation_id)
|
||||
.bind(i32::try_from(request.pins.operation_version).unwrap_or(i32::MAX))
|
||||
.bind(&request.scoped_key)
|
||||
.bind(&request.input_fingerprint)
|
||||
.bind(request.support.request_id.as_str())
|
||||
.bind(request.support.trace_id.as_str())
|
||||
.bind(&request.support.traceparent)
|
||||
.bind(request.support.trace_sampled)
|
||||
.bind(policy_mode_str(request.pins.policy_mode))
|
||||
.bind(request.pins.approval_reference.as_deref())
|
||||
.bind(request.input.value().clone())
|
||||
.bind(request.pins.execution_deadline_unix_ms)
|
||||
.bind(request.pins.retain_until_unix_ms)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(task_sql_error)?
|
||||
.try_get("created_ms")
|
||||
.map_err(AttemptError::from_sql)?;
|
||||
|
||||
let admission_request = AdmissionRequest {
|
||||
scope: AdmissionScope {
|
||||
workspace_id: request.workspace_id.clone(),
|
||||
agent_key: request.owner_id.clone(),
|
||||
operation_id: request.operation_id.clone(),
|
||||
operation_version: request.pins.operation_version,
|
||||
},
|
||||
mode: AdmissionMode::Background,
|
||||
policy_mode: request.pins.policy_mode,
|
||||
no_tasks_fallback: NoTasksFallback::Unsupported,
|
||||
// Never reached: the intent row is inserted by this transaction, not by `admit`.
|
||||
approval: ApprovalEvidence::NotRequired,
|
||||
fingerprint: request.input_fingerprint.clone(),
|
||||
expires_at_unix_ms: request.pins.execution_deadline_unix_ms,
|
||||
};
|
||||
let owner_token = format!("task_{}", request.task_id);
|
||||
insert_admission_entry(
|
||||
transaction,
|
||||
&admission_request,
|
||||
&owner_token,
|
||||
"reserved",
|
||||
Some(request.task_id.as_uuid()),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Accepted::Created(TaskAcceptance {
|
||||
task_id: request.task_id,
|
||||
state: TaskState::Queued,
|
||||
operation_version: request.pins.operation_version,
|
||||
support: request.support.clone(),
|
||||
created_at_unix_ms: created_ms,
|
||||
retain_until_unix_ms: request.pins.retain_until_unix_ms,
|
||||
replayed: false,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Bounded scoped reread after a foreign unique conflict aborted the transaction.
|
||||
async fn reread_after_unique(
|
||||
&self,
|
||||
request: &TaskAcceptRequest,
|
||||
) -> Result<TaskAcceptance, TaskError> {
|
||||
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"select {TASK_PROJECTION} from tasks
|
||||
where workspace_id = $1 and owner_kind = $2 and owner_id = $3
|
||||
and authorization_scope = $4 and operation_id = $5 and scoped_key = $6"
|
||||
)))
|
||||
.bind(&request.workspace_id)
|
||||
.bind(request.owner_kind.as_str())
|
||||
.bind(&request.owner_id)
|
||||
.bind(&request.authorization_scope)
|
||||
.bind(&request.operation_id)
|
||||
.bind(&request.scoped_key)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
.map_err(Self::unavailable)?;
|
||||
let Some(row) = row else {
|
||||
return Err(TaskError::unavailable(
|
||||
"durable task acceptance ended with an unresolved unique conflict",
|
||||
));
|
||||
};
|
||||
let record = record_from_row(&row)?;
|
||||
if record.input_fingerprint != request.input_fingerprint {
|
||||
return Err(TaskError::FingerprintConflict);
|
||||
}
|
||||
Ok(acceptance_from_record(&record))
|
||||
}
|
||||
|
||||
/// A rejected conditional update is either a lost CAS race or a foreign/absent Task. Both are
|
||||
/// reported without payload, and a foreign Task is indistinguishable from an absent one.
|
||||
async fn classify_missed_finish(&self, request: &TaskFinishRequest) -> TaskError {
|
||||
let access = &request.access;
|
||||
match sqlx::query(
|
||||
"select state, version from tasks
|
||||
where task_id = $1 and workspace_id = $2 and owner_kind = $3
|
||||
and owner_id = $4 and authorization_scope = $5",
|
||||
)
|
||||
.bind(request.task_id.as_uuid())
|
||||
.bind(&access.workspace_id)
|
||||
.bind(access.owner_kind.as_str())
|
||||
.bind(&access.owner_id)
|
||||
.bind(&access.authorization_scope)
|
||||
.fetch_optional(&self.pool)
|
||||
.await
|
||||
{
|
||||
Ok(Some(_)) => TaskError::StateConflict,
|
||||
Ok(None) => TaskError::NotFound,
|
||||
Err(error) => Self::unavailable(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn policy_mode_str(mode: ToolExecutionMode) -> &'static str {
|
||||
match mode {
|
||||
ToolExecutionMode::Synchronous => "synchronous",
|
||||
ToolExecutionMode::Background => "background",
|
||||
ToolExecutionMode::Adaptive => "adaptive",
|
||||
}
|
||||
}
|
||||
|
||||
fn task_sql_error(error: sqlx::Error) -> AttemptError {
|
||||
if error
|
||||
.as_database_error()
|
||||
.and_then(|database| database.code())
|
||||
.as_deref()
|
||||
== Some("23505")
|
||||
{
|
||||
return AttemptError::UniqueViolation;
|
||||
}
|
||||
AttemptError::from_sql(error)
|
||||
}
|
||||
|
||||
fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError> {
|
||||
let task_id: Uuid = row.try_get("task_id").map_err(unavailable_row)?;
|
||||
let state: String = row.try_get("state").map_err(unavailable_row)?;
|
||||
let owner_kind: String = row.try_get("owner_kind").map_err(unavailable_row)?;
|
||||
let policy_mode: String = row.try_get("policy_mode").map_err(unavailable_row)?;
|
||||
let trace_id: String = row.try_get("trace_id").map_err(unavailable_row)?;
|
||||
let request_id: String = row.try_get("request_id").map_err(unavailable_row)?;
|
||||
let envelope = |column: &str| -> Result<Option<TaskEnvelope>, TaskError> {
|
||||
let value: Option<Value> = row.try_get(column).map_err(unavailable_row)?;
|
||||
value.map(TaskEnvelope::from_persisted).transpose()
|
||||
};
|
||||
Ok(TaskRecord {
|
||||
task_id: TaskId::parse(&task_id.to_string())?,
|
||||
state: TaskState::parse(&state)?,
|
||||
workspace_id: row.try_get("workspace_id").map_err(unavailable_row)?,
|
||||
owner_kind: TaskOwnerKind::parse(&owner_kind)?,
|
||||
owner_id: row.try_get("owner_id").map_err(unavailable_row)?,
|
||||
authorization_scope: row
|
||||
.try_get("authorization_scope")
|
||||
.map_err(unavailable_row)?,
|
||||
operation_id: row.try_get("operation_id").map_err(unavailable_row)?,
|
||||
input_fingerprint: row.try_get("input_fingerprint").map_err(unavailable_row)?,
|
||||
pins: TaskPins {
|
||||
operation_version: u32::try_from(
|
||||
row.try_get::<i32, _>("operation_version")
|
||||
.map_err(unavailable_row)?,
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
policy_mode: match policy_mode.as_str() {
|
||||
"background" => ToolExecutionMode::Background,
|
||||
"adaptive" => ToolExecutionMode::Adaptive,
|
||||
_ => ToolExecutionMode::Synchronous,
|
||||
},
|
||||
execution_deadline_unix_ms: row
|
||||
.try_get("execution_deadline_ms")
|
||||
.map_err(unavailable_row)?,
|
||||
retain_until_unix_ms: row.try_get("retain_until_ms").map_err(unavailable_row)?,
|
||||
approval_reference: row.try_get("approval_reference").map_err(unavailable_row)?,
|
||||
},
|
||||
support: TaskSupportIds {
|
||||
request_id: crank_core::RequestId::parse(&request_id)
|
||||
.map_err(|_| TaskError::unavailable("stored request id is invalid"))?,
|
||||
trace_id: crank_core::TraceId::parse(&trace_id)
|
||||
.map_err(|_| TaskError::unavailable("stored trace id is invalid"))?,
|
||||
traceparent: row.try_get("traceparent").map_err(unavailable_row)?,
|
||||
trace_sampled: row.try_get("trace_sampled").map_err(unavailable_row)?,
|
||||
},
|
||||
input: envelope("input_envelope")?
|
||||
.ok_or_else(|| TaskError::unavailable("stored task input envelope is missing"))?,
|
||||
progress: envelope("progress_envelope")?,
|
||||
result: envelope("result_envelope")?,
|
||||
error: envelope("error_envelope")?,
|
||||
attempts: u32::try_from(row.try_get::<i32, _>("attempts").map_err(unavailable_row)?)
|
||||
.unwrap_or_default(),
|
||||
version: u32::try_from(row.try_get::<i32, _>("version").map_err(unavailable_row)?)
|
||||
.unwrap_or_default(),
|
||||
created_at_unix_ms: row.try_get("created_ms").map_err(unavailable_row)?,
|
||||
updated_at_unix_ms: row.try_get("updated_ms").map_err(unavailable_row)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn unavailable_row(error: sqlx::Error) -> TaskError {
|
||||
PostgresTaskStore::unavailable(error)
|
||||
}
|
||||
Reference in new issue
Block a user