feat(epic4): исполнять durable Task через PG lease/fence и восстанавливать после сбоев (Story 4.3)
CI / UI Checks (pull_request) Successful in 15s
CI / Rust Checks (pull_request) Failing after 4m58s
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) Failing after 1s
CI / Deploy (pull_request) Skipped

mcp-server запускает сохранённые фоновые задачи: захват по PostgreSQL lease с
fence-токеном, зашифрованный input и повторная проверка доступа до сетевого
вызова, checkpoint с AttemptID до dispatch и восстановление только по PG.
Устаревший worker не может зафиксировать результат.

Добавлены миграции v26–v28 (V25 не меняется), guard их отсутствия в старой
схеме, метрики/трассы попыток (attempt_trace) и остановка до отправки запроса:
стоп в окне после checkpoint и до permit завершает задачу как
failed(shutdown_before_dispatch) без сетевых вызовов, соседние queued-задачи
остаются доступными. Retry-попытки получают отдельные дочерние spans с durable
current_attempt_id. Shared admission/fairness из Story 4.1 сохранены.

Проверки: durable_tasks 13/13, stages 11/11 (retry 5), runtime lib 47,
bin shutdown 1, registry tasks 16, admission 11, migrations 58 (независимая QA
и исходный runtime-прогон), точный exact-head CI остаётся обязательным.
This commit is contained in:
bsodfather committed 2026-10-29 22:26:52 +00:00
1 parent 6df6ffac4e
commit f9f8c625d1
52 files changed
+5142 -232

No files matched your search

