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

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:
bsodfather committed 2026-10-27 00:09:36 +00:00
1 parent cc612516a2
commit 2219a7217d
37 files changed
+4028 -136

No files matched your search

+134 -72
View File
@@ -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))
}
}