feat(epic4): безопасные повторы и отмена durable Task (Story 4.4)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 20m46s
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 per-outbound attempt до отправки запроса, bounded retry/read,
server-owned verified writes, честный cancel/unknown, deadline/fencing,
additive schema v29. Staged renames task.rs/tasks.rs разложены на модули.

Includes disclosed cosmetic parity exception: единственная правка вне
принятой дельты — удалена лишняя пустая строка в конце
scripts/ci-story-checks.sh (EOF blank line); story-код не менялся.
This commit is contained in:
bsodfather committed 2026-10-30 12:21:57 +00:00
1 parent 8c02380762
commit a3057de51e
44 files changed
+4547 -815

No files matched your search

+321 -51
View File
@@ -24,9 +24,13 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tracing::{Instrument, Span, debug, warn};
use uuid::Uuid;
use crate::task_attempt::{
TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
TaskAttemptRefusal,
};
use crate::task_worker::TaskDispatchPermit;
use crate::{
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
AdapterResponse, ExecutionAuthorization, ExecutionRequestError, PreparedRequest, RuntimeError,
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
auth::apply_resolved_auth,
request_preparation::{adapter_prepared_request, validate_selected_body_variant},
@@ -36,6 +40,18 @@ use crate::{
},
};
/// How many outbound sends one prepared request may perform.
///
/// `Legacy` keeps the existing synchronous `tools/call` retry behaviour inside the transport loop.
/// `Single` performs exactly one send, because a durable Task attempt already has its own committed
/// checkpoint and resolution around every send; it carries the pinned attempt ordinal and budget so
/// the one `adapter_attempt` span still names the real durable attempt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SendMode {
Legacy,
Single { attempt: u32, max_attempts: u32 },
}
#[derive(Clone)]
pub struct RuntimeExecutor {
adapters: AdapterRegistry,
@@ -181,57 +197,273 @@ impl RuntimeExecutor {
&self,
request: RuntimeExecutionRequest<'_>,
) -> Result<(Value, Value), RuntimeError> {
self.execute_request_impl(request, None).await
self.execute_request_impl(request, None, SendMode::Legacy)
.await
}
/// Drives the bounded, durable retry budget of one leased background Task (Story 4.4).
///
/// Each outbound send is preceded by its own committed attempt checkpoint and followed by one
/// atomic resolution; the pinned budget, the safe-retry decision and the accepted absolute
/// deadline are enforced by PostgreSQL, so a restart or a second worker cannot extend them.
pub async fn execute_task_outcome(
&self,
request: RuntimeExecutionRequest<'_>,
permit: TaskDispatchPermit,
) -> Result<crank_core::ExecutionSuccess, crank_core::ExecutionFailure> {
let operation = request.operation().clone();
let operation_id = operation.operation_id.clone();
let operation_version = operation.operation_version;
let origin = request.origin();
let correlation = crank_core::CorrelationContext::new(
request.request_context().request_id.clone(),
request.request_context().trace_context.clone(),
context: &TaskAttemptContext,
authority: &dyn TaskAttemptAuthority,
) -> TaskAttemptOutcome {
let store = context.store().clone();
let lease = context.lease().clone();
let mut record = lease.record.clone();
loop {
if context.is_cancelled() || context.is_stopping() {
return TaskAttemptOutcome::Stopped;
}
let current_lease = crank_core::TaskLease {
record: record.clone(),
owner: lease.owner.clone(),
fence: lease.fence,
lease_until: lease.lease_until,
};
let plan = match authority.prepare_attempt(&current_lease).await {
Ok(plan) => plan,
Err(TaskAttemptRefusal::Stopped) => return TaskAttemptOutcome::Stopped,
Err(TaskAttemptRefusal::Failed { code }) => {
// A refused attempt never erases a proven ambiguity: if an earlier attempt of this
// Task may already have reached the upstream, the store keeps the Task in the
// non-terminal `outcome_unknown` instead of downgrading it to a plain failure.
return match store.refuse_attempt(&current_lease, &code).await {
Ok(record) if record.state == crank_core::TaskState::OutcomeUnknown => {
TaskAttemptOutcome::OutcomeUnknown
}
_ => TaskAttemptOutcome::Failed { code },
};
}
};
let attempt_id = format!("attempt-{}", Uuid::now_v7());
let begin = crank_core::BeginAttempt {
task_id: record.task_id,
owner: lease.owner.clone(),
fence: lease.fence,
expected_version: record.version,
attempt_id: attempt_id.clone(),
input_fingerprint: record.input_fingerprint.clone(),
upstream_key_digest: plan.upstream_key_digest.clone(),
retry_allowed: plan.retry_allowed,
};
let attempt = match store.checkpoint_dispatch(begin).await {
Ok(attempt) => attempt,
// Cancellation, lease loss or a concurrent lifecycle change: nothing was dispatched.
Err(crank_core::TaskError::StateConflict)
| Err(crank_core::TaskError::NotFound)
| Err(crank_core::TaskError::FingerprintConflict) => {
return TaskAttemptOutcome::Stopped;
}
// An unproven commit is never retried by guess: no outbound call without a proven
// durable checkpoint.
Err(error) => {
warn!(error = %error, "durable dispatch checkpoint failed; no outbound call");
return TaskAttemptOutcome::Stopped;
}
};
if context.is_stopping() {
let code = "shutdown_before_dispatch".to_owned();
// A stop that lands before the send is a proven failure of *this* attempt only: when
// an earlier attempt of the same Task already lost its confirmation, the store keeps
// the non-terminal `outcome_unknown` instead of downgrading it to a plain failure.
return match store
.resolve_attempt(
&attempt,
crank_core::AttemptOutcome::Failed {
error: bounded_attempt_error(
&code,
crank_core::AttemptPhase::BeforeDispatch,
),
retryable: false,
phase: crank_core::AttemptPhase::BeforeDispatch,
},
)
.await
{
Ok(crank_core::AttemptResolution::Unknown(_)) => {
TaskAttemptOutcome::OutcomeUnknown
}
_ => TaskAttemptOutcome::Failed { code },
};
}
if context.is_cancelled() {
let _ = store
.resolve_attempt(
&attempt,
crank_core::AttemptOutcome::Uncertain {
error: bounded_attempt_error(
"outcome_unknown",
crank_core::AttemptPhase::BeforeDispatch,
),
repeatable: false,
phase: crank_core::AttemptPhase::BeforeDispatch,
},
)
.await;
return TaskAttemptOutcome::OutcomeUnknown;
}
// Each attempt owns exactly one `adapter_attempt` span, created around the single send
// inside the transport loop so the accepted trace shape (durable attempt → runtime
// execution → adapter attempt) is preserved.
let result = self.execute_task_send(&plan, &attempt).await;
let (outcome, code) = self.classify_task_attempt(&plan, result);
match store.resolve_attempt(&attempt, outcome).await {
Ok(crank_core::AttemptResolution::Finished(task)) => {
return if task.state == crank_core::TaskState::Completed {
TaskAttemptOutcome::Completed
} else {
TaskAttemptOutcome::Failed {
code: code.unwrap_or_else(|| "task_failed".to_owned()),
}
};
}
Ok(crank_core::AttemptResolution::Unknown(_)) => {
return TaskAttemptOutcome::OutcomeUnknown;
}
Ok(crank_core::AttemptResolution::RetryAt {
task,
next_attempt_at_unix_ms,
}) => {
record = task;
let remaining =
next_attempt_at_unix_ms.saturating_sub(crank_core::current_unix_ms());
let delay = Duration::from_millis(u64::try_from(remaining).unwrap_or(0));
if !self.wait_before_attempt(context, delay).await {
return TaskAttemptOutcome::Stopped;
}
}
// A stale fence or version lost the resolution CAS: another writer owns the Task now.
Err(_) => return TaskAttemptOutcome::Stopped,
}
}
}
/// One outbound send of one committed durable attempt.
async fn execute_task_send(
&self,
plan: &TaskAttemptPlan,
attempt: &crank_core::AttemptLease,
) -> Result<Value, RuntimeError> {
let permit = TaskDispatchPermit::new(
attempt.attempt.task_id,
plan.operation.operation_id.as_str().to_owned(),
plan.operation.operation_version,
plan.workspace_id.as_str().to_owned(),
plan.agent_id.as_ref().map(|id| id.as_str().to_owned()),
attempt.attempt.owner.clone(),
attempt.attempt.fence,
attempt.attempt.attempt_id.clone(),
);
let request = match RuntimeExecutionRequest::try_new(
&plan.workspace_id,
plan.origin,
plan.agent_id.as_ref(),
&plan.operation,
&plan.input,
plan.authorization,
plan.resolved_auth.as_ref(),
&plan.request_context,
plan.deadline,
) {
Ok(request) => request,
Err(ExecutionRequestError::DeadlineElapsed) => {
return Err(RuntimeError::ExecutionDeadlineElapsed {
may_have_dispatched: false,
});
}
Err(_) => return Err(RuntimeError::InvalidExecutionRequest),
};
let (output, _preview) = self
.execute_request_impl(
request,
Some(permit),
SendMode::Single {
attempt: attempt.attempt.ordinal,
max_attempts: attempt.task.pins.retry.max_attempts,
},
)
.await?;
Ok(output)
}
// Validate permit binding before any adapter dispatch.
if permit.operation_id() != operation_id.as_str()
|| permit.operation_version() != operation_version
|| permit.workspace_id() != request.workspace_id().as_str()
|| permit.agent_id() != request.agent_id().map(|value| value.as_str())
{
return Err(crate::normalize_runtime_error_for_operation(
&RuntimeError::InvalidExecutionRequest,
&correlation,
&operation,
));
}
if !permit.consume() {
return Err(crate::normalize_runtime_error_for_operation(
&RuntimeError::InvalidExecutionRequest,
&correlation,
&operation,
));
/// Maps one outbound result of a durable attempt onto its persisted attempt outcome.
fn classify_task_attempt(
&self,
plan: &TaskAttemptPlan,
result: Result<Value, RuntimeError>,
) -> (crank_core::AttemptOutcome, Option<String>) {
match result {
Ok(output) => match crank_core::TaskEnvelope::try_redacted(&output) {
Ok(envelope) => (crank_core::AttemptOutcome::Completed(envelope), None),
Err(_) => {
let code = "result_not_redactable".to_owned();
(
crank_core::AttemptOutcome::Failed {
error: bounded_attempt_error(
&code,
crank_core::AttemptPhase::Dispatched,
),
retryable: false,
phase: crank_core::AttemptPhase::Dispatched,
},
Some(code),
)
}
},
Err(error) => {
let phase = if runtime_error_may_have_dispatched(&error) {
crank_core::AttemptPhase::Dispatched
} else {
crank_core::AttemptPhase::BeforeDispatch
};
let correlation = crank_core::CorrelationContext::new(
plan.request_context.request_id.clone(),
plan.request_context.trace_context.clone(),
);
let failure = crate::normalize_runtime_error_for_operation(
&error,
&correlation,
&plan.operation,
);
let code = format!("{:?}", failure.error_code());
let safe_to_repeat = retry_is_allowed(&plan.operation, &error, plan.retry_allowed);
let envelope = bounded_attempt_error(&code, phase);
let outcome = match failure.outcome_certainty() {
crank_core::OutcomeCertainty::OutcomeUnknown => {
crank_core::AttemptOutcome::Uncertain {
error: envelope,
repeatable: safe_to_repeat,
phase,
}
}
_ => crank_core::AttemptOutcome::Failed {
error: envelope,
retryable: safe_to_repeat,
phase,
},
};
(outcome, Some(code))
}
}
}
match self.execute_request_impl(request, Some(permit)).await {
Ok((output, request_preview)) => Ok(crank_core::ExecutionSuccess {
operation_id: operation_id.clone(),
operation_version,
origin,
correlation,
request_preview,
output,
}),
Err(error) => Err(crate::normalize_runtime_error_for_operation(
&error,
&correlation,
&operation,
)),
/// Bounded cooperative wait inside the pinned backoff window. The lease keeps being renewed by
/// the worker, so a durable cancellation or lease loss still stops the local work here.
async fn wait_before_attempt(&self, context: &TaskAttemptContext, delay: Duration) -> bool {
let deadline = Instant::now() + delay;
loop {
if context.is_cancelled() || context.is_stopping() {
return false;
}
let now = Instant::now();
if now >= deadline {
return true;
}
tokio::time::sleep((deadline - now).min(Duration::from_millis(50))).await;
}
}
@@ -239,6 +471,7 @@ impl RuntimeExecutor {
&self,
request: RuntimeExecutionRequest<'_>,
permit: Option<TaskDispatchPermit>,
send_mode: SendMode,
) -> Result<(Value, Value), RuntimeError> {
let operation = request.operation();
// Derive trusted dispatch from a present permit; a missing permit always uses ordinary admission.
@@ -320,6 +553,7 @@ impl RuntimeExecutor {
Some(request_context),
Arc::clone(&dispatch_started),
durable_attempt_id.as_deref(),
send_mode,
)
.await;
if let Some(lease) = lease.as_mut() {
@@ -415,6 +649,7 @@ impl RuntimeExecutor {
Ok(prepared)
}
#[allow(clippy::too_many_arguments)]
async fn execute_prepared(
&self,
operation: &RuntimeOperation,
@@ -423,6 +658,7 @@ impl RuntimeExecutor {
request_context: Option<&RuntimeRequestContext>,
dispatch_started: Arc<AtomicBool>,
durable_attempt_id: Option<&str>,
send_mode: SendMode,
) -> Result<Value, RuntimeError> {
let mut prepared_request = prepared_request;
let idempotency_applicable = crate::idempotency::policy(operation).is_some();
@@ -472,7 +708,11 @@ impl RuntimeExecutor {
approval_result?;
}
let idempotency = if idempotency_applicable {
// The synchronous coordination guard is the replay authority of one `tools/call`. A durable
// Task attempt already has a PostgreSQL attempt authority around every send, so the guard is
// skipped there: an ambiguous first response must not block the bounded durable retry. The
// stable idempotency key is still delivered to the upstream by `prepare_idempotency` above.
let idempotency = if idempotency_applicable && matches!(send_mode, SendMode::Legacy) {
let idempotency_span = Stage::RuntimeIdempotency.span();
let result = crate::idempotency::begin(
self.coordination_store.as_deref(),
@@ -540,6 +780,7 @@ impl RuntimeExecutor {
idempotency_key.as_deref(),
),
durable_attempt_id,
send_mode,
)
.await;
if let Ok(response) = &adapter_response {
@@ -673,6 +914,7 @@ impl RuntimeExecutor {
.map_err(|error| map_protocol_adapter_error(operation, error))
}
#[allow(clippy::too_many_arguments)]
async fn execute_adapter_with_retry(
&self,
operation: &RuntimeOperation,
@@ -681,20 +923,32 @@ impl RuntimeExecutor {
dispatch_started: Arc<AtomicBool>,
verified_idempotency: bool,
durable_attempt_id: Option<&str>,
send_mode: SendMode,
) -> Result<AdapterResponse, RuntimeError> {
let max_attempts = retry_attempts(operation);
let mut attempt = 1;
// `max_attempts` bounds the transport loop; `reported_max_attempts` is the pinned Task budget
// the attempt span names. A durable attempt performs exactly one send, so its transport loop
// always has a single iteration even when the Task may retry later.
let (max_attempts, first_attempt, reported_max_attempts) = match send_mode {
SendMode::Single {
attempt,
max_attempts,
} => (1, attempt, max_attempts),
SendMode::Legacy => {
let attempts = retry_attempts(operation);
(attempts, 1, attempts)
}
};
let mut attempt = first_attempt;
loop {
// Task dispatches reuse the durable Attempt ID committed by the dispatch checkpoint; the
// retry index discriminates the attempts inside it. Only paths without a durable attempt
// (synchronous tools/call) mint a synthetic per-attempt id.
// Task dispatches reuse the durable Attempt ID committed by the dispatch checkpoint. Only
// paths without a durable attempt (synchronous tools/call) mint a synthetic identity.
let attempt_id = durable_attempt_id
.map(str::to_owned)
.unwrap_or_else(|| format!("attempt-{}", Uuid::now_v7()));
let attempt_span = tracing::info_span!(
"adapter_attempt",
attempt,
max_attempts,
max_attempts = reported_max_attempts,
attempt_id = %attempt_id
);
let result = self
@@ -846,6 +1100,22 @@ fn sanitized_request_preview(prepared: &PreparedRequest) -> Value {
})
}
/// Bounded persisted error envelope of one durable attempt: a closed code and the attempt phase.
/// It never carries an upstream body, status text, URL or credential.
fn bounded_attempt_error(code: &str, phase: crank_core::AttemptPhase) -> crank_core::TaskEnvelope {
crank_core::TaskEnvelope::try_redacted(&json!({
"code": code,
"phase": phase.as_str(),
}))
.unwrap_or_else(|_| {
crank_core::TaskEnvelope::try_redacted(&json!({
"code": "task_error_not_recordable",
"phase": phase.as_str(),
}))
.expect("bounded attempt error envelope is always valid")
})
}
fn runtime_error_may_have_dispatched(error: &RuntimeError) -> bool {
matches!(
error,
+6 -2
View File
@@ -15,6 +15,7 @@ mod rate_limit;
mod request_context;
mod request_preparation;
mod response_cache;
mod task_attempt;
mod task_worker;
mod tasks;
pub fn validate_resource_template_parameter(
@@ -116,8 +117,11 @@ pub use rate_limit::{
};
pub use request_context::{MeteringContext, ResponseCacheScope, RuntimeRequestContext};
pub use secret_crypto::SecretCrypto;
pub use task_attempt::{
TaskAttemptAuthority, TaskAttemptContext, TaskAttemptOutcome, TaskAttemptPlan,
TaskAttemptRefusal,
};
pub use task_worker::{
TaskAttemptOutcome, TaskDispatchPermit, TaskHandler, TaskWorker, TaskWorkerConfig,
TaskWorkerError,
TaskDispatchPermit, TaskHandler, TaskWorker, TaskWorkerConfig, TaskWorkerError,
};
pub use tasks::{TaskAcceptDraft, TaskOutcome, TaskService};
+113
View File
@@ -0,0 +1,113 @@
//! Durable per-outbound attempt execution of one background Task (Story 4.4).
//!
//! The authoritative state of a Task stays in PostgreSQL. This module only carries the owned
//! execution plan of one attempt, the durable control (store + lease + cooperative stop) and the
//! bounded seam the application layer implements to revalidate authority before each attempt.
//! The single retry loop lives in [`crate::RuntimeExecutor::execute_task_outcome`]; there is no second
//! loop in the worker and no retry inside the transport adapter.
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Instant;
use async_trait::async_trait;
use crank_core::{AgentId, ExecutionOrigin, TaskLease, TaskStore, WorkspaceId};
use crate::{ExecutionAuthorization, ResolvedAuth, RuntimeOperation, RuntimeRequestContext};
/// Owned execution plan of one durable attempt.
///
/// It is rebuilt by the application through [`TaskAttemptAuthority::prepare_attempt`] before every
/// attempt, so a republished catalog, a revoked key or an elapsed deadline is revalidated between two
/// attempts instead of being trusted from the first one.
pub struct TaskAttemptPlan {
pub workspace_id: WorkspaceId,
pub origin: ExecutionOrigin,
pub agent_id: Option<AgentId>,
pub operation: RuntimeOperation,
pub input: serde_json::Value,
pub authorization: ExecutionAuthorization,
pub resolved_auth: Option<ResolvedAuth>,
pub request_context: RuntimeRequestContext,
/// Absolute deadline pinned at acceptance; never re-derived from a later publication.
pub deadline: Instant,
/// Safe-to-retry decision of this attempt: a read, or a write whose upstream idempotency is
/// backed by server-owned evidence. A client-supplied key or header never makes this true.
pub retry_allowed: bool,
/// Digest of the stable upstream idempotency key (never the raw key or a header value).
pub upstream_key_digest: Option<String>,
}
/// Application-owned seam: revalidate authority and prepare exactly one durable attempt.
#[async_trait]
pub trait TaskAttemptAuthority: Send + Sync {
async fn prepare_attempt(
&self,
lease: &TaskLease,
) -> Result<TaskAttemptPlan, TaskAttemptRefusal>;
}
/// Typed refusal of one attempt preparation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TaskAttemptRefusal {
/// Proven refusal before any dispatch of this attempt; the bounded code is persisted.
Failed { code: String },
/// Durable control changed (cancellation, lease loss, shutdown): write nothing new from here.
Stopped,
}
/// Durable control of one leased Task: the store, the leased record and cooperative stop signals.
#[derive(Clone)]
pub struct TaskAttemptContext {
pub(crate) store: Arc<dyn TaskStore>,
pub(crate) lease: TaskLease,
pub(crate) cancelled: Arc<AtomicBool>,
pub(crate) stopping: Arc<AtomicBool>,
}
impl TaskAttemptContext {
pub(crate) fn new(
store: Arc<dyn TaskStore>,
lease: TaskLease,
cancelled: Arc<AtomicBool>,
stopping: Arc<AtomicBool>,
) -> Self {
Self {
store,
lease,
cancelled,
stopping,
}
}
pub fn store(&self) -> &Arc<dyn TaskStore> {
&self.store
}
pub fn lease(&self) -> &TaskLease {
&self.lease
}
/// Cooperative stop: the lease renewal or an observed durable cancellation set this flag.
pub fn is_cancelled(&self) -> bool {
self.cancelled.load(std::sync::atomic::Ordering::Acquire)
}
/// Process shutdown was requested: no new outbound send may start after the current checkpoint.
pub fn is_stopping(&self) -> bool {
self.stopping.load(std::sync::atomic::Ordering::Acquire)
}
}
/// Result of driving the whole pinned retry budget of one leased Task.
#[derive(Clone, Debug, PartialEq)]
pub enum TaskAttemptOutcome {
/// The Task committed `completed` (exactly one terminal write).
Completed,
/// The Task committed `failed` without dispatch or with a proven failure.
Failed { code: String },
/// The Task is non-terminal `outcome_unknown`; it is never retried or cancelled generically.
OutcomeUnknown,
/// Nothing new was written by this worker: cancellation, lease loss or an unavailable store.
Stopped,
}
+39 -194
View File
@@ -11,12 +11,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use async_trait::async_trait;
use crank_core::{TaskEnvelope, TaskError, TaskFinishRequest, TaskLease, TaskState, TaskStore};
use crank_core::{TaskError, TaskLease, TaskStore};
use tokio::sync::watch;
use tokio::task::JoinSet;
use tracing::{Instrument, debug, warn};
use uuid::Uuid;
use crate::task_attempt::{TaskAttemptContext, TaskAttemptOutcome};
/// Configuration for [`TaskWorker`]. Durations are capped by the caller to story timing budgets.
#[derive(Clone, Debug)]
pub struct TaskWorkerConfig {
@@ -50,29 +52,16 @@ impl Default for TaskWorkerConfig {
}
}
/// Result of one durable Task attempt produced by the application layer.
#[derive(Clone, Debug)]
pub enum TaskAttemptOutcome {
Completed(serde_json::Value),
Failed(serde_json::Value),
OutcomeUnknown,
}
/// Application-owned seam for pre-dispatch revalidation and execution.
///
/// The worker owns lease renewal/CAS/fencing and the dispatch checkpoint. The handler only
/// receives the leased record and attempt identity; it must not trust `TaskRecord.input` as
/// The worker owns lease renewal/CAS/fencing and passes a durable [`TaskAttemptContext`]. The
/// application implements [`crate::TaskAttemptAuthority`] and drives the pinned retry budget through
/// [`crate::RuntimeExecutor::execute_task_outcome`]; it must not trust `TaskRecord.input` as
/// executable payload.
#[async_trait]
pub trait TaskHandler: Send + Sync {
async fn revalidate(&self, lease: &TaskLease) -> Result<(), TaskWorkerError>;
async fn execute(
&self,
lease: &TaskLease,
attempt_id: &str,
cancelled: Arc<AtomicBool>,
permit: TaskDispatchPermit,
) -> TaskAttemptOutcome;
async fn execute(&self, context: TaskAttemptContext) -> TaskAttemptOutcome;
}
/// Sealed, single-use trusted dispatch permit created by [`TaskWorker`] after a durable lease and
@@ -91,6 +80,7 @@ pub struct TaskDispatchPermit {
}
impl TaskDispatchPermit {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
task_id: crank_core::TaskId,
operation_id: String,
@@ -244,10 +234,10 @@ impl TaskWorker {
if self.stopping.load(Ordering::Acquire) {
break;
}
if let Some(rx) = shutdown.as_mut() {
if *rx.borrow() {
break;
}
if let Some(rx) = shutdown.as_mut()
&& *rx.borrow()
{
break;
}
// Reap finished attempts before claiming more.
@@ -344,15 +334,7 @@ async fn process_lease(
return;
}
debug!(task_id = %task_id, error = %error, "task revalidation failed; finishing without dispatch");
finish_failed(
&store,
&owner,
task_id,
fence,
&lease,
"revalidation_failed",
)
.await;
finish_failed(&store, &lease, "revalidation_failed").await;
return;
}
if stopping.load(Ordering::Acquire) {
@@ -364,49 +346,8 @@ async fn process_lease(
let attempt_id = format!("attempt-{}", Uuid::now_v7());
// Durable checkpoint before any network use.
if store
.checkpoint_dispatch(&owner, task_id, fence, attempt_id.clone())
.await
.is_err()
{
// Lease lost or checkpoint rejected: do not dispatch.
cancelled.store(true, Ordering::Release);
return;
}
if stopping.load(Ordering::Acquire) {
// The checkpoint is durable, but we know the outbound callback has not started.
finish_failed(
&store,
&owner,
task_id,
fence,
&lease,
"shutdown_before_dispatch",
)
.await;
return;
}
// Sealed single-use permit for the trusted runtime dispatch bridge. It is created only after
// the current lease and durable checkpoint above.
let agent_id = if lease.record.owner_kind == crank_core::TaskOwnerKind::Agent {
Some(lease.record.owner_id.clone())
} else {
None
};
let permit = TaskDispatchPermit::new(
lease.record.task_id,
lease.record.operation_id.clone(),
lease.record.pins.operation_version,
lease.record.workspace_id.clone(),
agent_id,
owner.clone(),
fence,
attempt_id.clone(),
);
// Background lease renewal while the attempt runs.
// Background lease renewal covers the whole bounded retry budget, including the pinned backoff.
// A durable cancellation clears the lease, so the next renewal fails and the local work stops.
let renewal_store = store.clone();
let renewal_owner = owner.clone();
let renewal_cancelled = cancelled.clone();
@@ -435,139 +376,43 @@ async fn process_lease(
}
});
// Each dispatch gets a child span carrying the durable attempt identity, rooted in the parent
// trace persisted with the accepted Task (never a mutable queue/cache projection).
let span = tracing::info_span!("durable_task_attempt", task_id = %task_id, attempt_id = %attempt_id, fence);
// The parent span names the leased Task generation; every individual outbound attempt adds its own
// `adapter_attempt` child span with the durable attempt ID committed by its checkpoint.
let span = tracing::info_span!("durable_task_attempt", task_id = %task_id, lease_ref = %attempt_id, fence);
if let Ok(parent) = crank_core::TraceContext::parse(&lease.record.support.traceparent) {
crank_trace::set_parent_from_trace_context(&span, &parent);
}
let outcome = handler
.execute(&lease, &attempt_id, cancelled.clone(), permit)
.instrument(span)
.await;
// Every durable write of this Task (checkpoint, attempt resolution, terminal state) happens inside
// the executor's single retry loop under this lease/fence; the worker only renews and stops.
let context = TaskAttemptContext::new(
store.clone(),
lease.clone(),
cancelled.clone(),
stopping.clone(),
);
let outcome = handler.execute(context).instrument(span).await;
cancelled.store(true, Ordering::Release);
renewal_handle.abort();
// Terminal CAS under valid lease. Only one writer wins; stale token is rejected by store.
let access = crank_core::TaskAccess {
workspace_id: lease.record.workspace_id.clone(),
owner_kind: lease.record.owner_kind,
owner_id: lease.record.owner_id.clone(),
authorization_scope: lease.record.authorization_scope.clone(),
};
match outcome {
TaskAttemptOutcome::Completed(value) => {
let Ok(result) = TaskEnvelope::try_redacted(&value) else {
finish_failed(
&store,
&owner,
task_id,
fence,
&lease,
"result_not_redactable",
)
.await;
return;
};
let _ = store
.finish_leased(
TaskFinishRequest {
access,
task_id,
expected_state: leased_expected_state(&lease),
expected_version: lease.record.version,
target_state: TaskState::Completed,
result: Some(result),
error: None,
},
&owner,
fence,
)
.await;
TaskAttemptOutcome::Completed => {
debug!(task_id = %task_id, "durable task completed");
}
TaskAttemptOutcome::Failed(value) => {
let error = TaskEnvelope::try_redacted(&value).or_else(|_| {
TaskEnvelope::try_redacted(&serde_json::json!({
"code": "task_error_not_redactable"
}))
});
let Ok(error) = error else {
return;
};
let _ = store
.finish_leased(
TaskFinishRequest {
access,
task_id,
expected_state: leased_expected_state(&lease),
expected_version: lease.record.version,
target_state: TaskState::Failed,
result: None,
error: Some(error),
},
&owner,
fence,
)
.await;
TaskAttemptOutcome::Failed { code } => {
debug!(task_id = %task_id, code = %code, "durable task failed");
}
TaskAttemptOutcome::OutcomeUnknown => {
let _ = store
.finish_leased(
TaskFinishRequest {
access,
task_id,
expected_state: leased_expected_state(&lease),
expected_version: lease.record.version,
target_state: TaskState::OutcomeUnknown,
result: None,
error: None,
},
&owner,
fence,
)
.await;
warn!(task_id = %task_id, "durable task outcome is uncertain; no automatic retry");
}
TaskAttemptOutcome::Stopped => {
debug!(task_id = %task_id, "durable task attempt stopped without a new outcome");
}
}
}
fn leased_expected_state(lease: &TaskLease) -> TaskState {
// Claimed tasks are expected to be in a non-terminal processing state.
if lease.record.state == TaskState::Queued {
TaskState::Queued
} else {
TaskState::Working
}
}
async fn finish_failed(
store: &Arc<dyn TaskStore>,
owner: &str,
task_id: crank_core::TaskId,
fence: u64,
lease: &TaskLease,
code: &str,
) {
let access = crank_core::TaskAccess {
workspace_id: lease.record.workspace_id.clone(),
owner_kind: lease.record.owner_kind,
owner_id: lease.record.owner_id.clone(),
authorization_scope: lease.record.authorization_scope.clone(),
};
let _ = store
.finish_leased(
TaskFinishRequest {
access,
task_id,
expected_state: leased_expected_state(lease),
expected_version: lease.record.version,
target_state: TaskState::Failed,
result: None,
error: TaskEnvelope::try_redacted(&serde_json::json!({ "code": code })).ok(),
},
owner,
fence,
)
.await;
async fn finish_failed(store: &Arc<dyn TaskStore>, lease: &TaskLease, code: &str) {
// The store owns the fate of a refused pre-dispatch attempt: a Task that already carries a proven
// ambiguity still ends `outcome_unknown`, never a plain failure (Story 4.4).
let _ = store.refuse_attempt(lease, code).await;
}
+33
View File
@@ -47,6 +47,8 @@ pub struct TaskAcceptDraft {
/// Retention after the execution deadline.
pub retention_ms: i64,
pub approval_reference: Option<String>,
/// Bounded retry snapshot pinned from the exact published operation at acceptance.
pub retry: crank_core::TaskRetryPolicy,
}
/// Projection of the durable status/result read. `result`/`error` are only present once a terminal
@@ -161,6 +163,7 @@ impl TaskService {
execution_deadline_unix_ms,
retain_until_unix_ms: execution_deadline_unix_ms.saturating_add(retention_ms),
approval_reference: draft.approval_reference,
retry: draft.retry,
},
scoped_key,
input_fingerprint,
@@ -196,6 +199,35 @@ impl TaskService {
))
}
/// Owner-scoped cancellation of one accepted Task. The store decides under a row lock whether the
/// Task can still be cancelled or whether an already checkpointed attempt makes the outcome
/// uncertain; the service only carries the request and a bounded reason.
pub async fn cancel(
&self,
access: &TaskAccess,
task_id: TaskId,
expected_version: Option<u32>,
reason: &str,
) -> Result<crank_core::TaskCancelOutcome, TaskError> {
let request = crank_core::TaskCancelRequest {
access: access.clone(),
task_id,
expected_version,
reason: reason.to_owned(),
};
request.validate()?;
self.store.cancel(request).await
}
/// Bounded owner-scoped attempt history of one Task.
pub async fn attempts(
&self,
access: &TaskAccess,
task_id: TaskId,
) -> Result<Vec<crank_core::TaskAttempt>, TaskError> {
self.store.attempts(access, task_id).await
}
/// Decrypts and validates the executable input bound to a valid current lease.
pub async fn executable_input(
&self,
@@ -383,6 +415,7 @@ mod tests {
deadline: Instant::now() + std::time::Duration::from_secs(30),
retention_ms: TASK_DEFAULT_RETENTION_MS,
approval_reference: None,
retry: crank_core::TaskRetryPolicy::single_attempt(),
}
}