@@ -577,6 +577,145 @@ pub(super) async fn insert_admission_entry(
Ok(u64::try_from(ticket_id).unwrap_or_default())
}
/// Shared grant step used by the durable Task store: grants one reserved Task intent if capacity allows,
/// marks it `executing`, persists the weighted round-robin cursor, and returns its Task id. It reuses
/// the same selector/capacity logic as synchronous admission so no second policy exists.
pub(super) async fn grant_next_task(
transaction: &mut Transaction<'_, Postgres>,
workspace_id: &str,
cursor: &AdmissionCursor,
limits: &AdmissionLimits,
scheduler: AdmissionSchedulerConfig,
) -> Result<(Option<Uuid>, AdmissionCursor), AttemptError> {
let rows = sqlx::query(
"select ticket_id, agent_key, operation_id, task_id
from execution_admission_entries
where state = 'reserved' and task_id is not null
order by ticket_id
limit $1
for update skip locked",
)
.bind(QUEUE_READ_LIMIT)
.fetch_all(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
if rows.is_empty() {
return Ok((None, cursor.clone()));
}
struct Candidate {
entry: AdmissionQueueEntry,
task_id: Uuid,
}
let mut candidates = Vec::with_capacity(rows.len());
for row in rows {
let ticket_id: i64 = row.try_get("ticket_id").map_err(AttemptError::from_sql)?;
let task_id: Uuid = row.try_get("task_id").map_err(AttemptError::from_sql)?;
candidates.push(Candidate {
entry: AdmissionQueueEntry {
ticket_id: u64::try_from(ticket_id).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)?,
},
task_id,
});
}
let queue: Vec<AdmissionQueueEntry> = candidates.iter().map(|c| c.entry.clone()).collect();
let Some(selection) = select_next_grant(&queue, cursor, scheduler) else {
return Ok((None, cursor.clone()));
};
let head_index = selection.index;
let head = &candidates[head_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 = sqlx::query(
"select agent_key as key, count(*)::bigint as count
from execution_admission_entries where state = 'executing' group by agent_key",
)
.fetch_all(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
let mut agent_map = std::collections::BTreeMap::new();
for row in agent_counts {
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
agent_map.insert(key, u64::try_from(count).unwrap_or_default());
}
let tool_counts = sqlx::query(
"select operation_id as key, count(*)::bigint as count
from execution_admission_entries where state = 'executing' group by operation_id",
)
.fetch_all(&mut **transaction)
.await
.map_err(AttemptError::from_sql)?;
let mut tool_map = std::collections::BTreeMap::new();
for row in tool_counts {
let key: String = row.try_get("key").map_err(AttemptError::from_sql)?;
let count: i64 = row.try_get("count").map_err(AttemptError::from_sql)?;
tool_map.insert(key, u64::try_from(count).unwrap_or_default());
}
if u64::try_from(global_executing).unwrap_or(u64::MAX)
>= u64::try_from(limits.global_limit).unwrap_or(u64::MAX)
{
return Ok((None, cursor.clone()));
}
let agent_executing = agent_map
.get(head.entry.agent_key.as_str())
.copied()
.unwrap_or_default();
if agent_executing >= u64::try_from(limits.agent_limit).unwrap_or(u64::MAX) {
return Ok((None, cursor.clone()));
}
let tool_executing = tool_map
.get(head.entry.operation_id.as_str())
.copied()
.unwrap_or_default();
if tool_executing >= u64::try_from(limits.tool_limit).unwrap_or(u64::MAX) {
return Ok((None, cursor.clone()));
}
sqlx::query(
"update execution_admission_entries
set state = 'executing', granted_at = clock_timestamp()
where ticket_id = $1 and state = 'reserved'",
)
.bind(i64::try_from(head.entry.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((Some(head.task_id), selection.cursor))
}
#[derive(Debug)]
pub(super) enum AttemptError {
/// Lock or statement timeout: the transaction made no decision and the waiter retries.
Contended,
@@ -170,6 +170,69 @@ impl PostgresRegistry {
.transpose()
}
/// Authoritative revalidation of the Platform API key that authorized a durable Task (Story 4.3).
///
/// The key is returned only when the exact immutable ID is still active, unexpired and bound to
/// the same workspace and agent; otherwise `None`, so a worker fails closed. Only the immutable
/// identity is supplied here — the bearer secret is never stored or re-read.
pub async fn revalidate_platform_api_key(
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
key_id: &PlatformApiKeyId,
) -> Result<Option<PlatformApiKeyRecord>, RegistryError> {
let row = sqlx::query(
"select
k.id,
k.workspace_id,
k.agent_id,
k.key_kind,
k.name,
k.prefix,
k.scopes_json,
k.status,
k.created_at,
k.last_used_at,
k.expires_at,
k.allowed_origins_json
from platform_api_keys k
where k.id = $1
and k.workspace_id = $2
and k.agent_id = $3
and k.key_kind = 'mcp_client'
and k.status = 'active'
and (k.expires_at is null or k.expires_at > now())
limit 1",
)
.bind(key_id.as_str())
.bind(workspace_id.as_str())
.bind(agent_id.as_str())
.fetch_optional(&self.pool)
.await?;
row.map(|row| {
Ok(PlatformApiKeyRecord {
api_key: PlatformApiKey {
id: PlatformApiKeyId::new(row.get::<String, _>("id")),
workspace_id: WorkspaceId::new(row.get::<String, _>("workspace_id")),
agent_id: row.get::<Option<String>, _>("agent_id").map(AgentId::new),
key_kind: deserialize_enum_text(&row.get::<String, _>("key_kind"), "key_kind")?,
name: row.get("name"),
prefix: row.get("prefix"),
scopes: deserialize_json_value(row.get::<Value, _>("scopes_json"))?,
status: deserialize_enum_text(&row.get::<String, _>("status"), "status")?,
created_at: row.get("created_at"),
last_used_at: row.get("last_used_at"),
expires_at: row.get("expires_at"),
allowed_origins: deserialize_json_value(
row.get::<Value, _>("allowed_origins_json"),
)?,
},
})
})
.transpose()
}
pub async fn get_approval_api_key_by_secret_for_agent_slug(
&self,
workspace_slug: &str,
@@ -1,6 +1,6 @@
use super::*;
const MASTER_KEY_PAGE_LIMIT_MAX: i64 = 10_000;
pub(super) const MASTER_KEY_PAGE_LIMIT_MAX: i64 = 10_000;
impl PostgresRegistry {
pub async fn verify_or_register_master_key_identity(
@@ -356,12 +356,19 @@ impl PostgresRegistry {
return Err(RegistryError::MasterKeyRotationConflict);
}
let total = sqlx::query_scalar::<_, i64>(
let secret_total = sqlx::query_scalar::<_, i64>(
"select count(*) from secret_versions where master_key_epoch = $1",
)
.bind(source_epoch)
.fetch_one(&mut *tx)
.await?;
let task_total = sqlx::query_scalar::<_, i64>(
"select count(*) from tasks where executable_input_master_key_epoch = $1",
)
.bind(source_epoch)
.fetch_one(&mut *tx)
.await?;
let total = secret_total + task_total;
let rotation_id = format!("master-key-e{source_epoch}-to-e{target_epoch}");
let aborted = sqlx::query(
"select
@@ -403,6 +410,16 @@ impl PostgresRegistry {
.bind(target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update tasks
set target_executable_input_ciphertext = null,
target_executable_input_key_version = null,
target_executable_input_master_key_epoch = null
where target_executable_input_master_key_epoch = $1",
)
.bind(target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update master_key_rotations
set state = 'running',
@@ -662,9 +679,24 @@ impl PostgresRegistry {
.bind(rotation.target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update tasks
set executable_input_ciphertext = target_executable_input_ciphertext,
executable_input_key_version = target_executable_input_key_version,
executable_input_master_key_epoch = target_executable_input_master_key_epoch,
target_executable_input_ciphertext = null,
target_executable_input_key_version = null,
target_executable_input_master_key_epoch = null
where executable_input_master_key_epoch = $1
and target_executable_input_master_key_epoch = $2",
)
.bind(rotation.source_epoch)
.bind(rotation.target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update master_key_rotations
set state = 'promoted',
set state = 'promoted',
updated_at = $2::timestamptz
where id = $1",
)
@@ -697,6 +729,16 @@ impl PostgresRegistry {
.bind(rotation.target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update tasks
set target_executable_input_ciphertext = null,
target_executable_input_key_version = null,
target_executable_input_master_key_epoch = null
where target_executable_input_master_key_epoch = $1",
)
.bind(rotation.target_epoch)
.execute(&mut *tx)
.await?;
sqlx::query(
"update master_key_rotations
set state = 'aborted',
@@ -883,7 +925,7 @@ async fn select_active_master_key_identity_for_update(
Ok(row.map(map_master_key_identity))
}
async fn select_master_key_rotation_for_update(
pub(super) async fn select_master_key_rotation_for_update(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
rotation_id: &str,
) -> Result<MasterKeyRotationRecord, RegistryError> {
@@ -915,16 +957,19 @@ async fn select_master_key_rotation_for_update(
})
}
async fn count_staged_rotation_targets(
pub(super) async fn count_staged_rotation_targets(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
source_epoch: i64,
target_epoch: i64,
) -> Result<i64, RegistryError> {
let count = sqlx::query_scalar::<_, i64>(
"select count(*)
from secret_versions
where master_key_epoch = $1
and target_master_key_epoch = $2",
"select
(select count(*) from secret_versions
where master_key_epoch = $1
and target_master_key_epoch = $2) +
(select count(*) from tasks
where executable_input_master_key_epoch = $1
and target_executable_input_master_key_epoch = $2)",
)
.bind(source_epoch)
.bind(target_epoch)
@@ -0,0 +1,143 @@
//! Task ciphertext paging/staging of the master-key rotation (Story 4.3).
//!
//! Extracted from `master_key.rs` without logic changes so that module stays within the
//! code-health line limit; the operations and their SQL are unchanged.
use super::master_key::{
MASTER_KEY_PAGE_LIMIT_MAX, count_staged_rotation_targets, select_master_key_rotation_for_update,
};
use super::*;
fn map_master_key_task_version(
row: sqlx::postgres::PgRow,
) -> Result<MasterKeyTaskVersion, RegistryError> {
Ok(MasterKeyTaskVersion {
task_id: row.get::<String, _>("task_id"),
ciphertext: row
.get::<Option<String>, _>("executable_input_ciphertext")
.unwrap_or_default(),
key_version: row
.get::<Option<String>, _>("executable_input_key_version")
.unwrap_or_default(),
epoch: row
.get::<Option<i64>, _>("executable_input_master_key_epoch")
.unwrap_or_default(),
target_ciphertext: row.get::<Option<String>, _>("target_executable_input_ciphertext"),
target_key_version: row.get::<Option<String>, _>("target_executable_input_key_version"),
target_epoch: row.get::<Option<i64>, _>("target_executable_input_master_key_epoch"),
})
}
impl PostgresRegistry {
pub async fn list_tasks_for_master_key_epoch_page(
&self,
epoch: i64,
after_task_id: Option<&str>,
limit: i64,
) -> Result<Vec<MasterKeyTaskVersion>, RegistryError> {
if epoch < 1 || !(1..=MASTER_KEY_PAGE_LIMIT_MAX).contains(&limit) {
return Err(RegistryError::InvalidMasterKeyIdentity);
}
let rows = sqlx::query(
"select task_id::text as task_id, executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch, target_executable_input_ciphertext, target_executable_input_key_version, target_executable_input_master_key_epoch from tasks where executable_input_master_key_epoch = $1 and ($2::text is null or task_id::text > $2::text) order by task_id asc limit $3",
)
.bind(epoch)
.bind(after_task_id)
.bind(limit)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(map_master_key_task_version).collect()
}
pub async fn list_target_tasks_for_master_key_rotation_page(
&self,
target_epoch: i64,
after_task_id: Option<&str>,
limit: i64,
) -> Result<Vec<MasterKeyTaskVersion>, RegistryError> {
if target_epoch < 1 || !(1..=MASTER_KEY_PAGE_LIMIT_MAX).contains(&limit) {
return Err(RegistryError::InvalidMasterKeyIdentity);
}
let rows = sqlx::query(
"select task_id::text as task_id, executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch, target_executable_input_ciphertext, target_executable_input_key_version, target_executable_input_master_key_epoch from tasks where target_executable_input_master_key_epoch = $1 and ($2::text is null or task_id::text > $2::text) order by task_id asc limit $3",
)
.bind(target_epoch)
.bind(after_task_id)
.bind(limit)
.fetch_all(&self.pool)
.await?;
rows.into_iter().map(map_master_key_task_version).collect()
}
pub async fn stage_master_key_rotation_task_ciphertext(
&self,
rotation_id: &str,
task_id: &str,
source_epoch: i64,
target_ciphertext: &str,
target_key_version: &str,
target_epoch: i64,
now: &OffsetDateTime,
) -> Result<MasterKeyRotationRecord, RegistryError> {
let mut tx = self.pool.begin().await?;
let rotation = select_master_key_rotation_for_update(&mut tx, rotation_id).await?;
if rotation.state != "running"
|| rotation.source_epoch != source_epoch
|| rotation.target_epoch != target_epoch
{
return Err(RegistryError::MasterKeyRotationConflict);
}
let result = sqlx::query(
"update tasks
set target_executable_input_ciphertext = $3,
target_executable_input_key_version = $4,
target_executable_input_master_key_epoch = $5
where task_id::text = $1
and executable_input_master_key_epoch = $2
and (
target_executable_input_master_key_epoch is null
or target_executable_input_master_key_epoch = $5
)
and (
target_executable_input_ciphertext is null
or target_executable_input_ciphertext = $3
)",
)
.bind(task_id)
.bind(source_epoch)
.bind(target_ciphertext)
.bind(target_key_version)
.bind(target_epoch)
.execute(&mut *tx)
.await?;
if result.rows_affected() != 1 {
return Err(RegistryError::MasterKeyRotationConflict);
}
let processed = count_staged_rotation_targets(&mut tx, source_epoch, target_epoch).await?;
sqlx::query(
"update master_key_rotations
set checkpoint_secret_id = checkpoint_secret_id,
processed_secret_versions = $2,
updated_at = $3::timestamptz
where id = $1",
)
.bind(rotation_id)
.bind(processed)
.bind(now)
.execute(&mut *tx)
.await?;
let updated = select_master_key_rotation_for_update(&mut tx, rotation_id).await?;
tx.commit().await?;
Ok(updated)
}
}
pub struct MasterKeyTaskVersion {
pub task_id: String,
pub ciphertext: String,
pub key_version: String,
pub epoch: i64,
pub target_ciphertext: Option<String>,
pub target_key_version: Option<String>,
pub target_epoch: Option<i64>,
}
@@ -10,6 +10,7 @@ mod auth;
mod connection;
mod import_job;
mod master_key;
mod master_key_tasks;
mod observability;
mod onboarding;
mod onboarding_import;
+408 -10
View File
@@ -13,9 +13,9 @@
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,
PlatformApiKeyId, TaskAcceptRequest, TaskAcceptance, TaskAccess, TaskEnvelope, TaskError,
TaskFinishRequest, TaskId, TaskLease, TaskOwnerKind, TaskPins, TaskPurgeReport, TaskRecord,
TaskState, TaskStore, TaskSupportIds, ToolExecutionMode,
};
use serde_json::Value;
use sqlx::{PgPool, Postgres, Row, Transaction};
@@ -27,10 +27,14 @@ use super::admission::{
};
const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_id,
authorization_scope, operation_id, input_fingerprint, operation_version, policy_mode,
authorization_scope, platform_api_key_id, 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,
result_envelope, error_envelope, attempts, fence, lease_owner, lease_until,
(extract(epoch from lease_until) * 1000)::bigint as lease_until_ms,
current_attempt_id, dispatch_started_at,
(extract(epoch from dispatch_started_at) * 1000)::bigint as dispatch_started_at_ms, 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,
@@ -40,6 +44,7 @@ const TASK_PROJECTION: &str = "task_id, state, workspace_id, owner_kind, owner_i
pub struct PostgresTaskStore {
pool: PgPool,
limits: AdmissionLimits,
scheduler: crank_core::AdmissionSchedulerConfig,
}
impl PostgresTaskStore {
@@ -54,7 +59,11 @@ impl PostgresTaskStore {
scheduler
.validate()
.map_err(|error| TaskError::invalid(error.to_string()))?;
Ok(Self { pool, limits })
Ok(Self {
pool,
limits,
scheduler,
})
}
fn unavailable(error: impl std::fmt::Display) -> TaskError {
@@ -151,6 +160,20 @@ impl TaskStore for PostgresTaskStore {
async fn accept(&self, request: TaskAcceptRequest) -> Result<TaskAcceptance, TaskError> {
request.validate()?;
let mut transaction = self.start().await?;
super::master_key::ensure_no_active_master_key_rotation(&mut transaction)
.await
.map_err(|error| match error {
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
_ => TaskError::StateConflict,
})?;
if let Some(epoch) = request.executable_input_master_key_epoch {
super::master_key::ensure_active_master_key_epoch(&mut transaction, epoch)
.await
.map_err(|error| match error {
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
_ => TaskError::StateConflict,
})?;
}
let outcome = self.accept_locked(&mut transaction, &request).await;
match outcome {
Ok(Accepted::Created(acceptance) | Accepted::Replayed(acceptance)) => {
@@ -252,6 +275,7 @@ impl TaskStore for PostgresTaskStore {
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
and (lease_owner is null or fence = 0)
returning {TASK_PROJECTION}"
)))
.bind(request.target_state.as_str())
@@ -285,6 +309,12 @@ impl TaskStore for PostgresTaskStore {
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?;
super::master_key::ensure_no_active_master_key_rotation(&mut transaction)
.await
.map_err(|error| match error {
crate::RegistryError::Storage(_) => TaskError::unavailable(error.to_string()),
_ => TaskError::StateConflict,
})?;
let expired = sqlx::query(
"with expired as (
update tasks
@@ -295,6 +325,7 @@ impl TaskStore for PostgresTaskStore {
where task_id in (
select task_id from tasks
where state = 'queued' and execution_deadline <= now()
and lease_owner is null
order by task_id
limit $1
)
@@ -332,6 +363,351 @@ impl TaskStore for PostgresTaskStore {
expired_terminal: purged.rows_affected(),
})
}
async fn claim_batch(
&self,
owner: &str,
batch_limit: u32,
lease_ms: i64,
) -> Result<Vec<TaskLease>, TaskError> {
let batch = (batch_limit.clamp(1, 64)) as usize;
// A checkpointed attempt is never redispatched: once its lease expires the outbound outcome
// is uncertain, so it resolves to outcome_unknown and releases its admission slot. Story 4.4
// owns any later retry/cancellation of that uncertain outcome.
let mut transaction = self.start().await?;
sqlx::query(
"with candidates as (
select task_id from tasks
where state = 'working' and lease_owner is not null
and current_attempt_id is not null
and lease_until < clock_timestamp()
order by task_id
limit 64
), resolved as (
update tasks
set state = 'outcome_unknown',
lease_owner = null,
lease_until = null,
version = version + 1,
updated_at = now()
where task_id in (select task_id from candidates)
and state = 'working'
returning task_id
)
delete from execution_admission_entries
where task_id in (select task_id from resolved)",
)
.execute(&mut *transaction)
.await
.map_err(Self::unavailable)?;
// A crash before the durable dispatch checkpoint left the Task queued for execution: its
// admission intent is re-armed as reserved and the Task becomes claimable again. Recovery is
// bounded by the <=30s lease expiry, inside the 60s story budget.
sqlx::query(
"with candidates as (
select task_id from tasks
where state = 'working' and lease_owner is not null
and current_attempt_id is null
and lease_until < clock_timestamp()
order by task_id
limit 64
), requeued as (
update tasks
set state = 'queued',
lease_owner = null,
lease_until = null,
version = version + 1,
updated_at = now()
where task_id in (select task_id from candidates)
and state = 'working'
returning task_id
)
update execution_admission_entries
set state = 'reserved', granted_at = null
where task_id in (select task_id from requeued) and state = 'executing'",
)
.execute(&mut *transaction)
.await
.map_err(Self::unavailable)?;
transaction.commit().await.map_err(Self::unavailable)?;
let mut leases = Vec::new();
for _ in 0..batch {
let mut transaction = self.start().await?;
let workspace_cursor =
match super::admission::lock_admission_in_tx(&mut transaction, "*").await {
Ok(cursor) => cursor,
Err(error) => {
transaction.rollback().await.ok();
return Err(TaskError::unavailable(format!("{error:?}")));
}
};
let (task_id, _updated_cursor) = match super::admission::grant_next_task(
&mut transaction,
"*",
&workspace_cursor,
&self.limits,
self.scheduler,
)
.await
{
Ok(value) => value,
Err(error) => {
transaction.rollback().await.ok();
return Err(TaskError::unavailable(format!("{error:?}")));
}
};
// Persist the updated controller cursor even when no task is granted.
let Some(task_id) = task_id else {
transaction.commit().await.map_err(Self::unavailable)?;
break;
};
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
"update tasks
set state = 'working',
lease_owner = $1,
lease_until = clock_timestamp() + ($2::bigint || ' milliseconds')::interval,
fence = fence + 1,
updated_at = now()
where task_id = $3
and (
(state = 'queued' and lease_owner is null)
or (state = 'working' and lease_owner is not null
and lease_until < clock_timestamp() and current_attempt_id is null)
)
returning {TASK_PROJECTION}"
)))
.bind(owner)
.bind(lease_ms)
.bind(task_id)
.fetch_optional(&mut *transaction)
.await
.map_err(Self::unavailable)?;
// Persist cursor update (grant_next_task already did it) regardless.
let Some(row) = row else {
transaction.rollback().await.ok();
break;
};
let record = record_from_row(&row).map_err(Self::unavailable)?;
leases.push(TaskLease {
owner: owner.to_owned(),
fence: record.fence,
lease_until: record.lease_until_unix_ms.unwrap_or_default(),
record,
});
transaction.commit().await.map_err(Self::unavailable)?;
}
Ok(leases)
}
async fn renew_lease(
&self,
owner: &str,
task_id: TaskId,
fence: u64,
lease_ms: i64,
) -> Result<TaskLease, TaskError> {
let mut transaction = self.start().await?;
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
"update tasks
set lease_until = clock_timestamp() + ($1::bigint || ' milliseconds')::interval,
updated_at = now()
where task_id = $2 and lease_owner = $3 and fence = $4
and lease_until > clock_timestamp()
returning {TASK_PROJECTION}"
)))
.bind(lease_ms)
.bind(task_id.as_uuid())
.bind(owner)
.bind(i64::try_from(fence).unwrap_or_default())
.fetch_optional(&mut *transaction)
.await
.map_err(Self::unavailable)?;
let Some(row) = row else {
transaction.rollback().await.ok();
return Err(TaskError::StateConflict);
};
let record = record_from_row(&row).map_err(Self::unavailable)?;
let lease = TaskLease {
owner: owner.to_owned(),
fence: record.fence,
lease_until: record.lease_until_unix_ms.unwrap_or_default(),
record,
};
transaction.commit().await.map_err(Self::unavailable)?;
Ok(lease)
}
async fn write_progress(
&self,
owner: &str,
task_id: TaskId,
fence: u64,
progress: TaskEnvelope,
) -> Result<TaskRecord, TaskError> {
let mut transaction = self.start().await?;
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
"update tasks
set progress_envelope = $1, updated_at = now()
where task_id = $2 and lease_owner = $3 and fence = $4
and lease_until > clock_timestamp()
returning {TASK_PROJECTION}"
)))
.bind(progress.value().clone())
.bind(task_id.as_uuid())
.bind(owner)
.bind(i64::try_from(fence).unwrap_or_default())
.fetch_optional(&mut *transaction)
.await
.map_err(Self::unavailable)?;
let Some(row) = row else {
transaction.rollback().await.ok();
return Err(TaskError::StateConflict);
};
let record = record_from_row(&row).map_err(Self::unavailable)?;
transaction.commit().await.map_err(Self::unavailable)?;
Ok(record)
}
async fn read_executable_input(
&self,
owner: &str,
task_id: TaskId,
fence: u64,
) -> Result<(String, String, i64), TaskError> {
let row = sqlx::query(
"select executable_input_ciphertext, executable_input_key_version, executable_input_master_key_epoch
from tasks
where task_id = $1 and state = 'working' and lease_owner = $2 and fence = $3
and lease_until > clock_timestamp()",
)
.bind(task_id.as_uuid())
.bind(owner)
.bind(i64::try_from(fence).unwrap_or_default())
.fetch_optional(&self.pool)
.await
.map_err(Self::unavailable)?;
let Some(row) = row else {
return Err(TaskError::StateConflict);
};
let ciphertext: Option<String> = row
.try_get("executable_input_ciphertext")
.map_err(Self::unavailable)?;
let key_version: Option<String> = row
.try_get("executable_input_key_version")
.map_err(Self::unavailable)?;
let epoch: Option<i64> = row
.try_get("executable_input_master_key_epoch")
.map_err(Self::unavailable)?;
if let Some(epoch) = epoch {
let active = sqlx::query_scalar::<_, i64>(
"select epoch from master_key_identities where status = 'active' order by epoch desc limit 1",
)
.fetch_optional(&self.pool)
.await
.map_err(Self::unavailable)?;
if let Some(active) = active {
if active != epoch {
return Err(TaskError::StateConflict);
}
}
}
match (ciphertext, key_version, epoch) {
(Some(ciphertext), Some(key_version), Some(epoch)) if !ciphertext.is_empty() => {
Ok((ciphertext, key_version, epoch))
}
_ => Err(TaskError::NotFound),
}
}
async fn checkpoint_dispatch(
&self,
owner: &str,
task_id: TaskId,
fence: u64,
attempt_id: String,
) -> Result<TaskRecord, TaskError> {
let mut transaction = self.start().await?;
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
"update tasks
set current_attempt_id = $1,
dispatch_started_at = now(),
attempts = attempts + 1,
updated_at = now()
where task_id = $2 and lease_owner = $3 and fence = $4
and lease_until > clock_timestamp() and current_attempt_id is null
returning {TASK_PROJECTION}"
)))
.bind(&attempt_id)
.bind(task_id.as_uuid())
.bind(owner)
.bind(i64::try_from(fence).unwrap_or_default())
.fetch_optional(&mut *transaction)
.await
.map_err(Self::unavailable)?;
let Some(row) = row else {
transaction.rollback().await.ok();
return Err(TaskError::StateConflict);
};
let record = record_from_row(&row).map_err(Self::unavailable)?;
transaction.commit().await.map_err(Self::unavailable)?;
Ok(record)
}
async fn finish_leased(
&self,
request: TaskFinishRequest,
owner: &str,
fence: u64,
) -> Result<TaskRecord, TaskError> {
request.validate()?;
let mut transaction = self.start().await?;
let access = &request.access;
let row = sqlx::query(sqlx::AssertSqlSafe(format!(
"update tasks
set state = $1,
result_envelope = $2,
error_envelope = $3,
version = version + 1,
updated_at = now(),
lease_owner = null,
lease_until = null
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
and lease_owner = $11 and fence = $12
and lease_until > clock_timestamp()
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))
.bind(owner)
.bind(i64::try_from(fence).unwrap_or_default())
.fetch_optional(&mut *transaction)
.await
.map_err(Self::unavailable)?;
let Some(row) = row else {
transaction.rollback().await.ok();
return Err(TaskError::StateConflict);
};
let record = record_from_row(&row).map_err(Self::unavailable)?;
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)
}
}
impl PostgresTaskStore {
@@ -377,11 +753,12 @@ impl PostgresTaskStore {
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
execution_deadline, retain_until, executable_input_ciphertext, executable_input_key_version,
executable_input_master_key_epoch, platform_api_key_id
) 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)
$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), $19, $20, $21, $22
)
returning (extract(epoch from created_at) * 1000)::bigint as created_ms",
)
@@ -403,6 +780,15 @@ impl PostgresTaskStore {
.bind(request.input.value().clone())
.bind(request.pins.execution_deadline_unix_ms)
.bind(request.pins.retain_until_unix_ms)
.bind(request.executable_input_ciphertext.as_deref())
.bind(request.executable_input_key_version.as_deref())
.bind(request.executable_input_master_key_epoch)
.bind(
request
.platform_api_key_id
.as_ref()
.map(PlatformApiKeyId::as_str),
)
.fetch_one(&mut **transaction)
.await
.map_err(task_sql_error)?
@@ -540,6 +926,10 @@ fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError>
authorization_scope: row
.try_get("authorization_scope")
.map_err(unavailable_row)?,
platform_api_key_id: row
.try_get::<Option<String>, _>("platform_api_key_id")
.map_err(unavailable_row)?
.map(PlatformApiKeyId::new),
operation_id: row.try_get("operation_id").map_err(unavailable_row)?,
input_fingerprint: row.try_get("input_fingerprint").map_err(unavailable_row)?,
pins: TaskPins {
@@ -574,6 +964,14 @@ fn record_from_row(row: &sqlx::postgres::PgRow) -> Result<TaskRecord, TaskError>
error: envelope("error_envelope")?,
attempts: u32::try_from(row.try_get::<i32, _>("attempts").map_err(unavailable_row)?)
.unwrap_or_default(),
fence: u64::try_from(row.try_get::<i64, _>("fence").map_err(unavailable_row)?)
.unwrap_or_default(),
lease_owner: row.try_get("lease_owner").map_err(unavailable_row)?,
lease_until_unix_ms: row.try_get("lease_until_ms").map_err(unavailable_row)?,
current_attempt_id: row.try_get("current_attempt_id").map_err(unavailable_row)?,
dispatch_started_at_unix_ms: row
.try_get("dispatch_started_at_ms")
.map_err(unavailable_row)?,
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)?,