CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 21m42s
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
Durable worker приостанавливает Task как input_required до dispatch, если закреплённая схема требует отсутствующее поле; authorized schema-validated update атомарно и с аудитом возобновляет тот же Task ровно один раз. Replay/conflict/TTL безопасны, ожидание удерживает admission permit. Additive schema v30: task_input_requests, fingerprint/version, TTL-индекс.
197 lines
8.3 KiB
Rust
197 lines
8.3 KiB
Rust
//! Acceptance half of the PostgreSQL Task store (Story 4.2/4.3): the one-transaction acceptance
|
|
//! path, its bounded unique-conflict reread and the typed miss classification.
|
|
|
|
use crank_core::{
|
|
AdmissionMode, AdmissionRequest, AdmissionScope, ApprovalEvidence, NoTasksFallback,
|
|
PlatformApiKeyId, TaskAcceptRequest, TaskAcceptance, TaskError, TaskFinishRequest, TaskState,
|
|
};
|
|
use sqlx::{Postgres, Row, Transaction};
|
|
|
|
use super::super::admission::{
|
|
AttemptError, bounded_queue_len, cleanup_expired_unlinked, insert_admission_entry,
|
|
lock_admission_in_tx,
|
|
};
|
|
use super::{
|
|
Accepted, PostgresTaskStore, TASK_PROJECTION, acceptance_from_record, policy_mode_str,
|
|
record_from_row, task_sql_error,
|
|
};
|
|
|
|
impl PostgresTaskStore {
|
|
pub(super) 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, effective_input_fingerprint,
|
|
request_id, trace_id, traceparent,
|
|
trace_sampled, policy_mode, approval_reference, state, input_envelope,
|
|
execution_deadline, retain_until, executable_input_ciphertext, executable_input_key_version,
|
|
executable_input_master_key_epoch, platform_api_key_id, max_attempts, retry_backoff_step_ms
|
|
) values (
|
|
$1, $2, $3, $4, $5, $6, $7, $8, $9, $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, $23, $24
|
|
)
|
|
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)
|
|
.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),
|
|
)
|
|
.bind(i32::try_from(request.pins.retry.max_attempts).unwrap_or(1))
|
|
.bind(request.pins.retry.backoff_step_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.
|
|
pub(super) 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.
|
|
pub(super) 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),
|
|
}
|
|
}
|
|
}
|